Use interface or type for variable definition in java?

后端 未结 8 1970
挽巷
挽巷 2020-11-29 05:59
ArrayList aList = new ArrayList();

List aList = new ArrayList();

What\'s the difference between these two and which is better to use and why?

8条回答
  •  再見小時候
    2020-11-29 06:58

    All these answers are the same recite from some dogma they read somewhere.

    A variable declaration and initialization statement, Type x = new Constructor();, is definitely part of implementation detail. It's not part of a public API (unless it's public final, but List is mutable so that's inappropriate)

    As an implementation detail, who you are trying to fool with your abstractions? It's better to keep the type as specific as possible. Is it an array list or a linked list? Should it be thread safe or not? The choice is important for your implementation, you carefully chose the specific list impl. Then you declare it as a mere List as if it doesn't matter and you don't care?

    The only legitimate reason to declare it as List is I'm too lazy to type. That also covers the argument that if I need to move to another List impl I have one less place to modify.

    This reason is legitimate only when the variable scope is small, and you can see all of its usages from one glance. Otherwise, keep the most specific type, so that its performance and semantic characteristics are manifest across all the code that use the variable.

提交回复
热议问题