i heard that getters and setters are bad but idk |
getters and setters are bad, but not just because they are useless code. It's because they ruin object-oriented design.
Let's look at health, for example: you have a get_health(), which is fine (except that it should be const, of course), if it makes sense for someone else to be able to quanitfy how healthy a player is just by looking at him, but what is set_health() supposed to
mean?
So you walk around the world and suddenly some external force comes in and makes your health a totally different number? It's a lot more likely that your health will
change, as a consequence of getting hurt or resting up instead. Resting is something a player can do, setting the health is not.
Besides failing to model the object behavior, setters introduce tight coupling, because the logic that belongs to your class now sits elsewhere: if you bump into a tree, the tree has to communicate your new health value to you, and for that to happen, the tree has to read your current health value, real your other attributes (toughness, etc) factor in your speed and angle and whatever other variables are needed, and send back your new health value. The tree now knows all about the player. Even if you factor out your health change calculations to some sort of GameMechanics class, it's still never going to make sense to have a public member function called "set_health()" on a player.
PS: do try to use proper syntax for constructors, it's
1 2 3 4 5
|
player::player()
: health(100),
money(35),
score(0)
{ }
|
PS: of course there are classes where setters make sense: std::vector has a setter called resize(), for example, because resizing is what vectors do. Note that it doesn't just change one member variable, though.