I have one requirement
For this requirement, i am using functional programming to achieve the result.
Here I have created the multiple functions in my Service layer
final Function<String, Employee> getRegisteredEmployee =
localId -> employeeRepository.findById(employeeId).
orElseThrow(() -> new ResourceNotFoundException("ResourceNotFound"));
final Function<Employee, Employee> updateEmployeAddressandSave =
employe -> {
String status = //some logic to identitythe Employee
Employee e = new Employee(employee.getName(),employee.getAddress ,"INTERNAL_EMPLOYEE")
Employee emp = employeeRepository.save(e);
return emp;
};
Likewise, I created different functions and then I am using the andThen method of the functional interface to get the results
getRegisteredEmployee.
andThen(updateEmployeAddressandSave).
andThen(transformTheEmployeeToGatewayRequest).
andThen(allgateWayClinet).apply(12);
According to the functional programming model, a function should take input and give some output; it should not throw any exception. But in my example getRegisteredEmployee throws an exception if employee is not found.
Hence, am I not following the functional programming core principles?
what is the alternate way to throw the exception in functional programming?
While not adhering to principles, it is technically possible to create a functional interface that will throw a checked exception.
@FunctionalInterface
interface CheckedFunction<A, B> {
B apply(A a) throws Exception;
}
(Since you're using andThen you'll need to implement that as well using the default keyword. Remember, though, that the functional interface must have at most one non-default method, so you'll have to provide the andThen implementation defaulted.)
So, as an example, you would be able to do something like:
public void doThings(Integer id) throws Exception {
CheckedFunction<Integer, Employee> fn = (id) -> someMethodThatReturnsAnEmployeeOrThrows(id);
fn.apply(id)
.map( ... ) // ... some other stuff
}
As I mentioned, this doe not adhere to principles; I only go down this path when I absolutely have to bubble the exception up. Other Java 8 features such as Optional are more appropriate in this situation. (Since it looks like you're using spring's JPA implementation, you can define your findById method to return an Optional<Employee>.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With