Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected readonly field vs protected property

Tags:

c#

oop

I have an abstract class and I'd like to initialize a readonly field in its protected constructor. I'd like this readonly field to be available in derived classes.

Following my habit of making all fields private and exposing properties, I implemented this as follows:

abstract class Foo
{
    private readonly int _field;

    protected Foo(int field)
    {
        _field = field;
    }

    protected int Field
    {
        get { return _field; }
    }
}

But then I wondered if there is really much advantage of keeping the field private here. I'm aware of the advantages of properties and there are several SO questions on this issue in general, but they focus on public fields as opposed to protected ones.

So should I switch to the below implementation or not? What are the considerations and advantages/disadvantages to be aware of in either case?

abstract class Foo
{
    protected readonly int _field;

    protected Foo(int field)
    {
        _field = field;
    }
}
like image 569
Zaid Masud Avatar asked Oct 23 '12 11:10

Zaid Masud


2 Answers

I'd leave the implementation or go with:

protected Field {get; private set;}

(not exactly the same as Field is not readonly for the parent class)

The advantage of properties over fields is they are more future proof. You can change the implementation on the parent class without affecting the children. Without the property you're committed to the field always being readonly. Using fields is frowned upon for another reason, they hurt opacity: the class describes the exact implementation of the field.

So yes, leave the encapsulation.

The only place where I would consider using fields directly for readability is in highly coupled classes such as the states in a state pattern, but in this case the classes themselves would be private.

like image 28
Eli Algranti Avatar answered Sep 20 '22 12:09

Eli Algranti


Derived classes are still 'users' of the original code; fields should be encapsulated from them too.

You should think of base classes as safe and extendable APIs, rather than just classes which expose their internals. Keep the fields private - apart from anything, it allows the base class to change how that property's value is generated :)

like image 82
Lawrence Wagerfield Avatar answered Sep 19 '22 12:09

Lawrence Wagerfield