Better way to write the checkOrElseThrow generic function

Alex Man :

I have two function calls for Employee and Address DAO class where I check if the employee name or address is already in used

For making it generic to check and throw exception I have created the following generic function

checkOrElseThrow in CommonUtil.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;
}

and the above generic function is been called in EmployeeDAO.java and AddressDAO.java like as shown below

checkAndReturnEmployee in EmployeeDAO.java

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

checkAndReturnAddress in AddressDAO.java

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

Question

My solution is working fine, but I would like to know if there is any other better way to rewrite the generic function (checkOrElseThrow) which I have written

weston :

The best way to write this is to not.

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

The code above is just as short, but far more readable. It's clearer what the condition is, and what happens when it is not met.

Your custom function only serves to attempt to create a new syntax for Java, one that other people will not understand, and you may soon forget also.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409712&siteId=1