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 Жыл бұрын
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 Жыл бұрын
Well its their job getting paid off view so they gotta bait the clicks 😂 i hate tech influencers
@verzivull Жыл бұрын
can it be an advice from chatgpt?
@envo2199 Жыл бұрын
its called rage bait posting.
@samsim4648 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@slowjocrow6451 For data struct members, one often doesn't want even the minuscule indirection of a property when doing high performance data processing.
@PlerbyMcFlerb Жыл бұрын
@@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
@amirhosseinahmadi3706 Жыл бұрын
Rule #1: Never take advice from someone who calls fields "class member variables".
@Z3rgatul Жыл бұрын
Good one 🤣
@EdKolis Жыл бұрын
I remember a series of otherwise decent C# tutorials on KZbin that insisted on calling fields "attributes". Yeah, that's totally not going to get confusing later...
@JoeRomano-s8g11 ай бұрын
😂😂
@MrMatthewLayton9 ай бұрын
"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".
@joergw Жыл бұрын
I am using private readonly fields without underscore - 100% agree with Nick 🙂
@dr_Bats Жыл бұрын
I hate underscores. I use this to access class private members. Thanks Nick for agreeing with me. 😄
@the-niker Жыл бұрын
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 Жыл бұрын
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
@JohnWII Жыл бұрын
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.
@qtxsystems Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
How does that improve readability at all? I dont get it...
@MostlyPennyCat Жыл бұрын
@@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 Жыл бұрын
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 Жыл бұрын
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 :)
@VeggehGaming Жыл бұрын
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 Жыл бұрын
I like underscores in private field names. It highlights them as what they are, and I immediately know how to handle them.
@dantecavallin8229 Жыл бұрын
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 Жыл бұрын
@@dantecavallin8229 this is exactly how it was designed in python, where everything is public, underscore just suggest not to use it
@brianviktor8212 Жыл бұрын
@@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 Жыл бұрын
@@brianviktor8212 I do the underscore only for backing fields if I need them for a property.
@neralem Жыл бұрын
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 Жыл бұрын
I got fooled by your avatar! I really thought I had a fly on my screen.🤣🤣🤣
@sealsharp Жыл бұрын
@@alfflasymphonyx Me too. You got me.
@massimoandreasibassi7016 Жыл бұрын
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.
@MarkAdamson-Eddie Жыл бұрын
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.
@mrShot94 Жыл бұрын
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 Жыл бұрын
That's what break on value change can already do. It just shows the person has no clue how to use a debugger
@joshman1019 Жыл бұрын
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.
@vargonian Жыл бұрын
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.
@OnnoInvernizzi11 ай бұрын
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.
@TazG2000 Жыл бұрын
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.
@raldotromp Жыл бұрын
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.
@asteinerd Жыл бұрын
"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 Жыл бұрын
Not sure. For auto properties an optimization should work which uses the field directly without get/set method
@proosee Жыл бұрын
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.
@BearJewOo Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@Integer0 Жыл бұрын
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.
@nanvlad Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
@@nanvlad thank you
@heiko316910 ай бұрын
You are violating clean code rules already by declaring a class inside another class.
@GufNZ Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
You should *always* use an underscore prefix for intellisense. At a lower level, it's the standard way for expressing intent.
@jamesroot9777 Жыл бұрын
The 9 points just look like something ChatGPT would generate.
@AlFasGD Жыл бұрын
From my experience with ChatGPT, it would be smarter than those stupid ideas and arguments against fields.
@ferd1775 Жыл бұрын
@@AlFasGD I agree, but I think they asked it to generate an article arguing FOR it..cus it will do that haha
@baetz2 Жыл бұрын
@@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 Жыл бұрын
More and more, they might actually be so.
@kzryzstof Жыл бұрын
"It should be readonly" Love it and I can't help protecting fields as much as possible.
@denissmith82828 ай бұрын
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.
@PPSzB Жыл бұрын
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
@SG_01 Жыл бұрын
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.
@ferd1775 Жыл бұрын
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 Жыл бұрын
I bet they use the 9 reasons from chat gpt
@chlorobyte_projects Жыл бұрын
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 Жыл бұрын
f... each comment makes it sound more and more like chatgpt
@ferd1775 Жыл бұрын
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
@Ayymoss Жыл бұрын
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.
@sajilicious Жыл бұрын
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 Жыл бұрын
this is it.
@SecondFinale Жыл бұрын
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.
@insa07 Жыл бұрын
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 Жыл бұрын
The case that we don't have any 'public' members - they all private
@AlFasGD Жыл бұрын
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 Жыл бұрын
There's no way they're referring to binary compability considering the rest of the post.
@AlFasGD Жыл бұрын
@@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 Жыл бұрын
Except they made the property private which means it's not part of the public API.
@francoislepron2301 Жыл бұрын
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.
@TubeAccount-b1f Жыл бұрын
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
@DaneWithADrone Жыл бұрын
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
@MilanDendis Жыл бұрын
Definitely fields is my choice. And that underscore helps me to know i'm using a private field later in code.
@minhhieugma Жыл бұрын
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.
@paulp4061 Жыл бұрын
One benefit of private properties over private fields is that for properties VS codelens shows reference count which can sometimes be handy
@eradubbo Жыл бұрын
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 Жыл бұрын
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
@fxandrei11 ай бұрын
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
@nickpolyderopoulos3491 Жыл бұрын
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
@vyrp Жыл бұрын
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 Жыл бұрын
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.
@shalopo Жыл бұрын
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 Жыл бұрын
lol, I was about to point out private fields would not be accessible externally, then read your last line.
@EdKolis Жыл бұрын
But what if the caller is using reflection to access private members? 😛
@lordicemaniac Жыл бұрын
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;
@mariocamspam72 Жыл бұрын
Some of these posts are the computer equivalent of wives' tales
@computer9764 Жыл бұрын
@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 Жыл бұрын
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 Жыл бұрын
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 :(
Жыл бұрын
I'm not a good fan to use underscore for private fields , but I understand your logic.
@supern4ut3 Жыл бұрын
I Agreed.
@CRBarchager Жыл бұрын
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 Жыл бұрын
@@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.
@meowzhin Жыл бұрын
Prefix/Sufix for classes and interfaces, _ for private members, UPPER_CASE for constants and $ for observables. This is the way.
@TheDiggidee Жыл бұрын
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
@ratherbyexploring4898 Жыл бұрын
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
@alexandernava9275 Жыл бұрын
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).
@iSoldat Жыл бұрын
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 Жыл бұрын
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.
@ScottGarryFoster Жыл бұрын
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.
@m4ster_root Жыл бұрын
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.
@davidcfrogley Жыл бұрын
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?
@KennethSiewersMller Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Shift + Alt + F11 / Ctrl + Alt + (PgUp | PgDown)
@KennethSiewersMller Жыл бұрын
@@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 Жыл бұрын
@@rpenha yes, I know, it I’m talking about the inline hints Rider shows for properties and methods.
@gabrielfkrk Жыл бұрын
@@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
@ExpensivePizza Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
And some of us are so old school we use camel case for fields...
@andrewmcclement4464 Жыл бұрын
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).
@billy65bob Жыл бұрын
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.
@antonmartyniuk Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@phizc you can do this, but the whole idea behind primary constructors is to decrease amount of code you write
@stephenyork7318 Жыл бұрын
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.
@IDrDoh Жыл бұрын
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)
@HilelHadjAli10 ай бұрын
fortunately Nick chapsas exists
@TheXX113 Жыл бұрын
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.
@pavelromashuk237 Жыл бұрын
Good shot, Nick!
@FR12321 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 :)
@DlinnyLag Жыл бұрын
Thanks. Commented on this LinkedIn post
@CyberAngel67 Жыл бұрын
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.
@MilYanXo Жыл бұрын
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.
@travisabrahamson8864 Жыл бұрын
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.
@artemisDev Жыл бұрын
I had quite the good laugh at that picture.
@tangomoocow Жыл бұрын
Feels very much like somebody churning out content from a LLM and either not checking it or not understanding it in the first place.
@YancyLi-t5n Жыл бұрын
Hello Nick, great lesson to me, and I wonder how do you auto fix the sting to string at 5:58?
@br3nto Жыл бұрын
I agree with the underscore comment. The _ style is just not needed anymore. It makes code feel old and yucky.
@sergius_carp Жыл бұрын
Regarding "versioning", I suspect they meant you can substitute "{ get; }" with some computation logic without changing the rest of the class.
@bradoestreicher3476 Жыл бұрын
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.
@EdKolis Жыл бұрын
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...
@allothernameswherealreadytaken Жыл бұрын
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.
@stevestrong9363 Жыл бұрын
I love this series! I take a drink every time I guess what you are going to say!
@Snikersano Жыл бұрын
XD
@astrokotik6887 Жыл бұрын
This is madness! THIS IS CODE REFACTORING!
@ianmcpherson2301 Жыл бұрын
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 Жыл бұрын
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.
@WilliamCWayne Жыл бұрын
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 Жыл бұрын
For an injected member, no less!
@RainFerret Жыл бұрын
Pointing out that fields have _underscores to allow you to easily see which they are is another reason I'm not too keen on the new C# 12 constructors: they create camel case fields.
@kylekeenan3485 Жыл бұрын
Your thumbnail was definitely giving me YMCA vibes 😂
@klocugh12 Жыл бұрын
Cue naming properties starting with underscores out of spite 😂 And someone should tell them about Lazy
@vchap01 Жыл бұрын
Lazy initialization (not loading) can be nicely abstracted by a property even if it is private. That's about the only real life use case I can think of.
@anm3037 Жыл бұрын
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.
@etiennelemieux472 Жыл бұрын
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.
@florianmartingrimm8055 Жыл бұрын
its a private property - no ABI reason - no versioning reason - its just slow - if you hate underscore add an editorconfig file and adjust it
@Kirill-l7c9y Жыл бұрын
I see just one pros in private get property. It is a possible to set a breakpoint on getter. In multithread code it may be matter. Does private getter inline in runtime?
@KnightSwordAG Жыл бұрын
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*
@timseguine2 Жыл бұрын
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.
@markovcd Жыл бұрын
No underscore, no "this." master race reporting in.
@99aabbccddeeff Жыл бұрын
Sometimes it's really awful to see these "Good Tips". I think these people don't understand they are talking about. Thanks for your video Sheriff. As alway, awesome :)
@Ilix42 Жыл бұрын
With modern tooling, I'm not a big fan of using a prefix to indicate class level variables as it adds more keystrokes before any autocomplete features become useful; I'd rather see the character as a suffix. That said, one extra keystroke doesn't really matter in practice, so it's more of a thing that just kind of bothers me. And not nearly enough that I would consider using private properties to avoid the class level prefix.
@mrwillis5339 Жыл бұрын
There is a reason why private properties can make sense. You can differentiate them from private fields and what has been injected. Of course, this is a bit weak, naming convention can overcome it. On my private code bases, the style has changed towards private fields, but there is definitely some mess in older libraries. Stopped doing logic inside setters/getters years back - maybe with vba. Have seen all manner of variations and am not going to go ape over it.
@muhammadtariq8323 Жыл бұрын
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
@ondrejvrabek9485 Жыл бұрын
Geter instead of property recomendation is probably from time before readonly(or init) was added. Is not?