I did a test task for the Junior Android developer's job, there was a line in the code:

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

I was told that it is better to write like this:

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

Then in one of the articles on habrahabr.ru the phrase met:

Just think, a big deal that a person does not understand why you need to write List values ​​= new ArrayList (); instead of ArrayList values ​​= ... .; Well, and who would not like to see names in the style of ArrayList arrayList = new ArrayList (); and smile. It is a pity that with the use of this anti-beer, all these, causing a smile, things usually show up after about a month of work.

Explain why writing is wrong. Formally - no error?

2 answers 2

This is usually explained as follows: if the encoder declares a variable of type ArrayList<String> instead of List<String> - he does not understand that all the methods he needs are already in the interface. This demonstrates a lack of understanding of the basic principles of design, because he really doesn’t need exactly ArrayList<String> , he can use any other collection! ... with the same asymptotics of operations ... oops.

In fact, those who write like that are protected from automatic refactorings that can convert a variable of a particular type into a parameter of the method, which will show their lack of understanding of the basic design principles used to the IDE, which emphasize such places with yellow and offer to correct the type of variable. It is just a habit.

For most algorithms, invented on the fly, ArrayList<> is the only collection with adequate execution times for operations and there is no difference what type of variable to declare.

But the types of parameters of methods or return values ​​must really be followed more carefully, choosing the smallest suitable interface - this will simplify the docking of code written by different programmers.

  • Thank you, from this side did not look. I got used to nailing - if you need an ArrayList, then it will be ArrayList. The courses on these points are not emphasized. - Miller777

It is more religious / stylistic than formal.

The List<String> declaration is wider than the ArrayList<String> declaration, that is, when a person writes List<String> he demonstrates his OOP entity type, as if he understands that the underlying object can be ArrayList and Vector and Stack , etc. and declaring a List abstracts from a particular implementation.

In fact, whether it is right or not is reminiscent of the discussions of medieval scholastics about the essence of universals.

  • The rigidity of the ratings is also from the section of scholasticism, as it is known the winners in scholastic disputes burned their opponents alive - so everything is fine :) - Barmaley
  • Thanks I got it! - Miller777