aime
aime

Reputation: 247

Open/Closed principle and violation of encapsulation

Could you please check if the following code is correct or not? The fact is that I found something similar in propduction code and I have doubt if it matches Open/Closed principle.

public abstract class CustomClass {

    private ClassThatSetEnvironmentProperty sysProp = new ClassThatSetEnvironmentProperty("SYS_PROPETY", "SYS_PROPERTY_VALUE");

    // some code here

    void setSysProp(ClassThatSetEnvironmentProperty sysProp) {
        this.sysProp = sysProp;
    }
}

My understanding is the setter is defined for unit-tests possibilities only (to mock ClassThatSetEnvironmentProperty). But in this case the setter allows concrete inheritants to change defined state. From my perspective it violates encapsulation. More over I think that it is also violates open/closed prinicple. Frankly, some of my coleagues takes an opposite view. I really have not to much experience so it is hard for me to recognise it. Please share your opinion here. Thank you.

Upvotes: 0

Views: 416

Answers (1)

Silas Reinagel
Silas Reinagel

Reputation: 4203

This doesn't directly relate to the Open Closed Principle, The Open Closed Principle just means that to add new behavior to your system you should create a new implementing class rather than change old ones. Using an abstract class for that is fine.

The one thing that does violate encapsulation (which is a different principle) is the package-accessible dependency setter. You can fix that issue by changing it to be a protected setter. Then extending classes can set their own, but outside callers cannot change the states of your objects.

protected final void setSysProp(ClassThatSetEnvironmentProperty sysProp) {
    this.sysProp = sysProp;
}

Upvotes: 5

Related Questions