user5417542
user5417542

Reputation: 3376

Refactoring or using Design Pattern on Switch-Case-Smell

Since I am currently dealing with Design Patterns and Refactoring some Legacy Code to write some JUnit-Tests, I am looking through my project, where I could apply it.

I found one method in one class, where I have a very long switch-case-statement. Of course this is a horrible scenario for unit-testing, since I need to create a test for every statement.

Now I thought about applying the Strategypattern. But the problem is, I have 30 different cases. That would mean I would have to create 30 classes. Is this advised, or should I consider some other way of refactoring? Morover the switch case is inside two for-loop, since it's an Excel-table.

Here is an excerpt of my method:

switch (column) {
    case CASE1:
        excelUtil.setCell(row, col++, item.getSomething(), styles[0]);
        break;
    case CASE2:
        excelUtil.setCell(row, col++, order.getSomething(), styles[0]);
        break;
    case CASE3:
        excelUtil.setCell(row, col++, order.getSomethingElse(), styles[0]);
        break;
    case CASE4:
        if (!StringUtils.isEmpty(order.getSomething())) {
            try {
                //do something before setting cell
                excelUtil.setCell(row, col++, soldToName, styles[0]);
            }
            catch (final Exception e) {
                excelUtil.setCell(row, col++, "", styles[0]);
            }
        }
        else {
            excelUtil.setCell(row, col++, "", styles[0]);
        }
        break; //.. and so on

Upvotes: 0

Views: 256

Answers (1)

theDmi
theDmi

Reputation: 18034

Yes, the strategy pattern is the right choice in this situation. Ensure that the state tracking logic (e.g. col++) is not leaked into the strategies.

With strategies in place, the strategy selection can then be moved to a dictionary: Create a dictionary that maps from column to a strategy, and use the dictionary in place of the switch-case. This works because the strategies all implement the same interface.

Upvotes: 1

Related Questions