gpt4 book ai didi

java - 如何重构这个验证方法

转载 作者:行者123 更新时间:2023-11-29 08:30:19 26 4
gpt4 key购买 nike

我下面有很多重复的代码。我在想是否有办法清理它并删除大量重复的代码。我想我应该创建一个方法来进行日志记录并抛出异常?但是我无法思考如何去做

  for (Shape shape : Shapes) {
if (shape.getShapeName().isEmpty()) {
final String mesg = String.format("Empty Shape.");
log.error(mesg);
throw new Exception(mesg);
}

invalidChar = p.matcher(shape.getShapeName()).find();

if (invalidChar) {
final String mesg = String.format("Invalid character(s) in Shape name %s",
shape.getShapeName());
log.error(mesg);
throw new Exception(mesg);
}

if (shape.getShapeDesc().isEmpty() || shape.getShapeDesc().trim().length() == 0) {
final String mesg = String.format("Empty Shape description.");
log.error(mesg);
throw new Exception(mesg);
}

if (Character.isWhitespace(shape.getShapeDesc().charAt(0))) {
final String mesg = String.format("Empty first character in Shape description %s", shape.getShapeDescription());
log.error(mesg);
throw new Exception(mesg);
}

p = Pattern.compile("[^a-zA-Z0-9]+");
invalidChar = p.matcher(shape.getShapeDesc()).find();

if (invalidChar) {
final String mesg = String.format("Invalid character in Shape description %s", shape.getShapeDesc());
log.error(mesg);
throw new Exception(mesg);
}
}

最佳答案

您可以编写一个方法,它接受两个参数,一个 boolean 值和一个字符串,并在该方法中调用带有日志记录和错误抛出的条件

void checkError(boolean condition, String message) {
if(condition) {
log.error(message);
throw new Exception(message);
}
}

然后您可以使用

代替您的条件
checkError(shape.getShapeName().isEmpty(), "Empty Shape.");

关于java - 如何重构这个验证方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857580/

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