Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Oriented Design problem

Tags:

oop

If I`m programming a game in which there is a worker that cuts wood (from trees), where would I put the "cutWood" method, in the worker class, or the tree class?

EDIT: The first example I read on OOD was about a circle (a class called circle) which has in it a method called "calculate area". Now, sure enough a circle doesn't calculate its own area. The only way to think of it is that calculating area is an operation that is relevant to the circle (an operation done on the circle)

So, cutWood method is relevant to both, the worker, and the tree.

like image 592
w4j3d Avatar asked Sep 30 '10 22:09

w4j3d


3 Answers

I don't see any cohesion to have a wood cutting method in the worker. The cutting is done on the tree, and should therefore be part of the tree class. Presumably, cutting the wood will also involve changing some internal state of the wood class too.

A worker should call the cut method on whatever tree he wants, rather than the tree telling the worker that he should cut it. If you want to abstract this like Hans has hinted at, you could make an ICuttable interface for the Cut method, and have your tree implement it.

Consider something you're familiar with, a String. When you want to cut a string (split), you don't define a splitString method in every object which is going to do this. Whatever object decides to split the string, the same thing takes place - and will usually need to know the internals of the target object (the string) in order to do it. Many other objects simply call the split method of the string. The string object has high cohesion - because it's methods contribute to a common task - manipulating strings.

I don't see how cutting wood contributes much to the worker object itself.

like image 167
Mark H Avatar answered Nov 04 '22 16:11

Mark H


Ask yourself: Do workers cut wood, or do trees cut wood?

like image 27
codelark Avatar answered Nov 04 '22 15:11

codelark


You basically answered it in your question: "a worker that cuts wood". You should put it to the worker class.

like image 31
Karel Petranek Avatar answered Nov 04 '22 15:11

Karel Petranek