OOP: When is it an object?

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

    As always, the answer is unfortunatly: it depends...

    At the beginning, you have some sort of environment and you want to create a model for it. But you would not model every thing, you'll concentrate on the important things. That's why I started with: it depends. It depends on what details you need to accomplish the task.

    Take the car and it's wheels - if you model a city and want some traffic, you may create a 'Car' class with the attribute 'numberOfWheels'. But if you design cars, then you most likely want to create a class 'Wheel' aswell and add four of those to the 'Car' class.

    Rule of a thumb:

    1. if that, what you're thinking about, has more then one attribute, define a class
    2. if that, what you're thinking about, has some behavior, define a class
    3. if that, what you're thinking about, may grow or be extended, define a class
    4. if that, what you're thinking about, has to be sortable, comparable, define a class
    5. if you're unsure, define a class ;)

    Edit

    Because you emphasized the 'multiple usage' aspect: I don't think that this is an aspect for a decision whether to use a class or not. Think of a simple counter, an integer value in a for loop. You'll use this concept hundreds of times but I bet you'll never think of wrapping this poor little int into a 'Counter' class - just because you use the 'concept of a counter' multiple times.

提交回复
热议问题