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?
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.
Use factory method
class ListRepository {
public static ListRepository createPrimaryKeysRepository(String id, List<PrimaryKey> initilizationList){}
public static ListRepository createDomainObjectsRepository(String id, List<DomainObject> initilizationList){}
}
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