2

我有两个函数调用 Employee 和 Address DAO 类,我检查员工姓名或地址是否已被使用

为了使其通用以检查和抛出异常,我创建了以下通用函数

CommonUtil.java中的checkOrElseThrow

public static <R, C, T extends Throwable> R checkOrElseThrow(R rtn, C chk, Supplier<? extends T> ex) throws T
{
    if (chk != null)
    {
        throw ex.get();
    }
    return rtn;
}

上面的通用函数在EmployeeDAO.javaAddressDAO.java中被调用,如下所示

EmployeeDAO.java中的checkAndReturnEmployee

public Employee checkAndReturnEmployee(Employee employee) {
    return checkOrElseThrow(
        employee,
        employee.getAddressName(),
        () -> new EntityNotFoundException("Employee already in use for another address"));
}

AddressDAO.java中的checkAndReturnAddress

public Address checkAndReturnAddress(Address address) {
    return checkOrElseThrow(
        address,
        address.getEmployeeName(),
        () -> new EntityNotFoundException("Address already in use for another address"));
}

问题

我的解决方案运行良好,但我想知道是否有任何其他更好的方法来重写我编写的通用函数(checkOrElseThrow

4

3 回答 3

5

写这个的最好方法是不要。

public Employee checkAndReturnEmployee(Employee employee) {
    if (employee.getAddressName() == null) {
      throw new EntityNotFoundException("Employee already in use for another address"));
    }
    return employee;
}

上面的代码同样简短,但更具可读性。更清楚的是条件是什么,不满足时会发生什么。

您的自定义函数仅用于尝试为 Java 创建一种新语法,这是其他人不会理解的,而且您可能很快也会忘记。

于 2020-04-04T21:56:01.427 回答
1

考虑使用java.util.Optional,因为您尝试实现的行为已经存在。我发现它比if (smth != null)支票优雅得多。

Optional.ofNullable(employee)
    .map(Employee::getAddressName)
    .orElseThrow(() -> new EntityNotFoundException("Employee already in use for another address");

一般来说,我更喜欢主要是因为如果还需要空检查(不是这个问题的情况),Optional可能会嵌套多个s 或链接条件。然后,您将需要比带有 Optional 的链接版本更难看且可读性差的东西。当然,后一种说法也有点句法品味。ifentityif (entity != null && entity.getAddress() == null) {throw ...}

于 2020-04-04T22:27:59.293 回答
1

由于问题更多的是围绕通用实现,您可以修改现有实现以使用 aPredicate来测试任何标准并将其计算为:

public <R, T extends Throwable> R checkOrElseThrow(R returnValue, Predicate<R> successCriteria,
                                                   Supplier<? extends T> ex) throws T {
    if (successCriteria.test(returnValue)) {
        return returnValue;
    }
    throw ex.get();
}

并在相应的地方进一步调用它:

public Employee checkAndReturnEmployee(Employee employee) throws EntityNotFoundException {
    return checkOrElseThrow(employee, emp -> emp.getAddressName() != null,
            () -> new EntityNotFoundException("Employee already in use for another address"));
}

public Address checkAndReturnAddress(Address address) throws EntityNotFoundException {
    return checkOrElseThrow(address, add -> add.getEmployeeName() != null,
            () -> new EntityNotFoundException("Address already in use for another address"));
}
于 2020-04-05T03:29:28.387 回答