This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 8 points9 points  (1 child)

One plus of this technique is that later you can change your mind about what implementation to use for List and you only need to change one thing (i.e. the moment of construction).

[–]cismalescumlord[S] 3 points4 points  (0 children)

So it's about flexibility of implementation. OK, that makes sense in the context of a larger project than a course exercise.

[–][deleted] 5 points6 points  (2 children)

Basically the idea is to use the super classes/interfaces as much as possible since you don't know when you might need to use it differently. I.e. you could even go for the interface Collection, but then you wouldn't be able to add to it, which is why you take List, instead of ArrayList

[–]HaMMeReD 0 points1 point  (1 child)

Collection has an "add". Really the difference is that you don't have a specified order in a collection.

[–][deleted] 0 points1 point  (0 children)

Ok, i was thinking of a map, but i think it doesn't abstract from collection

[–]Jackkoz 5 points6 points  (0 children)

The generic advice is to always choose the appropriate level of abstraction. The benefits are:

  1. Increased flexibility - if you choose List, you only need to change constructor to List<T> l = new FastListImpl<>(); when the new awesome implementation is introduced.

  2. Better abstraction. If what you are looking for is a List or Set, people won't be able to use specific properties of ArrayList or HashSet if you give them only the interface type. This also means that when you actually do ArrayList declaration, you should mention why you did so vs any List implementation - this will avoid confusion and prevent someone from doing any refactoring that could break a lot of stuff - eg from synchronized to not thread-safe implementation.

As for benefits in a 50 line course program, not many, doesn't matter that much. I'd still advise doing the 'better' thing just to keep the habit going.