3 Matching Annotations
- Jun 2023
-
stackoverflow.com stackoverflow.com
-
Are protected members/fields really that bad? No. They are way, way worse. As soon as a member is more accessible than private, you are making guarantees to other classes about how that member will behave. Since a field is totally uncontrolled, putting it "out in the wild" opens your class and classes that inherit from or interact with your class to higher bug risk. There is no way to know when a field changes, no way to control who or what changes it. If now, or at some point in the future, any of your code ever depends on a field some certain value, you now have to add validity checks and fallback logic in case it's not the expected value - every place you use it. That's a huge amount of wasted effort when you could've just made it a damn property instead ;) The best way to share information with deriving classes is the read-only property: protected object MyProperty { get; } If you absolutely have to make it read/write, don't. If you really, really have to make it read-write, rethink your design. If you still need it to be read-write, apologize to your colleagues and don't do it again :) A lot of developers believe - and will tell you - that this is overly strict. And it's true that you can get by just fine without being this strict. But taking this approach will help you go from just getting by to remarkably robust software. You'll spend far less time fixing bugs.
In other words, make the member variable itself private, but can be abstracted (and access provided) via public methods/properties
-
Public and/or protected fields are bad because they can be manipulated from outside the declaring class without validation; thus they can be said to break the encapsulation principle of object oriented programming.
-
Using a property or a method to access the field enables you to maintain encapsulation, and fulfill the contract of the declaring class.
Tags
- properties vs. direct access to instance variables
- I agree
- member visibility: make it private unless you have a good reason not to
- contract (programming)
- breaking encapsulation
- encapsulation (programming)
- using properties to abstract, encapsulate, and control access to private instance variables/data
Annotators
URL
-