Why should the interface for a Java class be preferred?

后端 未结 10 1337
陌清茗
陌清茗 2020-11-22 05:43

PMD would report a violation for:

ArrayList list = new ArrayList();


The violation was \"Avoid using implementat

相关标签:
10条回答
  • 2020-11-22 06:28

    In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.

    There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower.

    For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds.

    If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.

    0 讨论(0)
  • 2020-11-22 06:29

    This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.

    0 讨论(0)
  • 2020-11-22 06:32

    Even for local variables, using the interface over the concrete class helps. You may end up calling a method that is outside the interface and then it is difficult to change the implementation of the List if necessary. Also, it is best to use the least specific class or interface in a declaration. If element order does not matter, use a Collection instead of a List. That gives your code the maximum flexibility.

    0 讨论(0)
  • 2020-11-22 06:37

    The interface often has better representation in the debugger view than the concrete class.

    0 讨论(0)
提交回复
热议问题