April 18, 2010

Which pattern is this?

I've been working in a component with some singularities, one of them is his incremental behavior. To make it clear: When a feature is almost complete (or completed), some other features arise.

This is really annoying if you have implemented everything for an specific use (never do this, I've learned in the bad way) if needs to be changed to work with the new stuff.

One of the things that I needed to do is to create/fill/validate different objects; I started thinking: "This is easy, let's do a mapper for each one of them". So far so good, then another type of object to work with.... shit, create more mappers, modify logic...

I started thinking "I'm doing this over and over, why am I so stupid?, use interfaces, builders, factories, simplify the problem... moron". I realized that the validation/filling... logic was the same, so the things that are different  needed to be isolated: the mappers (I don't know the real name).

With a little of work, I did this:
public interface Initializer<Source,Target>{
     // initializes the Target object using the Source as data provider 
     Target initializeThis(Source source, Target reference);
Then my object creator is:
public class ObjectCreator<Car> implements Creator{
    public Car prepareObject(){
        Info info= readInfo();
        Initializer init = InitializerFactory.newInitializer(Car.class,Info.class);
        return init.initializeThis(new Car(),info);        
The logic doesn't changes, just use the proper Creator, and that's it. But I don't really know if this is a pattern, or an anti-pattern, or whatever.