Object oriented programming - class design confusion

前端 未结 13 1759
你的背包
你的背包 2021-02-05 22:01

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.

13条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 22:31

    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.

提交回复
热议问题