I keep coming across code where people instantiate a new ArrayList and assign it to the List interface, like this:
List<String> names = new ArrayList<String>();
What is the reasoning behind this approach?
Programming to an interface, not an implementation
It's a design pattern from Gang of Four (GoF). Why is that?
You guide by abstract contract instead of concrete implementation.
public class MyClass {
private List myList ;
public setMyList(List list){
myList=list;
}
}
what about instead of ArrayList
implementation you want LinkedList
implementation?
in that way you only has to inject that property with the setter.
Abstraction is the key, you don't know nothing about implementation only guide by specification.
Read this What does it mean programming to an interface?
To decouple your code from a specific implementation of the interface.
This also helps you to move to another implementation of the List
interface in the future.
For example -
You have List<String> names = new ArrayList<String>();
later on you decide that you should have used some other implementation of the List
interface, say LinkedList
so you would just change it to List<String> names = new LinkedList<String>();
and nothing breaks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With