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.
CodePudding user response:
This is what you asked for, I dont't know if it's elegant, your method looks fine as is to me, the only thing I would change is to create an InvalidUserException which takes in the name of the null field.
This can be a good exercise to understand data structures and the Functional Interface, but I wouldn't do it this way for something as simple as this.
You could check out the simplified strategy pattern with lambdas.
EDIT: This could be useful if you have a very complex validation logic on many fields, but simply for checking that no field is null I agree with using the Lombok approach as suggested in the comments.
public class App {
public static HashMap<String, Predicate<User>> VALIDATION_FUNCTIONS = new HashMap<>();
static {
VALIDATION_FUNCTIONS.put("NAME", user -> user.getName() != null);
VALIDATION_FUNCTIONS.put("MOREFIELDS", user -> user.getMorefields() != null);
}
public static void main(String[] args) {
validateUserFields(new User());
}
private static void validateUserFields(User user) {
VALIDATION_FUNCTIONS.forEach((field,function) -> {
if (!function.test(user)) {
throw new RuntimeException(field " is null");
}
}
);
}
@Getter
@NoArgsConstructor
static class User {
private String name;
private String morefields;
}
}
CodePudding user response:
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)
.findFirst()
.ifPresent(entry -> {
throw new RuntimeException("The user's " entry.getKey() " cannot be null");
});
}
I don't know if it's "elegant", but it is scaleable and flexible.