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:
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++.
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.
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:
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.