In a scenario, where we have to write complex if-else, it is helpful to have code as concise as possible inside the business logic code block to help with the bigger picture of the product specifications.
Here I am exploring the possibility of using Functional Interfaces as inner functions, motivation being the added scope of the outer function which will help access the outer function’s variables directly without having to be passed to a method as parameters.
This could very well be a utility function for a specific use case which applies to only the current business scenario. For instance, formatting date string based on a user setting ? Maybe.
it would ideally be a utility function to which you pass a timestamp and it returns you a formatted string with user time zone etc. considered. Complexity can be added in a real world scenario.
List<String> employees = Arrays.asList("John","Jane");
List<String> names = Arrays.asList("John","Jane","Jack");
List<String> employeeIds = new ArrayList<>();
// Construct and add EmployeeId to employeeIds list if a person is an employee
Function<String,String> getEmployeeId = (String name) -> {
if(employees.contains(name)) {
return name.toUpperCase();
}
return null;
};
for(String name : names){
String id = getEmployeeId.apply(name);
if(id != null) employeeIds.add(id);
}
System.out.println(employeeIds);`
I tried implementing a few lambdas as inner methods to check, they worked fine. As doing this goes against functional programming prohibiting side effects and asking to write pure functions, I am not sure if it should be done or not.
2