Getter-Setter and private variables

genonymous picture genonymous · Feb 25, 2014 · Viewed 14.7k times · Source

If I can change the value of private variable through getter-returned reference then isn't it bypassing the setter method? Doesn't it defeat the purpose of getter-setter and private variables

public class Test{

private Dimension cannotBeChanged;

public Test(int height, int width)
{
    if(height!=3)
       cannotBeChanged.height = height;
    if(width!=3)
       cannotBeChanged.width  = width;
}

public Dimension getDimension()
{
    return cannotBeChanged;
}


public void setDimension(int height, int width)
{
    if(height!=3)
       cannotBeChanged.height = height;
    if(width!=3)
       cannotBeChanged.width  = width;    
} 

 public static void main(String [] args)
{
    Test testOne = new Test(5,5);
    Dimension testSecond = testOne.getDimension();
    testSecond.height = 3; //Changed height and width to unwanted values
    testSecond.width= 3;
}

Answer

Abimaran Kugathasan picture Abimaran Kugathasan · Feb 25, 2014

Yes, It does. I have the following conclusion in getters and setters from the Clean Code book; you can use it if you really accept it.

  1. Very evil: public fields.
  2. Somewhat evil: Getters and setters where they're not required.
  3. Good: Getters and setters only where they're really required - make the type expose "larger" behaviour which happens to use its state, rather than just treating the type as a repository of state to be manipulated by other types.