I know the ‘data hiding’ concept of OOP, but in real devolopment it always is challanged when the specications are changed.
For example:
class role
{
std::string name;
int level;
public:
const std::string& get_name() { return name; }
void set_name(const std::string& value) { name = value; }
void set_level(int value) { level = value; }
int get_level() const { return level; }
}
Of course, there is nothing wrong with this code. But name and level are’t encapsulated at all, I thought.
My opinions as follows:
- User can modify data by setter function.
- setter/getter expose data type of those data member. If those data member have to change their type, setter/getter function member have to change their interfaces,too.
- If I need another operation for
levelmember, adding more operation member (e.qadd_level(int value)orsub_level(int value)etc.) functions is the only way. - Just one thing is fine. If
get/sethave to add some judgements to them, these interfaces can work well.
So, what kind of data member should I encapsulate? I can’t predict the scale and usage at all with those data members. If I expose them directly, operations on them will be completly simple, clear, and make sense. If I encapsulate them, I would make lots of operation members for them, and if someday their type changed by spec (int -> class, class -> int), my operation members must change their interface or kill them all directly (because I will send them to public zone, once for all!).
I have been reading on many different languages, and notably functional languages, and I have slowly come to question the idea of setters.
Suppose that I have a class
Person, this is what I would have written some years ago:You will note how similar it is to your own class.
Personchange during the lifetime of the object ?Personchange during the lifetime of the object ? What could be we do to avoid this situation ?_name: changing it would break thename()getter…And now, an alternative implementation, which is what I would write today:
This class no longer have any setter. This class no longer return any handle to its internals (I’ll pay the price of the copy therefore, probably won’t amount to much anyway).
The most notable point however is that I changed how I memorized the information: the
ageis a fluctuating value derived from the birth date and the current date. Therefore, why memorizing a byproduct rather the source ?And I want to change the value ? Well:
works well enough. And at least I only write my invariants once (in the constructor).
Obviously, this does not necessarily applies everywhere. If your class only has a few fields though it works well; when your class gets more fields, maybe it’s time to extract some of them into classes of their own.