Advantage of set and get methods vs public variable

zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz picture zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz · Jun 17, 2012 · Viewed 57.4k times · Source

Possible Duplicate:
Why use getters and setters?

Is there any advantage to making methods to access private variables in your class instead of making the variable public?

For example is the second case better than the first?

//Case 1
public class Shoe{
    public int size;
}

//Case 2
public class Shoe{
    private int size;
    public int getSize(){
        return size;
    }

    public void setSize(int sz){
        size = sz;
    }

}

Answer

dantuch picture dantuch · Jun 17, 2012

What I have seen someday on SO, as answer (written by @ChssPly76) why to use getters and setters

Because 2 weeks (months, years) from now when you realize that your setter needs to do more than just set the value, you'll also realize that the property has been used directly in 238 other classes :-)

there are much more advantages:

  1. getters and setter can have validation in them, fields can't
  2. using getter you can get subclass of wanted class.
  3. getters and setters are polymorphic, fields aren't
  4. debugging can be much simpler, because breakpoint can be placed inside one method not near many references of that given field.
  5. they can hide implementation changes:

before:

private boolean alive = true;

public boolean isAlive() { return alive; }
public void setAlive(boolean alive) { this.alive = alive; }

after:

private int hp; // change!

public boolean isAlive() { return hp > 0; } // old signature 
 //method looks the same, no change in client code
public void setAlive(boolean alive) { this.hp = alive ? 100 : 0; }

EDIT: one additional new advange when you are using Eclipse - you can create watchpoint on field, but if you have setter you need just a breakpoint, and... breakpoints (e.g. in setter method) can be conditional, watchpoints (on field) cannot. So if you want to stop your debugger only if x=10 you can do it only with breakpoint inside setter.