When are Getters and Setters Justified

Posted by Winston Ewert on Programmers See other posts from Programmers or by Winston Ewert
Published on 2010-11-26T22:24:27Z Indexed on 2011/11/19 18:14 UTC
Read the original article Hit count: 390

Filed under:

Getters and setters are often criticized as being not proper OO. On the other hand most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example Procedural version of code.

struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}

Mutator version of code:

class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);        
}

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

© Programmers or respective owner

Related posts about object-oriented