You could create an isEmpty() method for each class that checks what ever fields it needs to to determine if it is 'empty' or not. For classes that contain other classes, its isEmpty() method could call the isEmpty() method of the contained class. In this way you would encapsulate the tests.
If you're talking about the chain of nested if statements, take a look at Optional. One implementation of this class is in the JDK for Java 8. If you aren't running Java 8, you can also find other (slightly different) implementations provided by some third party libraries such as Guava. Here's what those ifs might look like with the Java 8 Optional:
S Majumder wrote:Any better way by which can check null values would be appreciable...
I think the great advice so far should help you out there.
My advice is slightly different: Why deal with them at all?
It's tough to know exactly what's going on since you haven't shown us your Client class, but my question is this: Why would a method called getEmployee()not return an Employee?
And if it does return one, why would it not have an Address?
It seems to me that you're dealing with symptoms of a problem instead of tackling the cause, which is that you can have either incomplete or non-existent Employees.
However, if you really can't do anything about it, then another possibility might be to add hasEmployee()/hasAddress() methods, a bit like the way Iterator does it.
I dislike it, for the reason I gave above (it only tackles the symptom), and TBH, if you're on version 8 then Jason's solution is better - but if this code isn't under your control then it's possible that you can't do much about it.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
allen robin wrote:Hey,First you should check if employees itself isn't null, then simply check whether books[i] != null:
allen, please check how to UseCodeTags when you post any code on Ranch. I have added them for you, looks better, isn't?
If you check for books == null and throwing IllegalArgumentException without supplying message, better throw NullPointerException which would be more appropriate. Joshua Bloch in his Effective Java book states, that IllegalArgumentException should be thrown for illegal non null values. Either one or another, string message in it would be nice too.
Code snippet indentation not good enough. Here is Beginning Java forum, so better do not to give OP a feeling, that omitting curly braces is a good thing - which is indeed not, even to there are lots of code in production written like in your example.
If a regular clown is funny, then a larger clown would be funnier. Math. Verified by this tiny ad: