Search code examples
ooprefactoringencapsulation

What are the benefits of self encapsulation?


While reading some refactoring practices I stumbled upon this article

The author arguments to modify below code with getter and setters, I think they should be private but anyways what's the benefit in doing so? aren't we introducing the function call overhead?

Before:

private int _low, _high;
boolean includes (int arg) {
  return arg >= _low && arg <= _high;
}

After:

private int _low, _high;
boolean includes (int arg) {
  return arg >= getLow() && arg <= getHigh();
}
int getLow() {return _low;}
int getHigh() {return _high;} 

Solution

  • Let's say, for some reason you need to change the names of your class attributes from _low, _high to _min, _max. In the 1st version, you need to modify the includes() function as well. In the 2nd version you only need to modify the getters. In your example the benefit is small, but in a bigger class it could save you a lot of work.

    A slightly more complex example where the upper value is no longer stored but derived from the lower value and an interval:

    private int _low, _interval;
    boolean includes (int arg) {
        return arg >= getLow() && arg <= getHigh();
    }
    int getLow() {return _low;}
    int getHigh() {return _low + _interval;}
    

    Again you only need to modify the getter.

    Concerning the overhead: Depending on the language you are using, your compiler will optimize the function call away.