Using getter/setter vs “tell, don't ask”?

后端 未结 4 1530
春和景丽
春和景丽 2021-02-05 02:35

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

4条回答
  •  长情又很酷
    2021-02-05 03:15

    One reason that comes to mind is the ability to decide where you want the control to be.

    For example, with your setter/getter example, the caller can change the Warrior's health arbitrarily. At best, your setter might enforce maximum and minimum values to ensure the health remains valid. But if you use the "tell" form you can enforce additional rules. You might not allow more than a certain amount of damage or healing at once, and so on.

    Using this form gives you much greater control over the Warrior's interface: you can define the operations that are permitted, and you can change their implementation without having to rewrite all the code that calls them.

提交回复
热议问题