I would like to know how i can refactor my code using a Map Data Structure and Lambdas.
Here is my method:
private void validateUserFields(User user) {
if(user.getName() == null){
throw new RuntimeException("The user's name cannot be null");
}
if(user.getLastName() == null){
throw new RuntimeException("The user's lastName cannot be null");
}
if(user.getDni() == null){
throw new RuntimeException("The user's dni cannot be null");
}
if(user.getVehicle() == null){
throw new RuntimeException("The user's vehicle cannot be null");
}
}
I expect a elegant an a simple way to refactor my code.
Try a map of validations:
private static Map<String, Function<User, ?>> VALIDATIONS = Map.of(
"name", User::getName,
"lastName", User::getLastName,
"dni", User::getDni,
"vehicle", User::getVehicle
);
private void validateUserFields(User user) {
VALIDATIONS.entrySet().stream()
.filter(entry -> entry.getValue().apply(user) == null)
.map(Map.Entry::getKey)
.map(field -> String.format("The user's %s cannot be null", field))
.map(RuntimeException::new)
.findFirst()
.ifPresent(e -> {
throw e;
});
}
or this briefer version that bypasses the use of method references:
private void validateUserFields(User user) {
VALIDATIONS.entrySet().stream()
.filter(entry -> entry.getValue().apply(user) == null)
.findFirst()
.ifPresent(e -> {throw new RuntimeException("The user's " + e.getKey() + " cannot be null");});
}
I don't know if it's "elegant", but it is scaleable and flexible.