Tapas Bose
Tapas Bose

Reputation: 29806

Re-factoring the usage of same switch-case multiple time

In a class I have following switch-case:

switch(articleStep.getDeveloper()) {
    case CENTRAL:
        switch(articleStep.getArticleType()) {
            case POSM:
                //some code
                break;

            case PROMOTION_PACK:
                //some code
                break;
        }
        break;

    case LOCAL:
        //some code
        break;
}

in multiple methods. Only the internal operations differ among them (//some code).

Is there any alternate way exists by which I can place the switch-case in only one method, and I will call that method by passing the operations as parameters, and it will do the same job?


Usage-1

switch(articleStep.getDeveloper()) {
    case CENTRAL:
        switch(articleStep.getArticleType()) {
            case POSM:
                centralPOSMArticle = new AddManageArticleInDTO<ManageCentralPOSMArticleInDTO>();                
                centralPOSMArticle.setManageArticle(new ManageCentralPOSMArticleInDTO());
                setMandetoryParameterToAddManageArticleInDTO(centralPOSMArticle);
                break;

            case PROMOTION_PACK:
                centralPromotionPackArticle = new AddManageArticleInDTO<ManageCentralPromotionPackArticleInDTO>();                
                centralPromotionPackArticle.setManageArticle(new ManageCentralPromotionPackArticleInDTO());
                setMandetoryParameterToAddManageArticleInDTO(centralPromotionPackArticle);
                break;
        }
        break;

    case LOCAL:

        break;
}

Usage-2

switch(articleStep.getDeveloper()) {
    case CENTRAL:
        switch(articleStep.getArticleType()) {
            case POSM:
                genericDTO = centralPOSMArticle.getManageArticle();
                break;

            case PROMOTION_PACK:
                genericDTO = centralPromotionPackArticle.getManageArticle();
                break;
        }

        break;

    case LOCAL:

        break;
}

There are total seven place where I have used this type of switch-case.

Upvotes: 0

Views: 98

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

You'll find your idea quite unworkable, but a good approach would be to define methods inside your enum and rely on dynamic dispatch to do the work of your switch statements.

Upvotes: 2

Related Questions