gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:43:05 25 4
gpt4 key购买 nike

我想将此方法重构为不重复的方法:

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() 中测试它们- 不幸的是ValidationException已检查,因此不能使用我的 map 类型从 forEach 抛出它。

最佳答案

将整个 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;
}

关于java - 删除执行多个验证的代码片段中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com