vendredi 19 février 2016

Replace hardcoded class implementations

While working on a new project a came across to this familiar case.

private static Hashtable<String, Class<? extends MyExample>> MyExampleClassCollection = new Hashtable<String, Class<? extends MyExample>>();

static {
    MyExampleClassCollection.put("example1", MyExampleImplementation1.class);
    MyExampleClassCollection.put("example2", MyExampleImplementation2.class);
    MyExampleClassCollection.put("example3", MyExampleImplementation3.class);
}

public static MyExample getMyExample(String myExampleType){

    Class<? extends MyExample> templateClass = MyExampleClassCollection.get(myExampleType);

    try {
        Constructor ctor = templateClass.getConstructor(Connection.class);
        return (MyExample)ctor.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

This is the case where you are trying to create a more generic code and you end up hardcode the different implemantations of your generic class. Having the down side that you have to create a new entry on the Hashtable for every new implementation.

A solution I saw on a previous project I worked on, was store the several names of the concrete classes in the DB. Having a field with the name of the concrete class that is going to be used. And create it again with reflection, for example MyExampleImplementation1. Gain that you don't use a HashTable. This solution is identical, the only difference is I retrieve the myExampleType from the DB.

Is there a more elegant way? I would prefer to use a configuration file. I thought I could use dependency injection (I'm not very experienced with this yet), but is this is a good case for that?

Is there a way to integrate this functionality with my application server ? I'm using Weblogic.





Aucun commentaire:

Enregistrer un commentaire