Search code examples
javadesign-patternsencapsulation

Encapsulation over engineering


In the doJob() method, B is referenced through getter. I personally do not favor this idea and would prefer just b.execute() since I know for sure that getB() will never be modified.

I know that by doing this, would be moving away from encapsulation, but isn't encapsulating B object an overkill here?

class A{
    private B b;

    public void setB(B b){
         this.b = b;
    }

    public B getB(){
         return b;
    }

    public void doJob(){
       getB().execute();
    }
}

Solution

  • It really doesn't matter if you access B through its attribute or getter as long as the attribute remains private (so yes, calling getB() is an overkill, it certainly doesn't break any design pattern).