编写 checkOrElseThrow 通用函数的更好方法

Ale*_*Man 2 java lambda throwable java-8 supplier

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

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

checkOrElseThrowCommonUtil.java

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;
}
Run Code Online (Sandbox Code Playgroud)

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

checkAndReturnEmployeeEmployeeDAO.java

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

checkAndReturnAddressAddressDAO.java

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

我的解决方案工作正常,但我想知道是否有其他更好的方法来重写我编写的通用函数(checkOrElseThrow

wes*_*ton 5

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

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

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

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