设计-设计一段处理错误码的代码

设计一段处理错误码的代码

不得不说,考察的这道题对我的编程观念有很大的帮助。

这个题目其实是我在面试的时候遇到的题目,主要考察的是工程能力,但当时心里只想着用表驱动优化了,结果无法记录错误代码的范围,也没想出来。不过面试官给了点提示,说时间复杂度也可以不是O(N),那我们就用配置文件解决这个问题吧。

请补全这个函数String getInfo(int errCode),输入错误码返回错误信息,比如:
错误代码1,用户名错误;
错误代码2,密码错误;
错误代码10-100,数据库错误;
错误代码200-1000,文件找不到错误。
要求这个函数要使修改错误码和错误信息时尽可能少修改代码(代码可维护)

我们可以把错误码抽象成一个类,用两个边界表示错误码的上下边界,然后,与从配置文件或者网络中读取的错误码信息比较,获得错误码字段,时间复杂度为O(N),但是代码的可复用性就极大的提高了。

/**
 * 请补全这个函数String getInfo(int errCode),输入错误码返回错误信息,比如:
 * 错误代码1,用户名错误;
 * 错误代码2,密码错误;
 * 错误代码10-100,数据库错误;
 * 错误代码200-1000,文件找不到错误。
 * 要求这个函数要使修改错误码和错误信息时尽可能少修改代码(代码可维护)
 */
public class ErrCodeHelper {
    
    
    /**
     * 实现思路,把错误信息写在配置文件,或者从网络读取错误信息
     */
    public static List<ErrCode> errCodes;
    
    static class ErrCode{
    
    
        public int min;
        public int max;
        public String errInfo;

        public ErrCode(int min, int max, String errInfo) {
    
    
            this.min = min;
            this.max = max;
            this.errInfo = errInfo;
        }
    }
    
    public static String getInfo(int errCode){
    
    
        String errInfo=null;
        try {
    
    
            errInfo=getInfo(errCode,loadErrCodeList());
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return errInfo;
    }
    public static String getInfo(int errCode, List<ErrCode> errCodeList) throws Exception {
    
    
        if(errCodeList==null||errCodeList.isEmpty()){
    
    
            throw new Exception("ErrCode List Error");
        }
        for (ErrCode code:errCodeList){
    
    
            if(errCode>=code.min&&errCode<=code.max){
    
    
                return code.errInfo;
            }
        }
        throw new Exception("ErrCode Not Found Exception");
    }
    
    public static List<ErrCode> loadErrCodeList(){
    
    
        if(errCodes==null){
    
    
            //read from disk or network
            errCodes=new LinkedList<>();
        }
        return errCodes;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_23594799/article/details/108012464