Click here to Skip to main content
15,848,391 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
This is my method, which I am using Optional to avoid NullPointerException, but I want to do that using without if else statement to avoid nullpointer exception. is it possible or is there any way, that I say using without if else statement control any structure?

Java
@Override
    public void save2(Optional<CheckResponse> response) {
        if (response.isPresent()) {
            CheckResponse checkResponse = response.get();
            if (checkResponse.getValue().isPresent()) {
                Optional<List<CheckDetails>> value = checkResponse.getValue();
                if (value.isPresent()) {
                    List<CheckDetails> checkDetails = value.get();
                    Stream<Checks> checksStream = checkDetails.stream().map(this::mapDtoCheckDetailsToEntiyChecks);
                    Optional<Checks> first = checksStream.findFirst();
                    if (first.isPresent()) {
                        Checks checks = first.get();
                        this.checkRepository.save(checks);
                    }
                }
            }
            Checked checked = new Checked();
            checked.setResponse(checkResponse.getResponse());
            checked.setServiceResponse(checkResponse.getServiceResponse());
            checked.setErrorMessage(checkResponse.getErrorMessage());
            if (checkResponse.getBrokenRules().isPresent()) {
                List<BrokenRulesResponse> brokenRulesResponses = checkResponse.getBrokenRules().get();
                brokenRulesResponses.forEach(brokenRulesResponse -> {
                    checked.setMessage(brokenRulesResponse.getMessage());
                    checked.setMember(brokenRulesResponse.getMember());
                    this.checkedRepository.save(checked);
                });
            }
        }
    }


And the piece of code I show here is the event described in an article. And here it is said finally, we have avoided all the potential NullPointerExceptions and the code is now safe. However, that made the method ugly. Moreover, think about the case where there are more nested objects like this. However, as far as I understand, I have done the same operation by using unlimited if control conditions. There is only one thing I want here. Can I shorten the code by using Optional without using too many if control conditions?

Java
if (users != null) {
    
    User user = users.get(0);
    if (user != null) {
        
        Address address = user.getAddress();
        if (address != null) {
        
            String state = address.getState();
            if (state != null) {
                System.out.println("State is " + state);
            }
        }
    }
}


What I have tried:

I still finding any solution but I couldn't find.
Posted
Updated 29-Nov-21 22:29pm
v2

1 solution

The null checks are there for a reason - to make sure that there is a User, that the user has an Address, and the address includes a State - without these, there is no information to process - and the null return is the way the method tells you "Does not exist".

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

If it is possible to have a "missing user", a "missing address", or a "missing state" then you need to check in some way to ensure you don't go off the rails - if you don;t you will get a "null reference exception" and you app will crash if that isn't handled somewhere!
 
Share this answer
 
Comments
[no name] 30-Nov-21 4:23am    
I just want to using this logic without if control statament is it possible?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900