Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an object with a list of different types?

Tags:

java

generics

Hey, I'm initializing a ListRepository with two different types of initialization lists. The best way would be something like this.

public ListRepository(String id, List<PrimaryKey> initilizationList)
{
   // Load objects from data source via primary key.
}

public ListRepository(String id, List<DomainObject> initilizationList)
{
   // Store objects directly
}

Unfortunately this is not possible due to runtime type erasure. I don't like a constructor approach with List<?> as an argument, this leads to an ugly instanceof check of the first entry, to determine the list type and handle it.

How do you solve such a problem with an intuitive and clean API?

like image 401
Christopher Klewes Avatar asked Mar 21 '11 11:03

Christopher Klewes


2 Answers

The constructor is doing far more than initialising the object. It is best to keep constructors simple.

I would use a static method to perform each query.

public static ListRepository<PrimaryKey> loadFromPrimaryKey(String id, List<PrimaryKey> initilizationList) {
   // Load objects from data source via primary key.
}

public static ListRepository<PrimaryKey> loadFromDomainObject(String id, List<DomainObject> initilizationList) {
   // Store objects directly
}

You would have one constructor which just takes the resulting data. This would make it much clearer as to what the methods will build.

like image 101
Peter Lawrey Avatar answered Sep 27 '22 19:09

Peter Lawrey


Use factory method

class ListRepository {     
    public static ListRepository createPrimaryKeysRepository(String id, List<PrimaryKey> initilizationList){}
    public static ListRepository createDomainObjectsRepository(String id, List<DomainObject> initilizationList){}
}
like image 29
Stan Kurilin Avatar answered Sep 27 '22 19:09

Stan Kurilin