Why not inherit from List?

前端 未结 27 2522
悲哀的现实
悲哀的现实 2020-11-21 05:39

When planning out my programs, I often start with a chain of thought like so:

A football team is just a list of football players. Therefore, I should

27条回答
  •  天命终不由人
    2020-11-21 06:01

    As everyone has pointed out, a team of players is not a list of players. This mistake is made by many people everywhere, perhaps at various levels of expertise. Often the problem is subtle and occasionally very gross, as in this case. Such designs are bad because these violate the Liskov Substitution Principle. The internet has many good articles explaining this concept e.g., http://en.wikipedia.org/wiki/Liskov_substitution_principle

    In summary, there are two rules to be preserved in a Parent/Child relationship among classes:

    • a Child should require no characteristic less than what completely defines the Parent.
    • a Parent should require no characteristic in addition to what completely defines the Child.

    In other words, a Parent is a necessary definition of a child, and a child is a sufficient definition of a Parent.

    Here is a way to think through ones solution and apply the above principle that should help one avoid such a mistake. One should test ones hypothesis by verifying if all the operations of a parent class are valid for the derived class both structurally and semantically.

    • Is a football team a list of football players? ( Do all properties of a list apply to a team in the same meaning)
      • Is a team a collection of homogenous entities? Yes, team is a collection of Players
      • Is the order of inclusion of players descriptive of the state of the team and does the team ensure that the sequence is preserved unless explicitly changed? No, and No
      • Are players expected to be included/dropped based on their sequencial position in the team? No

    As you see, only the first characteristic of a list is applicable to a team. Hence a team is not a list. A list would be a implementation detail of how you manage your team, so it should only be used to store the player objects and be manipulated with methods of Team class.

    At this point I'd like to remark that a Team class should, in my opinion, not even be implemented using a List; it should be implemented using a Set data structure (HashSet, for example) in most cases.

提交回复
热议问题