When should you encapsulate generic types?

前端 未结 3 1776
南旧
南旧 2021-01-18 11:38

I\'ve seen a number of people suggest that you should encapsulate generic types with a class closer to your domain, for example Steve and Nat suggest in Growing Object-Orien

3条回答
  •  既然无缘
    2021-01-18 12:15

    I disagree with that philosophy. List is a type just like PersonList is. The domain concept of a list of persons is encapsulated in it just as well. If you ask me, it's better to use generics as much as possible unless using them limits you (see below) or makes the code hard to understand. For example, a function that works on PersonList will be harder to generalize than one that works on List, if you even notice that it's doing something general.

    That said, specifically in Java there is a limitation on generics that makes them a lot less attractive. Due to type erasure, you cannot fully utilize generics when static methods / members of a type are involved, and you may need to extract a specific type that is not generic to be able to use it for certain things. Bottom line is, in Java you do need to extract a specific type in many cases, if that allows you to remain type-safe.

提交回复
热议问题