删除执行多个验证的代码片段中的重复

时间:2015-12-20 12:44:14

标签: java refactoring

我想将这个方法重构为没有重复的东西:

public class ContextValidator
{
    public static boolean validate(LoggingContext loggingContext) throws ValidationException
    {
        if (!isValidValue(loggingContext.getApplicationlevel()))
        {
            throw new ValidationException(UserErrors.UE_BAD_PARAMS,
                new Object[] { "Applicationlevel", "must be between 0 and 5" });
        }

        if (!isValidValue(loggingContext.getAuditlevel()))
        {
            throw new ValidationException(UserErrors.UE_BAD_PARAMS,
                new Object[] { "Auditlevel", "must be between 0 and 5" });
        }

        if (!isValidValue(loggingContext.getBillinglevel()))
        {
            throw new ValidationException(UserErrors.UE_BAD_PARAMS,
                new Object[] { "Billinglevel", "must be between 0 and 5" });
        }

        if (!isValidValue(loggingContext.getMetricslevel()))
        {
            throw new ValidationException(UserErrors.UE_BAD_PARAMS,
                new Object[] { "Metricslevel", "must be between 0 and 5" });
        }

        if (!isValidValue(loggingContext.getSecuritylevel()))
        {
            throw new ValidationException(UserErrors.UE_BAD_PARAMS,
                new Object[] { "Securitylevel","must be between 0 and 5" });
        }
        return true;
    }

    private static boolean isValidValue(int applicationlevel)
    {
        return (applicationlevel >= 0) && (applicationlevel <= 5);
    }
}

其中getXXXLevel()是返回int的方法。我尝试创建对字符串的方法引用的映射:Map<Supplier<Integer>, String> (ex: loggingContext::getBillinglevel, "BillingLevel")并在forEach()中测试它们 - 检查了unfortunatelly ValidationException因此无法使用我的地图类型从forEach中抛出它

1 个答案:

答案 0 :(得分:1)

将整个if包装到辅助方法中:

public static void checkAndThrow(int val, String name)
    throws ValidationException
{
    if (!isValidValue(val) {
        throw new ValidationException(UserErrors.UE_BAD_PARAMS,
            new Object[] { name, "must be between 0 and 5" });
    }
}

现在,您可以通过调用if来替换每个checkAndThrow

public static boolean validate(LoggingContext loggingContext)
    throws ValidationException
{
    checkAndThrow(loggingContext.getApplicationlevel(), "Applicationlevel");
    checkAndThrow(loggingContext.getAuditlevel(), "Auditlevel");
    checkAndThrow(loggingContext.getBillinglevel(), "Billinglevel");
    ...
    return true;
}