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

后端 未结 4 1567
春和景丽
春和景丽 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:34

    At my point of view, both codes do the same thing. The difference is in the expressivity of each one. The first one (setters anad getters) can be more expressive than the second one (tell, don' ask).

    It's true that, when you ask, you are going to make a decision. But it not happens in most part of times. Sometimes you just want to know or set some value of the object, and this is not possible with tell, don't ask.

    Of course, when you create a program, it's important to define the responsabilities of an object and make sure that these responsabilities remains only inside the object, letting the logic of your application out of it. This we already know, but if you need ask to make a decision that's not a responsability of your object, how do you make it with tell, don't ask?

    Actually, getters and setters prevails, but it's common to see the idea of tell, don't ask together with it. In other words, some APIs has getters and setters and also the methods of the tell, don't ask idea.

提交回复
热议问题