Switch: throw an exception if default section shouldn’t be reached? #Route 85 – Quick Tip: Don’t Default that Switch!

Categories: Java; Tagged with: ; @ March 8th, 2015 21:32

There’s a quick tip from Google developers about switch, the suggestion is getting rid of throwing exception in switch default section if the default handler shouldn’t be reached.

Here’s an example in Java:

package com.liguoliang.java.core.lang.enum_;

/**
 * Created by Guoliang, Li(liguoiang.com) on 3/8/2015.
 */

public class SwitchDefaultDemo {

    public static void main(String[] args) {
        System.out.println(getBookCategoryDesc(BookCategory.JAVA));
;    }

    private static String getBookCategoryDesc(BookCategory bookCategory) {
        String desc = null;
        switch (bookCategory) {
            case JAVA:
                desc = "It's a Java book";
                break;
            case PYTHON:
                desc = "It's a PHP book";
                break;
            default:
                throw new RuntimeException("Unknown book category");
        }

        return desc;
    }

    public static enum BookCategory {
        JAVA, PYTHON, PHP;
    }
}

The tip’s point is if developer added a new enum and forgot to update the switch statement accordingly, there’ll be a issue, it may fail the test or crash the application.

so to improve the switch statement, the video suggest to remove the default section. if some client calls getBookCategoryDesc(PHP), the method will be executed normally, instead of throwing an exception.

it seems debatable for me, I prefer to keep the exception,  throwing an exception to exposure the risk instead of hiding it, because the exception tells the details, developers can fix the bug immediately. otherwise, developers will realize the issue and start to debug until user reporting it.

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.