Search code examples
oopclass-design

Object oriented programming - class design confusion


I am trying to wrap my head around object oriented programming.

My understanding is that we have objects so we can design our programs to mirror real-life objects.

Let's take a class hierarchy:

class Fruit {
    void Eat() {

    }
}

class Apple extends Fruit {

}

Obviously, you can use Fruit polymorphically if Eat() is virtual. But does this make sense? Fruit cannot eat itself!

Should a fruit object rather be passed to a human object which has a Eat() function?

I am trying to figure out the correct way to think about this. How closely, in general, should programming objects mirror real-life objects?


Solution

  • You've got a design problem -- as you correctly point out, Eat() doesn't make obvious sense as a member of Fruit. On the other hand, an "edible" attribute would make more sense. As would an "onEaten" event, etc. What your fruit/apple classes expose (and what other objects make sense in your model) depends on a lot of other factors, including what you're trying to accomplish with those constructs in your application.

    In general you want your classes to represent logical domain level entities. Sometimes those correspond to a physical entity in the real world, but in many cases they don't.

    In my opinion OO problem decomposition is something programmers are generally pretty bad at. I don't know how many times I've seen the equivalent of a car derived from a steering wheel and shaken my head while the original developer couldn't wrap their head around why their design didn't make a lot of sense.