What question answers the behavior of the object?

Reading a book I found the following statement:

(Object) Behavior answers one of two questions: what does this object do (for me)? or What can I do with this object? In the case of an orange, this does not do much, but we can do something. One of the actions is to eat it.

In my understanding of the behavior of the object, the above statement is true regarding the first question and is not true in the case of the second. However, I often see classes with methods such as Orange :: eat (), and this clearly defines my design skills. So I would like to ask if there is a design error to give the oranges any behavior? (oranges and food are used, for example, only)

+3
source share
3 answers

I think that there is nothing wrong with your way of thinking about objects and their responsibilities. Orange::eat()it would make sense if oranges had mouths. Otherwise, this Animalis what makes the food.

The fact is that SVO (Subject-Verb-Object) sentences are not always the best way to describe something, but OOP seems to be very biased towards such a statement, so we often come across strange, unnatural and abstract constructions of sentences in code .

+3
source

Let's take a classic Employee pattern. "What can I do for this object" means:

void SetSalary (int value);

Eating an orange is not an orange method, it is a Person method:

void Eat(Orange& orange);
+1

, , . , , , , .

With this obvious example, the answer is simple, but it becomes more complex in real life scenarios; you can take a look at Agile Principles, Patterns and Practices in C # by Robert Martin. Follow at least a few scenarios and understand who is doing what, etc.

+1
source

Source: https://habr.com/ru/post/1736075/


All Articles