+ 2

Is it good to set all variables as public at the beginning of creating a class?

I'm making a bigger application using C#. There are tens of different classes. When I'm creating another class I set all members public, because I don't know which of them I will use from other classes. I change access modifiers to private when I end work with this classes. Is it a good habit? Maybe is it better to set all members private and then, when it is necessary, change them to public?

22nd Dec 2016, 12:12 AM
Jan Mróz
Jan Mróz - avatar
4 odpowiedzi
+ 6
It is always best to program with the mindset of Object Oriented Programming. This means setting all member variables to private and all methods or functions to public. This way you are building robust programs with member variables that cannot be accessed publicly (which may lead to problems down the line). I hope this helps! Gud Luk! -bErN
22nd Dec 2016, 12:16 AM
bernscode
bernscode - avatar
+ 2
@Jan you sound like Carten from South Park.
28th Jan 2017, 7:26 AM
Steven Bennett
Steven Bennett - avatar
- 1
It depends on the class, really. When you are defining a class, you shouldn't really consider all too much about what other classes are going to need from it. What you should care about is what functionality the class itself is going to provide through its methods. If outside objects don't need to poke at a variable to make the class do it's job (usually some kind of internal state), keep it private or protected. If you an external class does need access to a variable (for instance, to configure some settings) if you need that variable to be in certain valid states (like references can't be null) then have it private but exposed through getters and setters that validate its data. If this is not needed then it can be public just fine.
22nd Dec 2016, 12:42 AM
Thomas Stone
Thomas Stone - avatar
- 1
Thank you for your answers! @bErNbLeNd - I don't think it's the best method in C#, maybe it's good in C++ or other languages. Setting all variables private and than write functions to access them can result with too much needless code in C#. Because in C# you can get and set public variables through special accessors and tell the program what it must do when the value you want to assign is wrong. It's something like the variable with integrated read and set functions. @Thomas Stone Thanks for full of knowledge answer! It really helps to understand how classes and their members work. So, refer to my question, do you think it is better to consider access-modifiers and accessors at the beginning of scripting and than, at the end, check if they are setted correctly?
22nd Dec 2016, 2:33 PM
Jan Mróz
Jan Mróz - avatar