【问题标题】:How to refactor this validation method如何重构此验证方法
【发布时间】:2018-02-18 23:06:38
【问题描述】:

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

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

【问题讨论】:

    标签: java refactoring code-duplication


    【解决方案1】:

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

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

    然后你可以使用而不是你的条件

    checkError(shape.getShapeName().isEmpty(), "Empty Shape.");
    

    【讨论】:

      【解决方案2】:

      除了@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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 2013-09-29
        相关资源
        最近更新 更多