Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason not to use 'protected' properties?

Tags:

c#

.net

protected

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;
    }
}
like image 249
pencilCake Avatar asked Feb 01 '11 13:02

pencilCake


People also ask

Are protected variables bad practice?

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.

Why and when do we use protected instead of private?

- 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.

Should you use protected in Java?

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.

Should I use private or protected Java?

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.


2 Answers

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.

like image 167
decyclone Avatar answered Nov 02 '22 23:11

decyclone


A few more reasons to use properties instead of methods:

  • Data binding can only see properties
  • You can use read only or write only semantics.
like image 39
Edwin de Koning Avatar answered Nov 03 '22 00:11

Edwin de Koning