Avoid "empty" getters/setters

I am writing a Connect four application that is eventually gonna be connected to a Qt GUI. I have read that writing empty getters and setters should be avoided in OOP. By "empty", I mean that it deals directly with the members variables, without any verification to be done on them. The getters simply returns the member variable, the setters only mutates it. For example, in my application I have a Token class:

1
2
3
4
5
6
7
8
9
10
11
class Token
{
public:
    unsigned int getColor() const
    {
        return m_color;
    }

private
    unsigned int m_color;
};


The getColor() getter is clearly "empty". I will need to access this value in other classes, or in the main later on. How can I do that without making the member variable public, and respect encapsulation?

I have found many articles saying that empty getters setters are "evil", but not so many on how to avoid them, especially in C++.

Your help would be greatly appreciated!
Last edited on
Sometimes it's necessary, but too many, too often is usually a sign of bad design. Why do you need this value? What calculation are you performing with it? Is the calculation actually something that should be done within the class? If something else needs it and this Token class doesn't do anything with it, why doesn't that something else contain it?
Moschops: your point is that the goal is not necessarily to remove them, but to avoid them as much as possible?

For example, I might wanna use it in the main function (console mode) to be able to print the color of the token a specific player has chosen. Then I might have to write something like:

 
    cout << player.getToken().getColor();


where both getters are empty. I could create a getColor() directly in the player, but would still need to access the token color.

Thanks for your reply.
I would say that objects should be responsible for themselves. If the object is supposed to dump a value to cout, then the object should do that on request. Either have the object call cout <<m_color; itself, or give the object a function you can call in which you specify the outstream:

1
2
3
4
    void writeColourToStream(ostream& stream) const
    {
        stream << m_color;
    }
Mischops: Interesting, I understand what you mean.

Thanks a lot, I will meditate on that!
This is something of a toy example, but the principle is sound. Objects should look after themselves; it makes code easier to design, easier to reason about, easier to maintain, reduces coupling. It's just helpful all round.
Topic archived. No new replies allowed.