views:

76

answers:

3

Reading a book I have found the following statement:

(Object) Behaviors answer either of two questions: What does this object do (for me)? or What can I do to this object? In the case of an orange, it doesn’t do a whole lot, but we can do things to it. One behavior is that it can be eaten.

In my understanding of object behaviour the statement above is correct regarding the first question and is incorrect in case of the second. However, I often see classes with methods like Orange::eat(), and this makes me uncertain about my design skills. So I would like to ask is it a design mistake to give oranges a behaviour eat? (oranges and eat are used just for example)

+3  A: 

I think there's nothing wrong with your way of thinking about objects and their responsibilities. Orange::eat() would make sense if oranges had mouths. Otherwise, it's an Animal who is doing the eating.

The thing of the matter is, SVO (Subject-Verb-Object) sentences aren't always the best way to describe something, but OOP seems to be heavily biased towards that kind of statement so we frequently run into strange, unnatural and abstract sentence constructions in code.

Tomislav Nakic-Alfirevic
Good point about orange eating orange :)
Alex Farber
I'm not sure I agree with this statement. After all, if Eat() is a method on Animal, who is telling the Animal to Eat? It seems like Animal should have a method Feed, which might cause the Animal to call Eat on the food it was given.
kyoryu
I'm not sure I follow. My point was that animal.eat(orange) makes more sense than orange.eat(): what do you mean by "who is telling the Animal to eat"?
Tomislav Nakic-Alfirevic
+1  A: 
Alex Farber
Hmm... In other words the second question implies accessing object properties. Are there other cases?
Corwin
Yes, it could mean accessing an object's methods:`void Eat(Orange /* ... */ }`
GodsBoss
+1  A: 

An orange can do things, for example, give rize to new orange trees. You are right, oranges can't eat anything, so it would make sense to have whatever is eating the orange have the eat method.

With this obvious example the answer is easy but it gets more complex in real life scenarios, you could take a look at Agile Principles, Patterns, and Practices in C# by Robert Martin. To go though a few scenarios and understand who gets to do what etc.

Mark Dickinson
The original book is Agile Software Development, Principles, Patterns, and Practices, and is not written with a view to C#, just in case title put you off.
Mark Dickinson
I'll look into the book, thanks.
Corwin