How to avoid null in Java method chain

81 views Asked by At

Here is my code snippet.

     String fileName = "";
     FileDTO file = 
     FileService.findById(fileId);
    if(file != null && file.getFileFormate() != null){
        fileName = file.getFileName();
        fileName = "." +file.getFileFormate().getExtension();
    }

Here I can see chance of Null pointer exception. If file not null and then file.getFileFormate() not null then I can call file.getFileFormate().getExtension(). So I have to check null for each of them. Is there any flied way to check it. Something like:-

file?.getFileFormate()?.getExtension()

Also does JVM execute code from left to right for right to left?

So my code cold as check:

if(file != null && file.getFileFormate() != null)

or

if(file.getFileFormate() != null  && file != null)

or

if(null != file.getFileFormate()  &&  null != file)
1

There are 1 answers

0
JustAnotherDeveloper On BEST ANSWER

Since presumably FileDTO is a class you've written, you can simplify your checks for null values like so:

if(file != null){
    fileName = file.getFileName();
    fileName = "." +file.getExtension();
}

And then add something like the following to FileDTO:

public String getExtension() {
    String extension = "";
    if (this.getFileFormate() != null) {
        extension = this.getFileFormate().getExtension();
    }
    return extension;
}

This has the added benefit of not exposing internal implementation details of FileDTO.

As for your other question, as the comment already said, it's left to right, but some operators have an order of precedence.