mercredi 16 octobre 2019

design patterns (command pattern) to avoid the multiple if conditions

  1. This is the request that been sent to service layer
public class UserRequest {

    private String id;
    private String link;
    private String searchText;
}
  1. Created class for "user response creator" -> to have different transformations
@Component
public class UserResponseCreator {
    @Autowired
    private UserInfoServiceClient userInfoServiceClient;

    public List<UserResponse> getUserResponse() {
    //transformation one
    }

    public List<UserResponse> getUserResponse(UserRequest request) {
    //transformation two
    }
}
  1. The service class:
@Service
public class UserService {
@Autowired
    private UserResponseCreator UserResponseCreator;

    public List<UserResponse> sendEntries(UserRequest request) {

        String node = request.getnode();
        String link = request.getLinkedTo();
        String searchText = request.getSearchText();

        List<UserResponse> UserResponses = new ArrayList<>(); 

        if ( node == null && link == null && searchText == null ) {
            UserResponses = UserResponseCreator.getUserResponse();

        } else if (node != null && link != null) {
                UserResponses = UserResponseCreator.getUserResponse(request);

        } else if (searchText!=null) { 
            UserResponses = UserResponseCreator.getUserResponse();
        } else {
            throw new InvalidRequestBodyException("Please check the request body");
        }

        return UserResponses;  
    }

}

Now I have following issues:

  1. How to avoid the multiple if and repeated null checks

Have to use command pattern and create a method to pass parameter , check null values

For the null check i prepared a method:

public boolean checkFieldsIsNull(Object... varArgs) {
        return Stream.of(varArgs)
                .allMatch(Objects::isNull);
    }

Aucun commentaire:

Enregistrer un commentaire