Tell, don\'t ask principle here is often pasted to me when I use getters or setters, and people tell me not to use them. The site clearly explains what I should and what I shoul
You still need the same amount of methods (increase/decrease vs set/get) and you lose the benefit of asking if you ever need to ask.
You got it wrong. The point is to replace the getVariable
and setVariable
with a meaningful operation: inflictDamage
, for example. Replacing getVariable
with increaseVariable
just gives you different more obscure names for the getter and setter.
Where does this matter. For example, you don't need to provide a setter/getter to track the armor and health differently, a single inflictDamage
can be processed by the class by trying to block (and damaging the shield in the process) and then taking damage on the character if the shield is not sufficient or your algorithm demands it. At the same time you can add more complex logic in a single place.
Add a magic shield that will temporarily increase the damage caused by your weapons for a short time when taking damage, for example. If you have getter/setters all attackers need to see if you have such an item, then apply the same logic in multiple places to hopefully get to the same result. In the tell approach attackers still need to just figure out how much damage they do, and tell it to your character. The character can then figure out how the damage is spread across the items, and whether it affects the character in any other way.
Complicate the game and add fire weapons, then you can have inflictFireDamage
(or pass the fire damage as a different argument to the inflictDamage
function). The Warrior
can figure out whether she is affected by a fire resistance spell and ignore the fire damage, rather than having all other objects in the program try to figure out how their action is going to affect the others.