lundi 30 novembre 2015

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

Aucun commentaire:

Enregistrer un commentaire