Тёмный

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

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

Use code TDD20 and get 20% off the brand new Test-Driven Development course on Dometrain: dometrain.com/...
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/nickwor...
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasG...
Follow me on Twitter: bit.ly/ChapsasT...
Connect on LinkedIn: bit.ly/ChapsasL...
Keep coding merch: keepcoding.shop
#csharp #dotnet

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

 

29 сен 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 443   
@amirhosseinahmadi3706
@amirhosseinahmadi3706 11 месяцев назад
Rule #1: Never take advice from someone who calls fields "class member variables".
@Z3rgatul
@Z3rgatul 11 месяцев назад
Good one 🤣
@EdKolis
@EdKolis 10 месяцев назад
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...
@JoeRomano-s8g
@JoeRomano-s8g 10 месяцев назад
😂😂
@MrMatthewLayton
@MrMatthewLayton 8 месяцев назад
"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".
@nanvlad
@nanvlad 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
@@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 11 месяцев назад
@@nanvlad thank you
@heiko3169
@heiko3169 9 месяцев назад
You are violating clean code rules already by declaring a class inside another class.
@vyrp
@vyrp 11 месяцев назад
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 11 месяцев назад
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.
@IDrDoh
@IDrDoh 11 месяцев назад
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)
@KnightSwordAG
@KnightSwordAG 11 месяцев назад
I have created a private property, but I did that because in Blazor, I wanted to Inject a service into a component, but I did not want that service exposed to the component users. And the InjectAttribute doesn't work on fields. I wonder if I could have injected it via the constructor? But then do Blazor components have constructors? *goes investigating*
@CyberAngel67
@CyberAngel67 11 месяцев назад
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.
@memsom
@memsom 11 месяцев назад
The underscore is optional and not even universally used in Microsoft’s own code. I personally don’t use it and it is not really enforced by Visual Studio either.
@UnseenScofield
@UnseenScofield 11 месяцев назад
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.
@anonimzwx
@anonimzwx 11 месяцев назад
Tbh i dont like the underscore and i just dont write it on fields, i dont know why people uses naming conventions that they dont like.
@Ba_Dashi
@Ba_Dashi 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
Well its their job getting paid off view so they gotta bait the clicks 😂 i hate tech influencers
@verzivull
@verzivull 11 месяцев назад
can it be an advice from chatgpt?
@envo2199
@envo2199 11 месяцев назад
its called rage bait posting.
@samsim4648
@samsim4648 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
@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 11 месяцев назад
@@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
@ferd1775
@ferd1775 11 месяцев назад
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 11 месяцев назад
I bet they use the 9 reasons from chat gpt
@chlorobyte_projects
@chlorobyte_projects 11 месяцев назад
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 11 месяцев назад
f... each comment makes it sound more and more like chatgpt
@ferd1775
@ferd1775 11 месяцев назад
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
@JohnWII
@JohnWII 11 месяцев назад
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.
@mariocamspam72
@mariocamspam72 11 месяцев назад
Some of these posts are the computer equivalent of wives' tales
@jamesroot9777
@jamesroot9777 11 месяцев назад
The 9 points just look like something ChatGPT would generate.
@AlFasGD
@AlFasGD 11 месяцев назад
From my experience with ChatGPT, it would be smarter than those stupid ideas and arguments against fields.
@ferd1775
@ferd1775 11 месяцев назад
@@AlFasGD I agree, but I think they asked it to generate an article arguing FOR it..cus it will do that haha
@baetz2
@baetz2 11 месяцев назад
​@@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 11 месяцев назад
More and more, they might actually be so.
@qtxsystems
@qtxsystems 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
How does that improve readability at all? I dont get it...
@MostlyPennyCat
@MostlyPennyCat 11 месяцев назад
​@@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 11 месяцев назад
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 11 месяцев назад
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 :)
@1Gargo
@1Gargo 11 месяцев назад
Sounds like the advice of someone who doesn't understand the basics. Is this person suffering from the Dunning-Kruger effect?
@TazG2000
@TazG2000 11 месяцев назад
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.
@proosee
@proosee 11 месяцев назад
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.
@neralem
@neralem 11 месяцев назад
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 11 месяцев назад
I got fooled by your avatar! I really thought I had a fly on my screen.🤣🤣🤣
@sealsharp
@sealsharp 11 месяцев назад
@@alfflasymphonyx Me too. You got me.
@BearJewOo
@BearJewOo 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
​@@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.
@VeggehGaming
@VeggehGaming 11 месяцев назад
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 11 месяцев назад
I like underscores in private field names. It highlights them as what they are, and I immediately know how to handle them.
@dantecavallin8229
@dantecavallin8229 11 месяцев назад
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 11 месяцев назад
@@dantecavallin8229 this is exactly how it was designed in python, where everything is public, underscore just suggest not to use it
@brianviktor8212
@brianviktor8212 11 месяцев назад
@@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 11 месяцев назад
@@brianviktor8212 I do the underscore only for backing fields if I need them for a property.
@the-niker
@the-niker 11 месяцев назад
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 11 месяцев назад
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
@asteinerd
@asteinerd 11 месяцев назад
"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 11 месяцев назад
Not sure. For auto properties an optimization should work which uses the field directly without get/set method
@PPSzB
@PPSzB 11 месяцев назад
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
@hemant-sathe
@hemant-sathe 11 месяцев назад
I personally believe that lot of SO highly upvoted answers are going to be fed into GenAI training data as right answers and we are going to get stupid answers much regularly than anticipated or worse, this stupidity will be masked. The world will adapt bad advice faster than today.
@mrShot94
@mrShot94 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
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.
@markmsmh
@markmsmh 11 месяцев назад
Nick, your readoning is as incorrect as the authors of that advice. Telling, that code valudation is being done in getter and that it waste resources is using wrong design to reason toward your goal. Validation has meaning in setter scenarios, not getter. Telling us, that properties are there mainly for encapsulation? Really? Why they exist? Those pesky private properties? Again, readoning by former okd bad design, that underscore informs me, that it is field comes from times of large toilet paper long classes. If you argunent with me about underscores THIS WAY, then that implies to me, rhat you have convoluted big class with super complex methods that clerly it fit on one sß😅creen. Such ognitive gravitationally collapsed star 😅
@drkrovischa
@drkrovischa 11 месяцев назад
So what is the problem with using properties instead of fields, even if they are private? Apart from the fact that the author of the "advice" does not understand what the property actually is. Personally, I don't like fields with underscores in their names. For the same reason, I didn't like the "m_field" stuff. It made sense in ancient times, when people wrote code on clay tablets, because code was just text. But nowadays, it's as unnecessary as tattooing "left" on your left hand and "right" on your right hand, so you don't get them mixed up. And if the class you are writing is so big and/or confusing that you have to add special symbols to remember which element is a class variable and which is a parameter, you have a bigger problem on your hands.
@Xotchkass
@Xotchkass 11 месяцев назад
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.
@Integer0
@Integer0 11 месяцев назад
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.
11 месяцев назад
Underscore"_", like the old convention "m_", today does not make any sense for me, at all. Seems to be from old times, when something like notepad was used to code. It is a convention after all, and these things change over time.
@KrucLeo
@KrucLeo 11 месяцев назад
You are not wrong. The only thing you are is 'too nice'. Developers should stop making fools of themselves by trying to act like fitness influencers.
@insa07
@insa07 11 месяцев назад
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 11 месяцев назад
The case that we don't have any 'public' members - they all private
@AlFasGD
@AlFasGD 11 месяцев назад
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 11 месяцев назад
There's no way they're referring to binary compability considering the rest of the post.
@AlFasGD
@AlFasGD 11 месяцев назад
@@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 11 месяцев назад
Except they made the property private which means it's not part of the public API.
@joergw
@joergw 11 месяцев назад
I am using private readonly fields without underscore - 100% agree with Nick 🙂
@br3nto
@br3nto 11 месяцев назад
I agree with the underscore comment. The _ style is just not needed anymore. It makes code feel old and yucky.
@DaneWithADrone
@DaneWithADrone 11 месяцев назад
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
@francoislepron2301
@francoislepron2301 11 месяцев назад
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.
@dr_Bats
@dr_Bats 11 месяцев назад
I hate underscores. I use this to access class private members. Thanks Nick for agreeing with me. 😄
@dotvkab
@dotvkab 11 месяцев назад
private properties without any getter/setter advanced logic are nonsense
@TubeAccount-b1f
@TubeAccount-b1f 11 месяцев назад
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
@FraserMcLean81
@FraserMcLean81 11 месяцев назад
Personally, I never liked fields prefixed with an underscore. Just doesn't make sense that there is this special exception for fields with regards to naming. Most IDEs will highlight a class field in a different colour.
@codecoachdev
@codecoachdev 11 месяцев назад
Yes, absolutely!
@massimoandreasibassi7016
@massimoandreasibassi7016 11 месяцев назад
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.
@eradubbo
@eradubbo 11 месяцев назад
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 11 месяцев назад
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
@Snikersano
@Snikersano 11 месяцев назад
XD
@ratherbyexploring4898
@ratherbyexploring4898 11 месяцев назад
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
@SG_01
@SG_01 11 месяцев назад
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.
11 месяцев назад
I'm not a good fan to use underscore for private fields , but I understand your logic.
@supern4ut3
@supern4ut3 11 месяцев назад
I Agreed.
@CRBarchager
@CRBarchager 11 месяцев назад
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 11 месяцев назад
@@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.
@ScottGarryFoster
@ScottGarryFoster 11 месяцев назад
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.
@br3nto
@br3nto 11 месяцев назад
The comment about encapsulation only makes sense for the current usage of the field. I’m not sure about you, but I’m often iterating and changing and improving class structures over time and moving things about, properties/fields swapping scopes and locations. It would be easier if the compiler only created a backing field and a getter if it were necessary to do so to minimise the difference between fields and properties. It should be possible to do that. And would be easier to use fields if the IDE displays usages for fields.
@GufNZ
@GufNZ 11 месяцев назад
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 11 месяцев назад
Yeah but I dont think one should rely on everyone who will ever read this code to have such an IDE and setup
@an_wobbly
@an_wobbly 11 месяцев назад
You should *always* use an underscore prefix for intellisense. At a lower level, it's the standard way for expressing intent.
@MrIlya007
@MrIlya007 11 месяцев назад
Maybe the author of this linkedin post is just a troll?
@sajilicious
@sajilicious 11 месяцев назад
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 11 месяцев назад
this is it.
@Ayymoss
@Ayymoss 11 месяцев назад
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.
@FR12321
@FR12321 11 месяцев назад
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 11 месяцев назад
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 11 месяцев назад
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 :)
@vargonian
@vargonian 11 месяцев назад
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 10 месяцев назад
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.
@meowzhin
@meowzhin 11 месяцев назад
Prefix/Sufix for classes and interfaces, _ for private members, UPPER_CASE for constants and $ for observables. This is the way.
@Rafloka
@Rafloka 8 месяцев назад
Looks like: Hey ChatGPT, please create some clean code tips I don't really understand but can use for several posts anyway.
@TheDiggidee
@TheDiggidee 11 месяцев назад
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
@bslushynskyi
@bslushynskyi 11 месяцев назад
This "advice" is not applicable when you use MVVM programming model in WPF application. Dependency properties require backing fileds. Or in P/Invoke interops! Usually you make struct with public fields to marshal object from unmanaged code into managed C#.
@ErazerPT
@ErazerPT 11 месяцев назад
Great video. And yeah, it's a "muscle memory" thing. You see the _ and brain goes "private". And totally agree, if you're gonna add up some overarching logic to the accessors, MAKE A DAMN METHOD. Truth be said, that advice smells like someone that is using business objects as data transfer objects, because in that case it would make sense, you serialize the properties that have business logic in them to compute the property value. Obviously, the stupidity of using a BO as a DTO to begin with is mind boggling, but everyone has seen them out in the wild...
@panosru
@panosru 11 месяцев назад
hahaha, I can't stop laughing at 1:21, you could easily say "ΜΑΛΑΚΙΕΣ", it's an international word nowadays hahaha! Thanks for the video, you put nice content ;) PS: I clipped that for my memes ;P
@adambickford8720
@adambickford8720 11 месяцев назад
The reality is that much of tech is fashion/art, not science. What's an antipattern in once context/time is a best practice in another context. The worst thing you can do is think your biases are objectively better. Just watch the webapp world do a COMPLETE 180 every ~5 years or so (we're currently rediscovering PHP). Every day I have to explain to 'OO' devs that their patterns are idiotic in other contexts, but they refuse to accept it. When forced to admit the app is faster and produces less bugs, it's still 'unreadable' and 'unmaintainable'. Mmmhmm.
@megalodogge
@megalodogge 11 месяцев назад
Underscore is such a weird naming convention. Like VS is already using different colors for member/local variables. Why do anyone need extra punctuation? You seem to have no problem distinguishing ClassName, MethodName or PropertyName - which are all PascalCase. Why use underscore?
@davidlloyd1526
@davidlloyd1526 11 месяцев назад
I suspect that presentation predated when C# supported field get/private set. I'll admit that was like .NET 2 or whatever... Also, prefixing private variables with underscore is a pretty ugly throwback to how linkers worked in the 90s. You don't need to know that fields are private any more than you need to name integers i_myField and strings s_myField. That was a problem when C compilers weren't enforcing type safety properly...
@nickpolyderopoulos3491
@nickpolyderopoulos3491 11 месяцев назад
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
@dand4485
@dand4485 11 месяцев назад
Not that i agree with it, but argument for versioning might be if you need to work with multiple versions they might be using different member properties that are version specific. Only reason i might see the argument for versioning but that said, can't help thinking of the aspirin one will need to take once they get a couple versions and then needing to harmonize/synchronize if they spin up a v3 but then need a v2 instance of the class or simply the $#^&*@ nightmare they will introduce.... Not that i would ever agree with the approach i'm mentioning, but the only reason i could see them wanting versioned variables... And being a contractor moving from project to project, have to agree i've seen some really really bad code. Amazing one "LARGE" company i worked for in Redmond... My co-worker and i would ask each other how would you do 'x'. We always jokingly said "The Hard Way". Always felt the only way people did stuff was the most convoluted over engineered way possible...
@bruno-id1wh
@bruno-id1wh 11 месяцев назад
I also hate _ but it's not required. The main thing if you're on a team is having a standard that people use. I don't personally see much use for it, although it might make intellisense easier separating fields from methods. I laughed at 2. Don't understand 3. At what point would the data validation occur? Getters. Can't see many uses of computing or transforming in a getter, as you'd never have access to the raw data. Easy enough to add a method that returns the computer or transformed field data. Lost the will after that
@colincbcampbell
@colincbcampbell 11 месяцев назад
I quite, embarrassingly, are one of the guys that constantly use private properties over the private fields..😅 It's not for any of the above reasons (besides using being prettier and using Capital name and hating underscores).. I shall now need to change my ways.. 😂 I do, however, still like using protected properties for its override abilities and public properties for its abilities to private set.. I just didn't think about the overhead of private properties vs. private fields.. Thanks, Nick.. Thanks.. 😅
@MilYanXo
@MilYanXo 11 месяцев назад
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.
@JinnFletch
@JinnFletch 11 месяцев назад
You don't have to add "this." just because you removed the underscore. As a matter of fact, you can take it one step further and make the private field PascalCase, and most of the OP's points would still feel validated to them. It's a horrible idea, but you can't argue with "Company Standards", if they decide to break industry standards. That's up to them. On the other hand, if you DO use _camelCase format, please please please do not ever prepend their use with "this.". What an absolute confusing waste of characters. "this." is exactly what is supposed to be saved with the whole purpose of the _camelCase format. It is effectively redundant.
@sealsharp
@sealsharp 11 месяцев назад
I didn't expect the advice to be "use properties to replace all purely private fields". That is more stupid than i could imagine. I personally do not think that _underscore versus "this." is purely a matter of preference. It would be if the compiler enforced that _underscore could only be used on fields and not on statics and if writing _MethodName() for calling MethodName() when calling it from withing a class would be a way to write it. But _underscore is not functionally equivalent to "this.", it's a choice of feelings over function.
@denissmith8282
@denissmith8282 6 месяцев назад
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.
@jeffmccloud905
@jeffmccloud905 11 месяцев назад
"m_" was in C++. It was never recommended or common in C#. Since C#'s release, Hungarian notation has been explicitly discouraged.
@andrewshirley9240
@andrewshirley9240 11 месяцев назад
The original advice has always been "Don't use public fields, ever. If it's public, make it a property." Then this dude either just forgot that the advice only applied to public fields with his example, or he willfully just said "I'm going to blindly apply this to private fields and try to justify it," then went on to make this lol
@Krauttrooper
@Krauttrooper 11 месяцев назад
If you don't like underscore use pascal case. When i'm working on a method I don't see a need for knowing if a name is a field, property, private, public, virtual, inherited, injected, .... Why should i waste time by decoding the name of a variable, when I just need the value?
@PeterOeC
@PeterOeC 10 месяцев назад
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 🙂
@teothe
@teothe 11 месяцев назад
Fun fact. Wathving this in the normal playback speed, Nick bashes the "advice" very calmly. If you speed it up it sounds like a proper bashing response to this very bad advice. Hey, sometimes, you need not just the proper words, but a tone that someone will remember by the tone alone, how bad it is. Just saying.
@bradoestreicher3476
@bradoestreicher3476 11 месяцев назад
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.
@Crossbow123
@Crossbow123 11 месяцев назад
Tbh, I don't know why properties are used all over the place anyway. It's common to see that all public class members are properties. But why? Why not just use a public field with the same naming? And if you need actual getter / setter logic just change it. The only reason I see is because most libraries that use reflection rely on the members being properties like DTO mappers or ORMs.
@kurokyuu
@kurokyuu 11 месяцев назад
Probably the most dumbest thing I've ever heard. Don't know how you get to this idea that private properties make any sense in this context... wyld~ Regarding the coding convention: Wasn't it the case for the first iterations in the C# Standard that they told you "Do not use m_ or _ or any of this stuff" and wanted users to adopt the more Java stuff of using "this"?
@Cornelis1983
@Cornelis1983 7 месяцев назад
I understand the fact that people want to separate fields with parameters/arguments. But why using the underscore? It is such an ennoying char to type and especially for new developers, it doesn't mean anything? Back in the day when I was programming in Delphi, they used the letter f standing for, surprise surprise.... field! So why not name your fields with the f prefix? My personal preference is not use a prefix at all. Unless someone can tell me why I want to know when a variable is a field or a parameter/arguments. As most, if not all of the services, controllers, repositories etc. are stateless anyway, the only fields in such classes are injected services or repository having service or repository in their name. That information already tells me when it is a field or argument. I don't need an additional underscore for that.
@minhhieugma
@minhhieugma 11 месяцев назад
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.
@markharwood6794
@markharwood6794 11 месяцев назад
That reminded me of a bad codebase I wrote 20 years ago, very funny, and seriously terrible advice from someone who just doesn't understand basic concepts. Perhaps ChatGPT wrote it hehe
@EdKolis
@EdKolis 10 месяцев назад
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...
@slipoch6635
@slipoch6635 11 месяцев назад
I wonder why they don't just remove the _ and use a different set of coding guidelines so it's obvious it's local? I came across a bunch of people saying you should always use continue inside a foreach loop even if you are only processing stuff on elements that are not continued. (so no processing prior to the continue if statement inside the loop) I did a bunch of tests on this with both lists of classes and structs and compared it to adding a where inside the loop control. I tested both .Net 4.7 and .Net 7. In every test case the where came up using less memory (no unnecessary allocation) and less CPU cycles. Interestingly the struct had a much higher std deviation on CPU cycles than class in .Net 7 so there is obviously some sort of predictive stuff happening for class but it was fascinating to see the jump in efficiency between Net framework and Net 7. It went from a difference of ~20% to ~5%. fascinating stuff.
@shalopo
@shalopo 11 месяцев назад
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 11 месяцев назад
lol, I was about to point out private fields would not be accessible externally, then read your last line.
@EdKolis
@EdKolis 10 месяцев назад
But what if the caller is using reflection to access private members? 😛
@guenolelacroix6434
@guenolelacroix6434 11 месяцев назад
I prefer to use properties for Di. Why ? There is no particular reason. 😂 I can use readonly fields, sometimes i do, but when vs2022 propose me properties or fields i take property. It's also because it's simpler there is no readonly word , and when you make it public you don't have any surprise. For performance i'm not sure there is a big difference between them...
@InfinityFnatic
@InfinityFnatic 11 месяцев назад
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.
@stephenyork7318
@stephenyork7318 11 месяцев назад
You said “Microsoft didn’t add it because they hate developers”…Microsoft don’t even use it, the CTRL-. Helper when you use it on a type in a constructor to add a field doesn’t put the underscore and uses this. so that comment is a furfy
@1980NightFire
@1980NightFire 11 месяцев назад
While I agree that what the article is proposing is ridiculous, your reasoning n the history is just plain wrong, m_ is a c/c++ convention which was never adopted by the c# or the now redundant vb team within microsoft. MS have always advised against using _ naming conventions, due to the possibility of collisions within the framework. The original advice since their release of avalon tools (the predecessor to .NET) was to use camel case for private fields. Private properties although having a specific use case, of when actions need to be performed when any access to the field happens regardless of scope, are an archaic band aid, to a problem that can be refactored away in nearly but maybe not all use cases.
@MrMatthewLayton
@MrMatthewLayton 8 месяцев назад
If you want fields, but no underscores...don't add underscores 🤷‍♂ Seriously, who's holding a gun to your head?
@eesaaphilips9271
@eesaaphilips9271 11 месяцев назад
I don't like that EF Core, and System.Text.Json don't read fields but props only by default. It forces me to use props when I don't want to
@andrewmcclement4464
@andrewmcclement4464 11 месяцев назад
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).
@etiennelemieux472
@etiennelemieux472 11 месяцев назад
The underscore seems to be discouraged from VS sometimes. Maybe because I installed Resharper some years ago, but on my private PC, I cannot force VS to generate underscore for private members, and even in Microsoft documentation you can see private members starting with lowercase letters. I hope this won't become a standard.
@codingbloke
@codingbloke 11 месяцев назад
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.
@codefoxtrot
@codefoxtrot 11 месяцев назад
Clearly the author of this post has a fundamental misunderstanding of the language and is inexperienced. Also, one of the key things to ask yourself when you learn something new, is "when should I be using this technique?" Anyway, I love this series, please keep writing these traffic tickets.
@olliet666
@olliet666 11 месяцев назад
Sure, but properties do not only exist for the sake of encapsulation. Otherwise there would be no private properties, right? Yet private properties are perfectly legal. And the 'terrible thing' that happens is that an automatic getter method is created? If anything, that is a minuscule overhead. IMO, it looks nicer without the underscores or having to use the 'this' identifier. The Pascal casing clearly indicates that this refers to internal state, just like an underscore does. I think I will use private properties in the future!
@allothernameswherealreadytaken
@allothernameswherealreadytaken 11 месяцев назад
One thing I think is annoying is that a class with both public and private values/fields becomes cluttered and feels inconsistent (because there’s a mix of “PropertyExample and _fieldExample in your code). This feels really ugly. If I’d recreate C# from scratch I would probably make the syntax more like in typescript/javascript than having two completely different ways to do two very similar things.
@skyswimsky1994
@skyswimsky1994 11 месяцев назад
I don't think using private properties is "outright wrong" and "absolutely stupid and moronic" like some comments seem to make it out to be that you should lose your job etc., though I do think the reasons listed aren't great, and I was hoping for a more grounded explanation. But I guess it does simply come down to what you prefer.
Далее
"Remove Braces From Your Code Now!" | Code Cop #004
8:36
Don't Use Polly in .NET Directly. Use this instead!
14:58
Witch changes monster hair color 👻🤣 #shorts
00:51
КАК БОМЖУ ЗАРАБОТАТЬ НА ТАЧКУ
1:36:32
"Stop Using Automapper in .NET!" - Code Cop #001
9:57
Просмотров 113 тыс.
CARLSEN VS NEPO, ARMAGEDDON!
29:32
Просмотров 88 тыс.
Properties vs. Fields in C#
11:13
Просмотров 8 тыс.
Brutally honest advice for new .NET Web Developers
7:19
how Google writes gorgeous C++
7:40
Просмотров 889 тыс.
"Your Code Has a SQL Injection!" | Code Cop #007
12:11
"The readonly Keyword Is Useless!" | Code Cop #012
9:42
Witch changes monster hair color 👻🤣 #shorts
00:51