jeudi 22 octobre 2015

What design pattern should be used when similarly if-else grows?

We have some code like:

public class ErrorCodeUtil {
    public static void handleErrorCode(String errorCode) {
        if (errorCode.equals("1")) {
            handleErrorCode1();
        } else if (errorCode.equals("2")) {
            handleErrorCode2();
        } else if (errorCode.equals("3")) {
            handleErrorCode3();
        } else {
            handleErrorCodeByDefault(errorCode);
        }
    }

    public static void logByErrorCode(String errorCode) {
        if (errorCode.equals("1")) {
            logErrorCode1();
        } else if (errorCode.equals("2")) {
            logErrorCode2();
        } else if (errorCode.equals("3")) {
            logErrorCode3();
        } else {
            logErrorCodeByDefault(errorCode);
        }
    }
    //... a lot of method about error code
}

As you see, we have a Util to handle all things about ErrorCode, and when we want to add a special logic to an error code, we have to change many method of that utils class.

As expected, the value of error code varies in large range(possibly "112345" or "error_code_001"). So what design pattern is proper for that case?

Aucun commentaire:

Enregistrer un commentaire