OOP: When is it an object?

前端 未结 20 1377
悲哀的现实
悲哀的现实 2021-01-30 23:01

I\'m trying to understand object orientation. I understand it a little bit of course, but sometimes I\'m not 100% clear. How do you decide what should be turned into an object (

20条回答
  •  终归单人心
    2021-01-30 23:42

    I'd advise you to think about how you are going to use it. Think what operations you will have to do with your "thing" and then consider what would be the easiest way of doing it. Sometimes it will be easier to make it a property of another object, sometimes it will be easier to make it a new object of its own.

    There is no universal recipe, there can be many factors that make one solution the better one. Just consider each case separately.

    Added: To take your example about a door/doorknob/keyhole - what will you do with the keyhole? Here are some factors that would make it logical to make the keyhole as a separate object:

    • You want store many properties of the keyhole like size, shape, direction, count of pins, whether the key can be turned once or twice, etc;
    • There can be more than one keyhole on a doorknob;
    • You want to give the keyhole some read-only properties (like whether it's locked or not) and then only allow modifying them through specific methods (like an "unlock" method which takes a "key" object as a parameters);
    • Keyholes are stored in a separate DB table with one keyhole per DB row (then it might make sense to make the keyhole object mimic the DB structure);
    • There are methods in your system that would be implemented in an elegant way if they could take a keyhole as a parameter;

    The scenarios for making it a property are the opposite:

    • Each doorknob can have only one keyhole and it has only one or very few properties;
    • Keyholes are stored together with the doorknobs in the DB;
    • You usually don't care about the keyhole alone, you just want it as a descriptive property of the doorknob (like whether or not there is one);

提交回复
热议问题