A farm contains farmers and cows who milk cows every day. Now, farmers and cows are regarded as the same object. You think that the property of milking should be assigned to farmers.
Is it reasonable for the operator to be assigned to the cows?
First of all, this is a question about object-oriented programming. It mainly examines your understanding of object-oriented. Therefore, we should use an object-oriented way of thinking to think about this problem.
There are two types of opinions:
Opinion 1: distributed to farmers;
Opinion 2: allocate to cows;
First, let's look at the first point of view: This point of view holds that the process of "milking" is done by farmers, so it should be the attributes of farmers.
If you think this way, you will be caught in the trap set by the examiner. In fact, what this question really explores is when you designProgramDoes it take into account its maintainability and scalability;
In fact, this problem can be abstracted into another model: "milking" is a cow, but it can be called by the farmer. In this case, if the business is changed in the future, for example, if an automatic milking device is introduced on the farm, the device can call the "milking" attribute of the cow. This attribute can also be called if the cows are raised by others in the future.
There are still many examples of this in programming modeling, such as employee salaries. The company has bosses and employees. According to our daily experience, the boss has the right to give employees a salary increase, therefore, the "salary increase" attribute should be assigned to the boss class, but if so, the same mistake is made, because the salary is the data of the employee class, therefore, it is best to process it by its internal attributes and Methods. Other classes can call their own methods if they want to modify its data. In this way, high cohesion and low coupling can be achieved. This is also a prerequisite for program maintenance and scalability.