Just wondering...
Is there any reasons not to use protected properties?
I mean instead of using this:
public abstract class Foo
{
protected Bar { get; private set; }
}
to use this one:
public abstract class Foo
{
private Bar _bar;
protected Foo(Bar bar)
{
_bar = bar;
}
protected GetBar()
{
return _bar;
}
}
Protected variables should be avoided because: They tend to lead to YAGNI issues. Unless you have a descendant class that actually does stuff with the protected member, make it private. They tend to lead to LSP issues.
- Private data members cannot be accessed outside the class. - When a class inherits a base class, all the data members except the private get inherited into it. So if we want data members to be accessible to only derived classes and not privately or publicly accessible, then we can use protected.
In short, yes. Protected member variables allow access to the variable from any sub-classes as well as any classes in the same package. This can be highly useful, especially for read-only data.
Use protected if subclasses will use the method/variable, otherwise use private. Specifically, if subclasses would have to re-define a very similar private variable in the parent, just make it protected.
I don't see any reason why you would use a GetXXX()
method instead of a property regardless of it's modifiers.
Since you tagged this question with C#
tag, I strictly recommend using the first approach. That is what properties are for.
Use a method only when value returned by it can be different every time you call it regardless of it's state. For example, DateTime.Now
was a mistake and should have been a method.
For more details refer to Property Usage Guidelines on MSDN
. On a side note, it's surprising how they haven't had a need to change it since Framework 1.1
.
A few more reasons to use properties instead of methods:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With