Liang
Liang

Reputation: 383

making it easy to change implementation of an interface later on

So in java the way to initialise an interface, such as a collection or list, is to create an instance of a class that implements it, eg:

Collection<Object> moo = new ArrayList();

If I wanted to specify an implementation at a later time in my code, I was thinking of doing this by creating another class like:

class ListList extends ArrayList{

}

and then initialise the variable with

Collection<Object> moo = new ListList();

And then all that's required if I want to change the implementation later on is to change what ListList extends.

So, here's the question.. is there a better way of doing this (I still feel as though I'm inexperienced with this type of thing).

Upvotes: 0

Views: 661

Answers (3)

Robin
Robin

Reputation: 36611

The basic idea is a good one. Make your variable/field/... an instance of the interface and not of the concrete class you are using. This will force all your code to work against the interface (on the condition that you not start casting somewhere down your code path), and allows to replace the implementation later on with a different class if you feel the need for it.

One can start discussion about how you create that concrete class, like for example using a factory method as @skaffman suggested in his response. However, this might depend on the situation. If it is just for a one-time use like initializing a field you can just create the instance without bothering about factory methods.

Upvotes: 0

jarCrack
jarCrack

Reputation: 116

You could also do it that way

Collection<Object> coll=new ArrayList(){
        //bla
    };

Upvotes: 0

skaffman
skaffman

Reputation: 403481

is there a better way of doing this

Yes: use a factory method:

public static Collection<Object> createCollection() {
    return new ArrayList<Object>(); // change this later, if need be
}

Then, invoke the factory rather than instantiating:

Collection<Object> moo = createCollection();

Your suggestion of using a "dummy" subclass might appear attractive, but such abuses of inheritance invariably lead to pain and suffering later on. You really don't want to do that.

Upvotes: 6

Related Questions