PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

[FIXED] How to refactor if statements with a Map using Java 8 Lambdas

 November 03, 2022     dictionary, hashmap, java, lambda, validation     No comments   

Issue

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.


Solution

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.



Answered By - Bohemian
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing