jeudi 25 novembre 2021

How to refactor this code into multiple classes and not have to repeat the try-catch block?

I have a class with the following structure(reduced to bare minimum)

class Main{

    processTask(){
        try{
            data = preStep1();
            preStep(data);
            processFurther(data);
        }
        catch(Exception1 e){
            handleEx1();
        }
        catch(Exception2 e){
            handleEx2();
        }
    }

    processFurther(data){
        switch(data){
            case cOne:
                doOneThing();
                break;
            case cTwo:
                doTwoThing();
                break;
            case cThree: 
                doThreeThing();
                break;
            case cFour:
                doFourThing();
                break;
            default:
                doDefault();    
        }
    }

}

The four functions doOneThing, doTwoThing, etc. are in another utility class let's say MainHelper.

Now, a requirement has come that the code for four case cOne, cTwo, cThree, cFour needs to be in 4 separate files, like MainOne, MainTwo, MainThree and MainFour. This is a must and cannot be avoided.

The problem that I face is that if I just split it as it is, then I have something like this

class MainOne{

    processTask(){
        try{
            data = preStep();
            doOneThing();
        }
        catch(Exception1 e){
            handleEx1();
        }
        catch(Exception2 e){
            hanldeEx2();
        }
    }

}

Now this preStep() and handeling exceptions is going to be repeated exactly like this in all the four classes. How can we through a design pattern or some custom way make it so that we don't have to repeat this code.

If the code was without the try-catch then I could have done the following. But I am not sure how I can do it now since there is a try-catch involved.

class MainOne{

    processTask(){
        Util.preProcess();
        doOneThing();
    }
}

class Util{

    preProcess(){
        data = preStep1();
        preStep2();
        return data;
    }

}

Aucun commentaire:

Enregistrer un commentaire