Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concrete types in declaration

I have come across recommendations that the variable declaration must be an interface rather than a concrete type similar to below –


Map<String,String> myMap = HashMap<>();
List<String> myList = new ArrayList<>()

However is it acceptable in terms of coding practices to have a concrete type in variable declaration especially for local variables?

HashMap<String,String> myMap = HashMap<>();
ArrayList<String> myList = new ArrayList<>()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First the rule makes sense as it allows more powerful expressions, method parameters and method results, and is also woven into the standard java libraries.

You may change the implementation later, as method parameter the method can deal with more than one concrete implementation and hence is more versatile, less needlessly restricted. As return type it allows different dynamic implementations, List as empty list or singleton list.

Answer: No, it is not a good idea to mix styles, because of keeping your mind on a single track. There is however:

var myMap = HashMap<String, String>();

Myself, as oldie, I do not like var but the overall style then is okay.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading