OOP: When is it an object?

前端 未结 20 1344
悲哀的现实
悲哀的现实 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:52

    First: forget about physical objects. I know that all of the textbooks "learning examples" use them, but you're only going to confuse yourself when you try to model a real system. There is no direct relationship between physical objects and Objects.

    An Object is a data structure combined with a set of methods that can operate on that data structure. The Properties of the Object hold the object state, and the methods operate on the state.

    What is the system state you are trying to model? Does that reside in the door, the knob, or some combination of the two?

    There are some methodologies that attempt to get the object model clearly specified before coding begins. Other methodologies (e.g, TDD) allow the object model to emerge through the coding process. In your case, I'd recommend coding some small-to-medium sized applications using TDD, so that you can see the advantages and disadvantages to various patterns. There's rarely one "right" way to model a given situation, but some models are much easier to use and understand than others; recognizing the patterns that apply to the situation in front of you comes with experience.

    So, bottom line: make a lot of models. Think of application domains, model them, and code. In doing so, things will become much clearer. Make a sandbox, and jump in.

    0 讨论(0)
  • 2021-01-30 23:54

    As the old cliche says "objects should be nouns". Any time you find yourself thinking of a thing, it should probably be an object. Any time you find yourself thinking of an action, it should probably be a function or method.

    Of course, there are exceptions to the above rules, and reality can be a bit more complex. However, this is probably the best starting place to start wrapping your head around the concept.

    0 讨论(0)
提交回复
热议问题