如何重构此验证方法

时间:2018-02-18 23:06:38

标签: java refactoring code-duplication

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

  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);
        }
    }

2 个答案:

答案 0 :(得分:4)

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

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

然后您可以使用

而不是您的条件
checkError(shape.getShapeName().isEmpty(), "Empty Shape.");

答案 1 :(得分:0)

除了@ T.Garcin的回答,

这个if语句:

shape.getShapeDesc().isEmpty() || shape.getShapeDesc().trim().length() == 0

可以缩短到恰当的条件,因为它会是相同的。但是我建议修改Shape构造函数中的值然后只调用isEmpty而不是记得在任何地方调用trim。

这意味着您也不必进行此项检查

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);
}