Are trivial protected getters blatant overkill

encapsulationinheritanceobject-oriented-designproperties

Something I really have not thought about before (AS3 syntax):

private var m_obj:Object;
protected function get obj():Object
{
    return m_obj;
}

private var m_str:String;
protected function get str():String
{
    return m_str;
}

At least subclasses won't be able to set m_obj or m_str (though they could still modify m_obj).

My question: Is this just blatant overkill?


This Programmer's question:
When or why should one use getters/setters for class properties instead of simply making them public properties?
has been suggested as a duplicate.

That question is different because it only addresses public vs. private properties and whether a property should be wrapped with getters & setters. For my question, I'm focusing on protected variables and how inheriting classes would interact with those variables.

So the alternative implementation would be:

protected var m_obj:Object; //more accessible than a private variable with a protected getter
protected var m_str:String; //more accessible than a private variable with a protected getter

My question is similar because I am talking about using trivial protected getters to block subclasses from writing to the variables, but to allow them all other access.
In languages like AS3, this will even allow them to make any changes to mutable object variables, as long as the references themselves are not modified.

Best Answer

Is this just blatant overkill?

Often times it is, sometimes it's not.

Keeping m_obj in some known good state helps protect the Liskov Substitution Principle, keeping your code more resilient and higher quality. Sometimes you can trust inheritors to respect that behavior, sometimes you can't (either due to usage pattern or the subtlety of the contract it implements). Though this code/question also stumbles towards some of the reasons for "Why is Clean Code suggesting avoiding protected variables?"

Related Topic