mardi 25 octobre 2016

Appropriate Java design pattern to avoid method duplication

I have this scenario. I started working with a system that 'process' documents. The problem is, it seems to be the typical scenario where it started small, and went getting bigger and bigger constructing it one chunk at a time and now it needs to be refactored.

Each document type has an identifier (docID), and all of them share the same underlying result structure.

There is a huge master class that does all the job BUT inside this class there are several methods (almost one for each site) with its own logic. They all do almost the same with slight changes (i.e. formatting a string before setting it to a field in the result structure or doing some calculation and then setting the field in the result structure).

For example:

private Result processDocGeneric(Result result){
            result.setField1("value1");
            result.setField2("value2");
            result.setField3("value3");
            return result;
        }

private Result processDoc1(Result result){
            result.setField1("VALUE1");
            return result;
        }

private Result processDoc2(Result result){
            result.setField2("V-A-L-U-E-2");
            return result;
        }

private void processDocs(){
            Result result = new Result();
            result = processDocGeneric(result);
            if(docID == 1){
                result = processDoc1(result);
            }
            else if(docID == 2){
                result = processDoc2(result);
            }
            ...
        }

Ok, so I'm planning to refactor this and I'm considering some design patterns I know but I don't want the feel that I'm killing a roach with a bazooka.

Command pattern is maybe the first that comes to my mind, also Strategy pattern. My major concern with those is that I will have to create a class for every document type that has its own implementation of the processDoc method (There are around 15 at the moment). I mean, if that's the way to go, that would be it but if there's a simpler way of doing it that I don't know, it would be better (since the change is in a single method).

The other thing that I could do is moving all those method to a 'methods' class, and also move the if-else block to a single method with a docID parameter (process(int docID) and then call it from the main class. But that's just splitting the huge class. It would be "cleaner" but not optimal.

What would be the best approach to clean and split this huge class and make it scalable (since there would be new document types to be added in the future)?.

Aucun commentaire:

Enregistrer un commentaire