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