mercredi 18 mars 2015

Inheritance vs hooks in abstract classes design approach

I am refactoring a piece of code that has huge list of if/else branches.

I am using strategy pattern as suggested here and have created a bunch of classes that implement the functionality inside the if branches.

Working on this I found that there are a few cases that the code does some "extra" work before actually doing the real work so now I want to make the sanest design decision:

1) Have something as follows:



public abstract class Processor {
private abstract void mainProcess(Object o);
protected void preProcess(Object o) {}
public void process(Object o) {
preProcess(o);
mainProcess(o);
}
}


And very few classes will actually override and preProcess with specific logic while for the rest is just an "empty" hook.


2) Have something like:



public interface Processor {
public void process(Object o);
}

public class XProcessor implements Processor {
@Override
public void process(Object o) {
//code here
}
}

public class SpecialCaseProcessor extends XProcessor {
private void preProcess(Object o) {
//code here
}

@Override
public void process(Object o) {
preProcess(o);
super.process(o);
}
}


To be honest I kind of like (1) but I don't like that only e.g. 5 out of 30 classes will actually implement the preprocess.


In (2) I avoid the empty hooks but I would need a way in my "constructor/factory" to distinguish between the specific extended subclasses


What is the sanest/most readable approach?


Aucun commentaire:

Enregistrer un commentaire