【发布时间】: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