83. Combining LVTI and programming to the interface technique

Java best practices encourage us to bind the code to the abstraction. In other words, we need to rely on the programming to the interface technique.

This technique fits very well for collection declarations. For example, it is advisable to declare ArrayList as follows:

List<String> players = new ArrayList<>();

We should also avoid something like this:

ArrayList<String> players = new ArrayList<>();

By following the first example, the code instantiates the ArrayList class (or HashSet, HashMap, and so on), but declares a variable of the List type (or Set, Map, and so on). Since List, Set, Map, and many more are interfaces (or contracts), it is very easy to replace the instantiation with other implementation of List (Set, and  Map) without subsequent modifications being made to the code.

Unfortunately, LVTI cannot take advantage of the programming to the interface technique. In other words, when we use var, the inferred type is the concrete implementation, not the contract. For example, replacing List<String> with var will result in the inferred type, ArrayList<String>:

// inferred as ArrayList<String>
var playerList = new ArrayList<String>();

Nevertheless, there are some explanations that sustain this behavior:

  • LVTI acts at the local level (local variables) where the programming to the interface technique is used less than method parameters/return types or field types.
  • Since local variables have a small scope, the modifications that are induced by switching to another implementation should be small as well. Switching implementation should have a small impact on detecting and fixing the code.
  • LVTI sees the code from the right-hand side as an initializer that's useful for inferring the actual type. If this initializer is going to be modified in the future, then the inferred type may differ, and this will cause problems in the code that uses this variable.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.174