Why not inherit from List?

前端 未结 27 1697
悲哀的现实
悲哀的现实 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 05:58

    My dirty secret: I don't care what people say, and I do it. .NET Framework is spread with "XxxxCollection" (UIElementCollection for top of my head example).

    So what stops me saying:

    team.Players.ByName("Nicolas")
    

    When I find it better than

    team.ByName("Nicolas")
    

    Moreover, my PlayerCollection might be used by other class, like "Club" without any code duplication.

    club.Players.ByName("Nicolas")
    

    Best practices of yesterday, might not be the one of tomorrow. There is no reason behind most best practices, most are only wide agreement among the community. Instead of asking the community if it will blame you when you do that ask yourself, what is more readable and maintainable?

    team.Players.ByName("Nicolas") 
    

    or

    team.ByName("Nicolas")
    

    Really. Do you have any doubt? Now maybe you need to play with other technical constraints that prevent you to use List in your real use case. But don't add a constraint that should not exist. If Microsoft did not document the why, then it is surely a "best practice" coming from nowhere.

提交回复
热议问题