如何在类似的方法中消除重复的try-catch代码?

时间:2017-03-28 06:23:33

标签: java refactoring code-duplication

我的服务中有以下插入/更新方法:

@Override
public void insertEntity(Entity entity) {

  try {        
    entityDao.insert(entityMapper.entityToEntityDO(entity));

  } catch (DataIntegrityViolationException ex){

    if(ex.getCause() instanceof SQLIntegrityConstraintViolationException) {
      SQLIntegrityConstraintViolationException violationEx = (SQLIntegrityConstraintViolationException) ex.getCause();
      if(violationEx.getErrorCode() == 1048 && "23000".equals(violationEx.getSQLState())) {
        throw new FieldCannotBeNullException(violationEx.getMessage());
      }
    }

    throw ex;
  }
}

@Override
public void updateEntity(Entity entity) {

  try {        
    entityDao.update(entityMapper.entityToEntityDO(entity));

  } catch (DataIntegrityViolationException ex){

    if(ex.getCause() instanceof SQLIntegrityConstraintViolationException) {
      SQLIntegrityConstraintViolationException violationEx = (SQLIntegrityConstraintViolationException) ex.getCause();
      if(violationEx.getErrorCode() == 1048 && "23000".equals(violationEx.getSQLState())) {
        throw new FieldCannotBeNullException(violationEx.getMessage());
      }
    }

    throw ex;
  }
}

如您所见,insertEntityupdateEntity的实际逻辑非常简单。为了抛出自定义Exception,我做了一些数据库错误代码检查。由于这两种方法都需要这种检查,因此代码在两种方法中都重复,这显然是一种代码味道。

如何消除这种代码重复?

4 个答案:

答案 0 :(得分:2)

将公共catch块提取到抛出DataIntegrityViolationException

的方法

答案 1 :(得分:0)

您可以将catch块中的代码放入单独的方法中。

或者,您可以捕获Exception并编写处理程序方法来处理异常,如果将来您希望在那里处理多个异常。

答案 2 :(得分:0)

您可以像这样创建界面:

public interface ConsumerWithException<T, V extends Exception> {
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t) throws V;

}

使用私有方法,如:

private void action(ConsumerWithException<Entity, DataIntegrityViolationException> doAction, Entity entity){
    try {
        doAction.accept(entity);
    } catch (DataIntegrityViolationException ex){

        if(ex.getCause() instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException violationEx = (SQLIntegrityConstraintViolationException) ex.getCause();
            if(violationEx.getErrorCode() == 1048 && "23000".equals(violationEx.getSQLState())) {
                throw new FieldCannotBeNullException(violationEx.getMessage());
            }
        }

        throw ex;
    }
}    

答案 3 :(得分:0)

您可以声明方法以引发异常,然后在调用方法的一个位置尝试/捕获。例如:

public void insertEntity(Entity entity) throws DataIntegrityViolationException {} 
public void updateEntity(Entity entity) throws DataIntegrityViolationException {}  
try {
  insertEntity(entity);
  updateEntity(entity);
catch (DataIntegrityViolationException e) {
  // handle exception
}