Search code examples
javadata-structuressonarqubereadabilitycyclomatic-complexity

Reducing complexity of large switch statements


In the codebase I'm currently working on, it's common to have to take a string passed in from further up the chain and use it as a key to find a different String. The current standard idiom is to use switch statements, however for larger switch statements (think ~20-30 cases) sonarqube says it's a code smell and should be reduced for cyclomatic complexity. My current solution is to use a static HashMap, like so

private static final HashMap<String, String> sortMap;
static {
    sortMap = new HashMap<>();
    sortMap.put("foo1", "bar1");
    sortMap.put("foo2", "bar2");
    sortMap.put("foo3", "bar3");
    etc...
}

protected String mapSortKey(String key) {

    return sortMap.get(key);
}

However this doesn't seem to actually be any cleaner, and if anything seems more confusing for maintainers. Is there a better way to solve this? Or should sonarqube be ignored in this situation? I am aware of using polymorphism, i.e. Ways to eliminate switch in code, however that seems like it is overkill for this problem, as the switch statements are being used as makeshift data structures rather than as rudimentary polymorphism. Other similar questions I've found about reducing switch case cyclomatic complexity aren't really applicable in this instance.


Solution

  • If, by your example, this is just the case of choosing a mapped value from a key, a table or properties file would be a more appropriate way to handle this.

    If you're talking about logic within the different switch statements, you might find that a rules engine would suit better.

    You hit upon the major requirement: maintainability. If we are coding in too much logic or too much data, we have made brittle code. Choose a design pattern suited to the type of switched information and export the functionality into a maintainable place for whomever must make changes later... because with a long list like this, chances are high that changes will be occurring with some frequency.