Тёмный

"Don't Use Fields in C#! Use Properties Instead" | Code Cop  

Nick Chapsas
Подписаться 293 тыс.
Просмотров 94 тыс.
50% 1

Use code TDD20 and get 20% off the brand new Test-Driven Development course on Dometrain: dometrain.com/course/from-zer...
Become a Patreon and get special perks: / nickchapsas
Hello everybody, I'm Nick, and in this episode of Code Cop we'll take a look at some really insane advice that says that you shouldn't use fields in your C# classes, but instead private properties.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasGitHub
Follow me on Twitter: bit.ly/ChapsasTwitter
Connect on LinkedIn: bit.ly/ChapsasLinkedIn
Keep coding merch: keepcoding.shop
#csharp #dotnet

Опубликовано:

 

8 окт 2023

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 444   
@Ba_Dashi
@Ba_Dashi 8 месяцев назад
At this point I feel like people post bs on social media just for the interactions, positive or not. They didn't intend to educate, they intended to cause controversy.
@ddrsdiego
@ddrsdiego 8 месяцев назад
It's a point of view, but I believe that these people go around putting up these absurdities to get the title of MVP.
@BlackDub21
@BlackDub21 8 месяцев назад
Well its their job getting paid off view so they gotta bait the clicks 😂 i hate tech influencers
@verzivull
@verzivull 8 месяцев назад
can it be an advice from chatgpt?
@envo2199
@envo2199 8 месяцев назад
its called rage bait posting.
@amirhosseinahmadi3706
@amirhosseinahmadi3706 8 месяцев назад
Rule #1: Never take advice from someone who calls fields "class member variables".
@Z3rgatul
@Z3rgatul 8 месяцев назад
Good one 🤣
@EdKolis
@EdKolis 7 месяцев назад
I remember a series of otherwise decent C# tutorials on RU-vid that insisted on calling fields "attributes". Yeah, that's totally not going to get confusing later...
@user-ji2yk7wu4n
@user-ji2yk7wu4n 7 месяцев назад
😂😂
@MrMatthewLayton
@MrMatthewLayton 5 месяцев назад
"class" + "member variables" I would consider to be redundant (it's like saying "general consensus"), but I don't have a problem with "member variables" or "fields" to mean the same thing. Indeed, "member variables" balances nicely with "local variables".
@samsim4648
@samsim4648 8 месяцев назад
I have a feeling that they read a textbook reasoning for using public properties vs public fields and confused it with the reasoning for property vs field in general.
@minhhieugma
@minhhieugma 8 месяцев назад
they will have a better position to protect their idea if it is a public one. But here in this context, we are talking about the private scope. Imagining when you have to talk to your "higher position" about this. I feel hopeless
@justindoyle8091
@justindoyle8091 8 месяцев назад
That's exactly what I thought. Some of the listed advantages only make sense when you're thinking about choosing public properties over public fields (which is a good idea). Mocking for example.
@slowjocrow6451
@slowjocrow6451 8 месяцев назад
Noob question, but when is it appropriate to use a public field? I find myself only using public properties or private fields, I don't know when I should be using a public field
@RiversJ
@RiversJ 8 месяцев назад
@slowjocrow6451 For data struct members, one often doesn't want even the minuscule indirection of a property when doing high performance data processing.
@PlerbyMcFlerb
@PlerbyMcFlerb 8 месяцев назад
@@slowjocrow6451idiomatic c# doesn’t use public fields, only public properties. Edit: riversj makes a good point,but depending on your domain you might never be in that niche scenario
@GufNZ
@GufNZ 8 месяцев назад
Rider & R# have options to provide extra colourisation based on semantics, which means you can define a different colour for a field so don't need to use an _ to make that visible. It also lets you immediately tell the difference between a parameter, a local var that's only assigned once or a more frequently mutated local var; or a normal class, a static class or a record etc, and similarly for static vs normal methods etc.
@neralem
@neralem 8 месяцев назад
Yeah but I dont think one should rely on everyone who will ever read this code to have such an IDE and setup
@joshuawillis7874
@joshuawillis7874 8 месяцев назад
You should *always* use an underscore prefix for intellisense. At a lower level, it's the standard way for expressing intent.
@qtxsystems
@qtxsystems 8 месяцев назад
I actually recall seeing this in a Fowler / Martin book on clean code. It escapes me why they recommended using a private getter, but I think the reasoning was improved readability in the "NameYourVariablesSomethingVeryDescriptive" category, and that they claimed that IDEs are so powerful now you don't need the underscore to tell you it's a private variable. Either way, this certainly isn't a hill I'd want to die on and it boils down to developer choice.
@EldenFiend
@EldenFiend 8 месяцев назад
I think this is the answer. I had this conversation more or less a month ago with friends from work. I don't see a need for the underscore but I don't dislike it either. It's visual preference.
@CZProtton
@CZProtton 8 месяцев назад
How does that improve readability at all? I dont get it...
@MostlyPennyCat
@MostlyPennyCat 8 месяцев назад
​@@CZProtton Because then you start with an auto property, single line of code? Only expanding it if and when you need more than just a property with a hidden backing variable
@jeffmccloud905
@jeffmccloud905 8 месяцев назад
Without an underscore, a camelCase variable will resemble an argument. To differentiate them, you should add "this." on the field. But adding "this." is not enforced by the compiler, but the underscore is (of course, since it's part of the variable name). Ergo, the underscore is better for private fields.
@vd3598
@vd3598 8 месяцев назад
IDEs are powerful now for sure, but we often read code not in IDE, e.g. in a web interface during PR review. Or maybe you want to access some private fields, start typing with _ and LSP will show you the list of them so you don't need to remember the exact name. This makes life a bit easier. But m_* convention is ugly though :)
@jamesroot9777
@jamesroot9777 8 месяцев назад
The 9 points just look like something ChatGPT would generate.
@AlFasGD
@AlFasGD 8 месяцев назад
From my experience with ChatGPT, it would be smarter than those stupid ideas and arguments against fields.
@ferd1775
@ferd1775 8 месяцев назад
@@AlFasGD I agree, but I think they asked it to generate an article arguing FOR it..cus it will do that haha
@baetz2
@baetz2 8 месяцев назад
​@@AlFasGDit is smart, when you're smart. Sometimes you can make it write something stupid, sometimes it does so by itself, and you need to be smart enough to discard it.
@benjamininkorea7016
@benjamininkorea7016 8 месяцев назад
More and more, they might actually be so.
@neralem
@neralem 8 месяцев назад
Sometimes I temporarily change private fields to private auto properties so I can put a breakpoint in the setter. But I prefer private members to be fields too.
@alfflasymphonyx
@alfflasymphonyx 8 месяцев назад
I got fooled by your avatar! I really thought I had a fly on my screen.🤣🤣🤣
@sealsharp
@sealsharp 8 месяцев назад
@@alfflasymphonyx Me too. You got me.
@joergw
@joergw 8 месяцев назад
I am using private readonly fields without underscore - 100% agree with Nick 🙂
@dr_Bats
@dr_Bats 8 месяцев назад
I hate underscores. I use this to access class private members. Thanks Nick for agreeing with me. 😄
@massimoandreasibassi7016
@massimoandreasibassi7016 8 месяцев назад
We (Eight Sleep) have a "zero clutter" rule, we don't use _ or even "private": never had a readability issue because if something is came-case it's either from your current method or a private class field.
@TazG2000
@TazG2000 8 месяцев назад
This could be somewhat defensible if it means to only access fields within properties, in case you need to add lazy loading or something later. But it's hard to justify a sweeping change only to simplify a refactoring that is already simple, and that may never happen. The point about mocking may be that you can make properties virtual and override the return values for testing. This works, but the simpler advice would be to let them be injected.
@JohnWII
@JohnWII 8 месяцев назад
While I don't agree with all the hilarious benefits that tip creator was claiming. I still prefer private properties for a number of reasons. 1. Why not? you're making this sound like some new outlandish idea - guessing this is just for the views? 2. Nothing wrong with future proofing in case you do need to add some logic to the getter later if required. 3. IDE's love properties. "Oh no, what's setting my private field, sure wish I could just put a breakpoint in it like I can with a property". "Gee whiz, it sure would be nice to tell at a glance if there are any usages of my private field in this class and what they are like I can with properties". You're completely throwing out the whole dx because you view it as more correct to have a private field? Come on man, there's no "actual" downside but there are arguably a couple gains. The original image is definitely way off base on the why, but I'll personally still continue using private properties.
@BearJewOo
@BearJewOo 8 месяцев назад
We switched our codebase to this approach as soon as get-only properties released. I agree that the original author reasoning is dogsheesh. We switched mostly for constructor arguments: 1. they have a tendency to change from private to say public, just change mod 2. improved readability 3. no need for readonly, sometimes devs forget it 4. you see pascal-case you know it came from constructor. 5. having accessor method does not affect performance 6. R# helps create property from argument, code coloring also helps 7. code style consistency, public properties, private properties (injected, state from outside), fields (impl details)
@JinnFletch
@JinnFletch 8 месяцев назад
Purely feedback on your points to play the other side of the debate. 1. A (if not the) major reason devs expand accessibility is because they find their code is coupled and they want to break the Law of Demeter instead of following best practices. 2. This can't be more subjective. "The Industry" vastly agrees that _thisStyle is more understandable for what it represents. 3. Sometimes devs forget to remove the "set;". Also, "readonly" explicitly says what is happening. A property with only a getter has to be understood. Though as of C#9, you can use "get; init;" which also becomes more explicit. This doesn't change the rest of the points though. 4. Same as #2. We would certainly hope we know PascalCase means it is a class member and not within the function scope. But most of the industry would see PascalCase as a property that might change state. 5. An empty accessor method may not measurably affect performance, but the assertion with some of the "benefits" of the OP is that the accessor method would be abused. 6. I cringe whenever somebody changes their Software Engineering principles to suit a random tool. 7. Nobody can argue with Company Standards. They're up to you and your architects. But this would not match "code style consistency" with the rest of the industry. As for { get; init; } (Which is not part of this OP), that is mainly for records; AKA Structs, Models, DTO's, POCOs. This video and all of the replies so far are talking about interfaces as class members. So those are talking about Services, not Models, and it is irrelevant.
@BearJewOo
@BearJewOo 8 месяцев назад
​@@JinnFletch You are absolutely right, both semantically and technically. But I was not talking about "your fancy nanoservice SOLID YAGNI KISS etc code", I was talking about "everyone else's gigaservice WTF LOL WUT code". And in large classes readability matters. As well as debugging. Like you can put a breakpoint on a setter, find all references of a setter or getter. I personally dislike that underscore-snake-camel naming, still I use it to be consistent with the rest of industry which uses it for private members only, no one exposes this naming. So why be consistent? And of course there is just no such thing as "The industry". I'd rather call it crab bucket.
@MarkAdamson-Eddie
@MarkAdamson-Eddie 8 месяцев назад
I think for the validation aspect they meant in an init block, which is nicer than cluttering up the constructor in my opinion. Though we'll need a different solution for primary constructors on classes I don't think you've understood how they and we implement lazy loading, it would be with a Lazy field as you say but then an expression bodied property returning the .value. we have used this before though sometimes there is a better overall design.
@Integer0
@Integer0 8 месяцев назад
At least one of the reasons given by the author of the post is correct. 7. In the case of a property, it is easier to debug what code changes the value of this property. But you're right that the rest of the reasons make no sense.
@asteinerd
@asteinerd 8 месяцев назад
"bullshit" - perfectly delivered feedback. CLEARLY this person has no idea what a property and field do at the lower-level. It's not JUST syntax sugar; it transposes the accessors at the lowered-level; and properties re-invoke every time they're called just like a method, so it's just more and more potential allocation; far more than a field FOR SURE.
@isnotnull
@isnotnull 8 месяцев назад
Not sure. For auto properties an optimization should work which uses the field directly without get/set method
@raldotromp
@raldotromp 8 месяцев назад
So glad to see you'll be speaking at Techorama Netherlands. I'm looking forward to attend your talk. See you at Techorama. Love the content. Keep it up.
@VeggehGaming
@VeggehGaming 8 месяцев назад
I can't say that the underscores are a bad thing. It's less "pretty" but it's useful to know at a glance when I'm accessing a private variable. And I like adhering to standards for when other developers need to see my code so they are more likely to know what's happening at a glance too.
@brianviktor8212
@brianviktor8212 8 месяцев назад
I like underscores in private field names. It highlights them as what they are, and I immediately know how to handle them.
@dantecavallin8229
@dantecavallin8229 8 месяцев назад
I always interpreted it as supposed to be ugly so that you ignore it when skimming the code. As you usually look for properties or public members when skimming code.
@qj0n
@qj0n 8 месяцев назад
@@dantecavallin8229 this is exactly how it was designed in python, where everything is public, underscore just suggest not to use it
@brianviktor8212
@brianviktor8212 8 месяцев назад
@@dantecavallin8229 True. They look different and like something you wouldn't want to expose to others (consumers of your library). And I like marking them as such... or "uglify" them.
@MrOudoum
@MrOudoum 8 месяцев назад
@@brianviktor8212 I do the underscore only for backing fields if I need them for a property.
@mrShot94
@mrShot94 8 месяцев назад
With debugging I think they met that if you have `set;` or `get;` then you can create a breakpoint exactly on those things. You do not need to declare body. This way you can put breakpoint when data is modified/accessed.
@LeutnantJoker
@LeutnantJoker 8 месяцев назад
That's what break on value change can already do. It just shows the person has no clue how to use a debugger
@joshman1019
@joshman1019 8 месяцев назад
In my opinion, if you are performing complex logic when getting or setting a field, then that should be the job of a well named helper method or extension method. Because in the calling code, merely “getting” a value doesn’t necessarily tell the reader what is happening to that value before it is being delivered to the caller. So if you had a variable called appleNames and your getter logic returns the list as an alphabetical list, then you should have created a private method called GetAppleNamesAscending() paired with a field. That way your code doesn’t look like it is doing magic. Every time you have magic, it takes a few seconds, up to a few hours, to understand what’s going on. Multiply that by hundreds of these little magical code references and you’ll have a mess on your hands.
@proosee
@proosee 8 месяцев назад
Once I worked in a project that was using camel case for fields and was enforcing "this." and although I initially thought it is weird then in the end I think it is very expressive. In the end, it doesn't matter much, you just need common convention within the team and that's it - whatever you agree on is fine. About the main topic: it's probably not even worth commenting... but it's a bit surprising that AI can come up with such gibberish while having entire SO as its source.
@ferd1775
@ferd1775 8 месяцев назад
I'd bet my bottom dollar that someone asked chatgpt(Edit: chargpt to chatgpt; typo) to write an article SUPPORTING this, and they published that crap 😂😂😂
@peanutcelery
@peanutcelery 8 месяцев назад
I bet they use the 9 reasons from chat gpt
@chlorobyte_projects
@chlorobyte_projects 8 месяцев назад
It actually sounds like ChatGPT. No way a human unironically wrote "9. Mocking and Testing: Simplify testing and mocking." as an argument for properties
@christophbornhardt7888
@christophbornhardt7888 8 месяцев назад
f... each comment makes it sound more and more like chatgpt
@ferd1775
@ferd1775 8 месяцев назад
But don't worry, they're going to write a followup article about how bad chatgpt because of the feedback it's recieved....which is also biased and bullshit hahahah
@vargonian
@vargonian 8 месяцев назад
I'm one of those people who was trained with the default StyleCop rules ages ago which enforced that you prefix fields with "this.". To be honest, I was a monster who did that in C++ as well because I thought it was clearer (well, "this->" in that case.). I'm finally warming up to the underscore prefix.
@OnnoInvernizzi
@OnnoInvernizzi 7 месяцев назад
Same here. Everything that belongs to the class starts with this. If it starts with a lower case, it's a field. If it starts with an upper case it's a property. If it ends with ( then, it's a method. If the call doesn't start with this, then it's static. The fact that this advice starts with saying that it's nice to have no underscores shows this writer could not think outside a convention and may not even know about the StyleCop way.
@denissmith8282
@denissmith8282 3 месяца назад
Nick, properties ain't always about encapsulation, but, in general, about adding a level of indirection, another layer of abstraction. From this perspective private properties are absolutely fine.
@DaneWithADrone
@DaneWithADrone 8 месяцев назад
I totally agree with you Nick. I just have an issue with the underscore which i dont prefer. I tend to use "this." in the constructor for e.g. DI
@I69420H
@I69420H 8 месяцев назад
because I'm an autocrat sure.. but here is my answer. Code should be self documenting, Fullstop. Herewith the same and some good advice. I prefer the concept of having "all" interfaces implement either ITransientDependency, IScopedDependency or ISingletonDependency interfaces. These "By Convention" interfaces does not implement any code however they have beautiful purpose. Other than auto registration, when looking at a class I can clearly see what lifetime scope I'm working with without browsing to some arbitrary improperly named builder extension class. Another example of self documenting code supplementary to understanding why an underscore should exist for fields. People are lazy and don't respect their code, reminds me of people camping in a beautful forest and leaving their trash behind. Yes the camp was a success, but not for the next person wanting to enjoy it. Here is the golden rule of code..... "You don't own the code you write", so look after it and stop being lazy. Few understand this
@the-niker
@the-niker 8 месяцев назад
Hot take - underscore fields are a remnant of c++ devs coming to C# originally. Mandatory "this." on everything is much more readable and gives clear distinction between local and class variables and methods (passing lambdas as paramaters, anyone?). A method should not care if a class-level variable is public or private, that is for the class to decide and change as needed, not a method. I do use underscores in my code, but only as a warning for any field that must never be accessed without a getter/setter. I agree private property makes little sense but if you feel that way it should give you a pause to consider if the property shouldn't be protected instead, especially in library code.
@CristianBaldi
@CristianBaldi 8 месяцев назад
I agree that underscores should be used to denote private backing fields that should not be accessed directly (ie backing fields for source generated change notifiyng properties, that would not work otherwise). To specify that what we're accessing is a class member rather than a local variable, we can still use the 'this.' which is more explicit
@mariocamspam72
@mariocamspam72 8 месяцев назад
Some of these posts are the computer equivalent of wives' tales
@stevestrong9363
@stevestrong9363 8 месяцев назад
I love this series! I take a drink every time I guess what you are going to say!
@PPSzB
@PPSzB 8 месяцев назад
In my opinion Getters shouldn't compute anything, small transforms are ok, but anything with even minor performance impact should go to the method. At least I'll know to cache the value if It's used more than once and I wouldn't do that with a property
@minhhieugma
@minhhieugma 8 месяцев назад
I believe they take the ideas from "are-there-any-reasons-to-use-private-properties-in-c" Last week, when I asked my staff engineer why he declared a private property to inject a service into a class, he gave me the above link - It is a private field/property and you have full control on it. Why do you need to make it as a property for some chance that likely never exist? - And if your logic is consistent, you should always use string/array to represent any values and should not use integer, float, double, decimal, object etc since you may need to change the type in the future.
@pavelromashuk237
@pavelromashuk237 8 месяцев назад
Good shot, Nick!
@Ayymoss
@Ayymoss 8 месяцев назад
Code Cop is awesome. I don't even think the underscore is not pretty. As you point out, when you're deep into a class you know exactly what that variable is; without the need to scroll to the top. But if you have public and private auto-props, there's no way to know by the standard naming convention. I choose to believe the person who made that original post made it for rage bait.
@SG_01
@SG_01 8 месяцев назад
This is like applying all the reasons for public properties instead of member fields to private member fields. Trying to encapsulate private data is misunderstanding the whole concept of encapsulation on a fundamental level. And yes, there is nothing stopping anyone from naming their private fields the same way as public properties. The language doesn't limit your coding standards, but they do exist for a reason.
@kzryzstof
@kzryzstof 8 месяцев назад
"It should be readonly" Love it and I can't help protecting fields as much as possible.
@sajilicious
@sajilicious 8 месяцев назад
I prefer the StyleCop way of using "this". That way you can easily see that it's a class field. Also, you can also easily tell the difference between methods calls to static methods and non-stick methods because the StyleCop analyser informs you to prefix "this" on calls to non-static members.
@sealsharp
@sealsharp 8 месяцев назад
this is it.
@nanvlad
@nanvlad 8 месяцев назад
I know the use case for that 1) Create a class OuterClass with a private _field 2) Declare a private class inside with some method 3) Inside this method create an instance of OuterClass, e.g. var outerInstance = new OuterClass() 4) Boom! outerInstance._field is available. P.S. Sometimes I use this approach for xUnit tests with [ClassData] attribute, where all initialization of services is in outer class and all testcases described in the private inner classes where they have access to inner state of a parent class
@g3ff01
@g3ff01 8 месяцев назад
Hi! I dont't know what you meant, but what I "understood" from this was something like this: class OuterClass { private int _field; private void SomeMethod() { private class InnerClass { private int _innerfield; } var outerInstance = new OuterClass(); } } and this doesn't make any sense. Could you please provide us some example code? As it sounds interesting.
@nanvlad
@nanvlad 8 месяцев назад
@@g3ff01 Hi, here is a code sample. If you try this approach for testing with xUnit and ClassData, you'll see a different visualization in VS TestExplorer public class Outer { private int _outerField; private class Inner { public int GetOuterField(Outer outer) => outer._outerField; } }
@g3ff01
@g3ff01 8 месяцев назад
@@nanvlad thank you
@heiko3169
@heiko3169 6 месяцев назад
You are violating clean code rules already by declaring a class inside another class.
@MilanDendis
@MilanDendis 8 месяцев назад
Definitely fields is my choice. And that underscore helps me to know i'm using a private field later in code.
@eradubbo
@eradubbo 8 месяцев назад
In my first job, as a junior .NET developer. I remember the "solution architect" of the application I were working on told the team we had to always use properties instead of fields, like in this video. I questioned him on why, but he had no answer for why. Shows there is a lot of bad advice being pushed by people that don't properly understand what they are advising.
@minhhieugma
@minhhieugma 8 месяцев назад
it is really hard to debate with a higher position especially if they give you a StackOverflow link of a highly rank author: are-there-any-reasons-to-use-private-properties-in-c
@DlinnyLag
@DlinnyLag 8 месяцев назад
Thanks. Commented on this LinkedIn post
@paulp4061
@paulp4061 8 месяцев назад
One benefit of private properties over private fields is that for properties VS codelens shows reference count which can sometimes be handy
@fxandrei
@fxandrei 7 месяцев назад
I really think you should make a video and go into detail about fields vs properties, when to use one vs the other, why, etc
@insa07
@insa07 8 месяцев назад
Maybe, with versioning, they were referring to binary compatibility. Where, if in one version you first have a public field, but in a later version you change the field to a public property, you would introduce a breaking change on a binary level. Whereas, if you work with a public property from the start, you are free to change the underlying logic without introducing a breaking binary change.
@nanvlad
@nanvlad 8 месяцев назад
The case that we don't have any 'public' members - they all private
@AlFasGD
@AlFasGD 8 месяцев назад
That's exactly what they refer to, and given the knowledge the person has about the language, they would still fail to understand what they are proposing for.
@Stealthy5am
@Stealthy5am 8 месяцев назад
There's no way they're referring to binary compability considering the rest of the post.
@AlFasGD
@AlFasGD 8 месяцев назад
@@Stealthy5am you know this could very well be an idiot munching the same chew gum as all others, and simply reproducing the brief summary of random arguments found online about preferring properties over fields
@pilotboba
@pilotboba 8 месяцев назад
Except they made the property private which means it's not part of the public API.
@nickpolyderopoulos3491
@nickpolyderopoulos3491 8 месяцев назад
Underscores in fields are just a naming convention(code style) which can easily be changed (I wonder how amazed the person will be when they encounter editorconfig). I guess what happens with a lot of people these days is that they have no understanding of how the `IL` works on the background. They would think that what they see is what the computer actually runs. Thanks for the Video
@mwzndev
@mwzndev 8 месяцев назад
Prefix/Sufix for classes and interfaces, _ for private members, UPPER_CASE for constants and $ for observables. This is the way.
@astrokotik6887
@astrokotik6887 8 месяцев назад
This is madness! THIS IS CODE REFACTORING!
@m4ster_root
@m4ster_root 8 месяцев назад
I got all furious when I saw the title... All for no reason! :D This is the second time I've made that mistake, maybe I'll learn one day.
@TheDiggidee
@TheDiggidee 8 месяцев назад
1. Use "this" instead then 2. You get that anyway 3. Not the responsibility of this class (belongs in the IoC container) 4. Not the responsibility of this class (belongs in the IoC container) 5. Use Lazy which is handled by the IoC container 6. Not the responsibility of this class (belongs in the IoC container) 7. Pointless 8. Not the responsibility of this class (belongs in the IoC container) 9. You get that anyway. Seems like someone needs to learn the "readonly" keyword
@vyrp
@vyrp 8 месяцев назад
I think the root problem of the post is that they used a *private* field in their example. Some of the reasons make sense when talking about public fields versus public properties.
@vyrp
@vyrp 8 месяцев назад
And under the lens of public properties, I would interpret the "versioning" reason as being able to change the serialization of the data without changing the class API.
@andrewmcclement4464
@andrewmcclement4464 8 месяцев назад
It can be argued that never using fields simplifies C#, so there is less to learn. (You don't need to remember two different ways to make something readonly - you just don't add the setter instead of needing to remember to use readonly keyword vs not including the setter.) You can also argue it is simpler if you later decide to make that property public. Still, I doubt paying the (small) cost of using properties everywhere is something people should adopt by default - no need to lose performance if it isn't necessary. Personally I like using private fields since you immediately know from the naming convention that it is a private field instead of a property which could be public or private, so you get more information at a glance when reading. Of course, the main value in using properties comes when dealing with the interface of the class, so public properties (but also protected properties allow you to restrict the setter to private, for instance).
@ScottGarryFoster
@ScottGarryFoster 8 месяцев назад
Mocking and Testing is a reason to choose it. Not because of the implementation because this would probably be in the interface as a {get}. Not sure if newer versions of .NET solved Fields in interfaces but I'm still plagued with them for this, not like it's a big deal generally just writing {get; private set;}. Also some frameworks on the Mocking side only like Properties, sucks but happens. Notifications I can see but that's more... this is what properties are for... generally for like MVC. Probably included as it's a point for them not because it's a particularly good point.
@ratherbyexploring4898
@ratherbyexploring4898 8 месяцев назад
One vote for the other guy would be that I can override a virtual property ( that has a get accessor) with a covariant return type. Granted it wouldn't be private
8 месяцев назад
I'm not a good fan to use underscore for private fields , but I understand your logic.
@supern4ut3
@supern4ut3 8 месяцев назад
I Agreed.
@CRBarchager
@CRBarchager 8 месяцев назад
Well the alternative is the this. instead. I, on the hand, find that ugly but what ever coding style you like you can use. As long as it's only you on the project or you agree with the rest of the team that this is how you would name things. There is no right or wrong here, but there is a standard way of naming things and you can use it if you like it or use your own if you prefer.
@timmygoldstein
@timmygoldstein 8 месяцев назад
@@CRBarchager You can just as well use standard camelCase and let IntelliSense do the work for you. It tells you whether it's a local variable or field. The main difference is the at a glance, which is the decision people have to make.
@computer9764
@computer9764 8 месяцев назад
@5:40 For a time, MS C# naming recommended to not include the underscore and to just start with a lowercase character. I think around the time dotnet got the native decency injection is around when it was changed to use the underscores.
@matthewrobertson6249
@matthewrobertson6249 8 месяцев назад
Thank you for commenting this. A long time ago I switched from prefixing with underscore and using camel case solely because it was in the C# style guide at the time. I'm glad to see this has changed because it makes it so much easier to differentiate fields vs parameters and variables in methods without bloating the code with this statements everywhere
@jsxpt
@jsxpt 8 месяцев назад
I thought the modern standard was to not include the underscore since a lot of Microsoft's documentation uses this standard. I guess I was wrong :(
@tangomoocow
@tangomoocow 8 месяцев назад
Feels very much like somebody churning out content from a LLM and either not checking it or not understanding it in the first place.
@IDrDoh
@IDrDoh 8 месяцев назад
If you make the property public you can write nicer unit tests, the property should be auto mocked and you can "stub" a function directly by accessing the property field. (i did this years ago, but not any more)
@billy65bob
@billy65bob 8 месяцев назад
8:30 What I think he means by "versioning" is that you can keep the properly around as a fancy getter/setter if you 'deprecate' it in a future revision of your API. So that code that expects it still works and doesn't blow up. But that's a moot point, because it's not the API's job to provide compatibility with its internals.
@artemisDev
@artemisDev 8 месяцев назад
I had quite the good laugh at that picture.
@alexandernava9275
@alexandernava9275 8 месяцев назад
Fun fact, the m_ came from c++ because way back in the day namespaces would use _ for interal stuff that would clash(atleast that is what my old teacher told me, not sure how true it is).
@Xotchkass
@Xotchkass 8 месяцев назад
The "underscore" argument is completely nonsensical because... you don't have to name private members with _. It's a convention, but its completely up to you. Want to name private fields in PascalCase - go for it. You can name them however you want, lol. It's not go where case of the name defines access modifier.
@user-mo8fo6bs1q
@user-mo8fo6bs1q 8 месяцев назад
Hello Nick, great lesson to me, and I wonder how do you auto fix the sting to string at 5:58?
@ianmcpherson2301
@ianmcpherson2301 8 месяцев назад
Coding function and performance is the bias that I wirk to. I often don't use an IDE so the underscore is the standard i now use. It took me a couple of years to drop the m_ and just use the _. In fact i still have a couple of legacy libraries that still have the m_ in the code.
@MRJerrod410
@MRJerrod410 7 месяцев назад
I use private properties instead of fields because the IDE tells me if, and where, it's being used automatically. I'm not sure why it can't do that for fields too. I also use Pascal case for class variables and camel care for method variables to distinguish. I only use the underscore for backing fields of properties so the caller knows not to use them.
@lordicemaniac
@lordicemaniac 8 месяцев назад
on note of giving advice just so you could give one, i have one "advice": one thing i see in code of others that they call async methods in succession even when they do not share data, they could be executed in parallel, if i'm not wrong, only thing they need to do is first create tasks and after that await them like var t1 = CallMethodAsync(); var t2 = CallAnotherMethodAsync(); var t1val = await t1; var t2val = await t2;
@user-pk7tw4sk6d
@user-pk7tw4sk6d 5 месяцев назад
fortunately Nick chapsas exists
@MilYanXo
@MilYanXo 8 месяцев назад
I always change editconfig to remove underscore from private field names and enforce camel case. I hate underscores, its so freaking MSVC++, its uncanny. There is a special circle of hell for people who brought it as a default into C#, especially with DI. You avoided having to use "this." in construcotr. Bravo. Ugh. If your attention span is so narrow or your method so complex you lose track which identifier is local var and which class member, you really should be looking for another job.
@antonmartyniuk
@antonmartyniuk 8 месяцев назад
One of the issues I have with primary class constructors in C# 12 is that you lose underscore for private readonly fields when having your dependencies in the primary constructors. I really like having my private fields be named with underscore
@phizc
@phizc 8 месяцев назад
You don't have to lose the underscore. You can do this class A( string name ) { string _name = name; // uses name from constructor } Unless you use the "name" argument from the constructor in a method (or getter) it won't get a hidden backing field.
@antonmartyniuk
@antonmartyniuk 8 месяцев назад
@@phizc you can do this, but the whole idea behind primary constructors is to decrease amount of code you write
@EdKolis
@EdKolis 7 месяцев назад
Private properties have their uses, like when you want a computed property but it needs to be private, or maybe your serializer only works with properties and not fields. I don't like fields much myself anymore, they seem like a relic. But replacing all fields with properties just to avoid underscores...
@FR12321
@FR12321 8 месяцев назад
I stopped using the _ in private fields because I can assign different colors to each member type in Visual Studio (Tools > Options > Environment > Fonts and Colors then search for User Member) I just have fields/properties in black, parameters in red-ish color and locals in navy color, it's consistent and I never run in the issue of forgetting an underscore somewhere. The only downside is that you need to use this in the constructor because parameters could have the same name as the fields.
@jeroen7362
@jeroen7362 8 месяцев назад
i guess you work alone on a project without pull requests. You also want readable code in code review on a webbrowser in the compare window.
@FR12321
@FR12321 8 месяцев назад
Readability of the PR in the browser was a concern at first, but so far (~10 devs, ~5 years doing this) there were no real issues I think some of the reasons for that are: - class names usually give a good idea of what the context is, eg. UserController, ArticleRepository, ... - fields names usually indicate functionality, eg. customerRepository, orderService, dbContext, ... - parameters names usually indicate data, eg. createCustomerRequest, userName, validUntil, ... - usually, it doesn't matter where an object comes from in a method as long as we can use it (and when it does, the issue tend to be in how it was injected and the lifespan it was given) This just my experience, definitely not a silver bullet but it works for us, colors are consistent even if you use _underscore :)
@anm3037
@anm3037 8 месяцев назад
The underscore as first letter of a backing-field helps when you want the IDE to put it at the end of name-suggestion list (which appears while typing) … helping you to see the property before the backing-field.
@bradoestreicher3476
@bradoestreicher3476 8 месяцев назад
While the reasons the author of the original post listed were, for the most part, pretty silly (as you point out), I do favor properties in most cases for one reason. In fact, you even demonstrated that reason without knowing/mentioning it! When you had the field and the property both present in your demo code, notice the 'guide' above the property that says '1 usage'. In Visual Studio, clicking on this guide shows where the property is referenced. Fields have no such feature (I don't know why, Microsoft should add this). So, simply as a convenience, properties make development easier because they have better IDE support.
@shalopo
@shalopo 8 месяцев назад
What they meant with version compatibility is that in the case you are providing a library, any code using your fields is going to break once you turn it into a property, and they'd have to recompile their code for it to work. So generally defining it as a property ahead of time would prevent this. However, this does not apply to private members anyway so this is completely pointless.
@slipoch6635
@slipoch6635 8 месяцев назад
lol, I was about to point out private fields would not be accessible externally, then read your last line.
@EdKolis
@EdKolis 7 месяцев назад
But what if the caller is using reflection to access private members? 😛
@KennethSiewersMller
@KennethSiewersMller 8 месяцев назад
One thing, which is not mentioned, is that the IDE typically show usages for properties but not for fields. I’m not sure whether that’s something you can enable in Rider, but it is sometimes useful to know how many times your field is accessed, which you just can’t for some reason.
@gabrielfkrk
@gabrielfkrk 8 месяцев назад
There are two features in Rider I know of that might help. "Find usages", Alt+F7. The second is in the context menu after right-clicking the field, don't remember the name but allows to find value origins and value destinations. So you can find what uses the field or what sets the field
@rpenha
@rpenha 8 месяцев назад
Shift + Alt + F11 / Ctrl + Alt + (PgUp | PgDown)
@KennethSiewersMller
@KennethSiewersMller 8 месяцев назад
@@gabrielfkrk I know the shortcut to find usages, but what I’m looking for is the inline hint on top of properties where Rider shows the number of usages. You could argue, from a design perspective, that one shouldn’t have classes so big that it’s necessary to see the usages, but Rider is smart enough to know when a field is unused, so it must keep count somewhere.
@KennethSiewersMller
@KennethSiewersMller 8 месяцев назад
@@rpenha yes, I know, it I’m talking about the inline hints Rider shows for properties and methods.
@gabrielfkrk
@gabrielfkrk 8 месяцев назад
@@KennethSiewersMller I see. And I agree, that info must be there somewhere or easy to switch on (I mean for JetBrains devs). Hmm, I am now curious myself if there is a setting for that
@stephenyork7318
@stephenyork7318 8 месяцев назад
I think one of the most telling things I’m this advice is they have a class named …UseCase. That I’m itself screams they’re clueless. I worked for a department once which actually had UseCase as the base class of every entry point to any action in a service. They worries too much about modelling things which weren’t necessary. Same here, thinking they have something to offer and chasing clout when they have no idea what they’re doing at the most basic level.
@WilliamCWayne
@WilliamCWayne 8 месяцев назад
I clicked on this video not even imagining the suggestion was going to be to make a private get only property ... wow, that's crazy.
@WilliamCWayne
@WilliamCWayne 8 месяцев назад
For an injected member, no less!
@UnseenScofield
@UnseenScofield 8 месяцев назад
Can we get a video about class libraries using low level implementations like scanner, ocr, printers etc. Do you have libraries to use them on dotnet core? Cause COM references and IO references pretty hard to upgrade on .net framework to .net core. Thanks.
@davidfrogley7117
@davidfrogley7117 8 месяцев назад
Related question. I have a public read-only property (only has a getter) backed by an explicit private member field. I do this so I can use the field explicitly within the class, to avoid the (slight) performance hit from calling the getter method that gets generated for the property. The compiler could very well be optimizing the code by inlining that call anyway, I don't know, I haven't bothered to check. But my IDE is recommending that I use an auto-property instead of an explicit backing field. This is a computation-intensive application that does need to be concerned about performance, so would an auto-property be optimized away during compilation (either IL compilation or JIT compilation), so I can go ahead and use one? Or should I continue using my explicit backing field?
@timseguine2
@timseguine2 8 месяцев назад
I think the versioning argument might be about ABI breaking behavior (at least something similar is true in some other languages. I am not knowledgeable enough in the CLR details to know if it applicable here though) Swapping between access control levels or switching between fields and properties can affect the ABI in some languages, which could have a negative effect on modularity and independent deployability. But based on some of the other arguments they gave maybe I am being too willing to accept they actually had good reasons. Sometimes private properties end up briefly in my code during the prototyping phase before the design has crystallized but I agree that they are a code smell. The only way they might make sense IMO is if csharp had protected or private interface inheritance, in which case a private property could form part of an extension interface for some sort of abstract base class. But even then the usual csharp convention would seem to be to make the protected, and as it stands this is something that shouldn't even survive a code review let alone be a recommendation.
@travisabrahamson8864
@travisabrahamson8864 8 месяцев назад
It seems to me that the majority of the time stuff passed in the ctor would be readonly and a Field, as you wouldn't want it modified. Such as Dependency Injection. I would use a property if I needed that value public or protected. Otherwise the private readonly Field is the choice I would make. I also prefer the underscore in front of the name.
@muhammadtariq8323
@muhammadtariq8323 8 месяцев назад
I requested you that make a video on .NET Core, static file response compression. Pre-Compress (br / gzip) or run time by .NET Core or IIS. Which are best and how to implement
@PeterOeC
@PeterOeC 7 месяцев назад
I like being able to only change the "private" to "public" or "public" to "private" and not the property name/field name when I realize that something should switch from being public to private or the other way around. It's a bit lazy, I know, and the editor can proberbly do it for me, but it takes a little bit of mental ressources and time to change - though I could go with a non-underscore naming for fields. Also I feel the underscore naming is a bit noisy to read rather than a private property... But that's just preference. Talked about exactly this in our team, and people prefer different things. I wonder if there's a slight performance benefit to fields rather than properties - maybe a tiny one, but still, on a massive scale, it might mean something 🙂
@iSoldat
@iSoldat 8 месяцев назад
I still don't understand why some people would use a global service like linkedin to post their personal coding preferences. We all have different styles of coding; some good and some bad. Thanks Nick, for keeping us informed.
@allinvanguard
@allinvanguard 8 месяцев назад
It's quite simple, the goal is not to spread technical knowledge or spreading an opinion, the goal is to increase visibility and followers so potential employers might get the idea that you are an impressive developer, netting you better career prospects or the chance to convert your following into money.
@francoislepron2301
@francoislepron2301 8 месяцев назад
Do you know why Microsoft has changed from m_ExplicitVarName to _ExplicitVarName removing the m which was there to specify "member" of a class ? I am an old software developer, and I still don't understand why they moved to another reduced naming convention. I would appreciate to know why. Thank you.
@florianmartingrimm8055
@florianmartingrimm8055 8 месяцев назад
its a private property - no ABI reason - no versioning reason - its just slow - if you hate underscore add an editorconfig file and adjust it
@TheXX113
@TheXX113 8 месяцев назад
Private properties, as from my experience, were used only for lazy loading and not repeating this logic all over the places in different methods. In other cases, not really much you could get out of it. Plus thinking of private methods (usually its implementation layer already) usually you want to "hide" all optimizations over there, and having property won't let you operate with ref.
@na_berna
@na_berna 8 месяцев назад
Perfect!
@AvgDan
@AvgDan 8 месяцев назад
I like seeing how many references there are to properties, but yeah, not gonna make member variables properties.
@Snikersano
@Snikersano 8 месяцев назад
XD
@codingbloke
@codingbloke 8 месяцев назад
I dislike the use of underscore to prefix a field, and especially dislike the use of double underscore for static fields. Whilst _ is the defacto industry standard, I prefer the prefix "my" for instance fields and "our" for static fields. The field names now have more meaning. myThing is an object instance saying this value belongs to me, whereas ourThing is the class saying this value belongs to all of our instances.
@br3nto
@br3nto 8 месяцев назад
I agree with the underscore comment. The _ style is just not needed anymore. It makes code feel old and yucky.
@sergius_carp
@sergius_carp 8 месяцев назад
Regarding "versioning", I suspect they meant you can substitute "{ get; }" with some computation logic without changing the rest of the class.
@VennieVin
@VennieVin 8 месяцев назад
Is it possible to see the low-level implementation in Visual Studio as well? Love the videos Nick!
@igorthelight
@igorthelight 8 месяцев назад
It is! Just google how ;-)
@VennieVin
@VennieVin 8 месяцев назад
@@igorthelight I’ve tried but can’t find anything, could you direct me to a link or summarise how? Cheers
@igorthelight
@igorthelight 8 месяцев назад
@@VennieVin Tools -> Options -> C# -> Advanced -> Enable navigation to decompiled sources (and "enable navigation to source link and embedded sources").
@VennieVin
@VennieVin 8 месяцев назад
Hey I really appreciate that, thank you!
@ExpensivePizza
@ExpensivePizza 8 месяцев назад
For a very long time Microsoft didn't even have documented naming conventions for private fields. Even so, most C# shops adopted the underscore for the very reasons Nick says in the video. It helps you understand what's going on in the code at a glance.
@slipoch6635
@slipoch6635 8 месяцев назад
Yeah as long as you have some standardised difference between public props, private fields, and method names you should be fine, differentiating from a class local field and a method local field may not always be needed but if you have any disposables happening I wouldn't want to go without that either. I'm not a huge fan of _ but I use it.
@EdKolis
@EdKolis 7 месяцев назад
And some of us are so old school we use camel case for fields...
@NelsonGiraldo
@NelsonGiraldo 8 месяцев назад
Much people that start in programming, publish tips to replicate what they learn even if they don't interiorise the concept and only replicate information that they don't fully understand.
@markovcd
@markovcd 8 месяцев назад
No underscore, no "this." master race reporting in.
@Vimes4
@Vimes4 8 месяцев назад
There was a naming guidelines doc on MSDN a long time ago that said to forgo the underscore. I stopped using it and didn't even notice. The doc is no longer up.
@klocugh12
@klocugh12 8 месяцев назад
Cue naming properties starting with underscores out of spite 😂 And someone should tell them about Lazy
@Ruhrpottpatriot
@Ruhrpottpatriot 8 месяцев назад
The whole post makes much more sense when you swap the access modifier to public. Still not the best advice, but at least it's not braindead anymore.
@CyberAngel67
@CyberAngel67 8 месяцев назад
As a Unity developer, I do use Properties a lot, but in moderation as well due to the extra time it takes to process a property over a field. I can also never understand the mentality of these people with the underscore, it is like they don't comprehend that the less you are going back and forth in your code is saving time when debugging. As for the property change, I never use it to do a property change like the Application world, but in Unity, I do use it to bypass the need to use the continuous use of an Update which again is a process saver.
@ondrejvrabek9485
@ondrejvrabek9485 8 месяцев назад
Geter instead of property recomendation is probably from time before readonly(or init) was added. Is not?
@InfinityFnatic
@InfinityFnatic 8 месяцев назад
Honestly we should just get rid of the underscore notation, it's a relic from times gone by. It replaced Java's way of things because in camelCase you had to use this.someField to know it was a class field. If we're already using PascalCase for everything else just use it for fields too, because local variables will be camelCased anyways, so there will be no ambiguity.
Далее
"Remove Braces From Your Code Now!" | Code Cop #004
8:36
Settling the Biggest Await Async Debate in .NET
14:47
Просмотров 140 тыс.
Crazy Girl destroy RC CARS 👩🤪🚘🚨
00:20
Просмотров 2,7 млн
He turned a baseball into a stylish shoe😱
00:59
Просмотров 399 тыс.
"I Lost a Job Because of This Codebase"
14:08
Просмотров 56 тыс.
Differences between a field and a property in C#
1:55
Просмотров 3,5 тыс.
The Smart Way of Using the Decorator Pattern in C#
12:37
"Stop Using Automapper in .NET!" - Code Cop #001
9:57
Просмотров 108 тыс.
How IEnumerable can kill your performance in C#
11:02
Просмотров 113 тыс.
how Google writes gorgeous C++
7:40
Просмотров 798 тыс.
Background Tasks Are Finally Fixed in .NET 8
10:29
Просмотров 101 тыс.
Don't put your types in .d.ts files
3:54
Просмотров 129 тыс.