#Nonnull with different IDEs - warn about unnecessary null checks - java

I'm working in an environment where developers use different IDEs - Eclipse, Netbeans and IntelliJ. I'm using the #Nonnull annotation (javax.annotation.Nonnull) to indicate that a method will never return null:
#Nonnull
public List<Bar> getBars() {
return bars; // this.bars is a final, initialized list
}
I'd like other developers to get a warning if they do one of the following:
Change the method to return null without removing the #Nonnull annotation
Unnecessarily check for null for methods that are explicitly defined with #Nonnull: if (foo.getBars() == null) { ... do something ... }
The first scenario is supported e.g. by IntelliJ. The second is not; the clients are not warned that checking for null is unnecessary.
We're in any case planning to move towards returning clones of collections instead of the collections themselves, so is it better to forget #Nonnull and do this instead:
public List<Bar> getBars() {
return new ArrayList<Bar>(bars);
}
Edit:
To clarify, I'm not considering changing IDE's for this. I'd like to know whether what I described above is supported by the mentioned IDEs - or alternatively, if there is a good reason as to why it is not supported.
I get the point about not relying too much on contracts. However, if I write getBars() with the style in the last paragraph (return a clone of the list), then e.g. IntelliJ flags a warning for any code that does
if (foo.getBars() == null) { ... }
If you choose to follow this warning and remove the null check, you seem to be equally reliant on the getBars() implementation not changing. However, in this case you seem to be depending on implementation details instead of an explicit contract (as is the case with #Nonnull).
Edit #2:
I'm not concerned about execution speed, null checks are indeed very fast. I'm concerned about code readability. Consider the following:
Option A:
if ((foo.getBars() == null || foo.getBars().size() < MAXIMUM_BARS) &&
(baz.getFoos() == null || baz.getFoos().size() < MAXIMUM_FOOS)) {
// do something
}
Option B:
if (foo.getBars().size() < MAXIMUM_BARS &&
baz.getFoos().size() < MAXIMUM_FOOS) {
// do something
}
I think Option B is more readable than Option A. Since code is read more often than it is written, I'd like to ensure all code I (and others in our team) write is as readable as possible.

I would recommend the following:
Stick with your #Nonnull and #Nullable annotations just like you are doing it already.
Define and enforce a default. It doesn't really matter what the default is, but it should be the same across your entire code base.
Use FindBugs to check for your cases 1 and 2. FindBugs has plugins for most IDEs, I saw Eclipse, Netbeans, and IntelliJ mentioned, but there are more. (The number 2 case is covered by the RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE rule. I tested it. Just thought I should mention that after reading DavidHarkness' comment elsewhere on this page.)
This approach is IDE agnostic and works also in an external build environment like Hudson or Jenkins.

I guess, with your annotation you want to do two things:
make the program faster
make the programmers have to work less (because they don't have to type the null-checks)
For the first one: A Null-check consumes hardly any resources. If you run this sample:
public static void main(String[] args) {
long ms = System.currentTimeMillis();
for (int i=0;i<10000;i++) {
returnsNonNull(i);
doNothing();
}
System.out.println("Without nullcheck took "+(System.currentTimeMillis()-ms)+" ms to complete");
ms = System.currentTimeMillis();
for (int i=10000;i<20000;i++) {
if (returnsNonNull(i)!=null) {
doNothing();
}
}
System.out.println("With nullcheck took "+(System.currentTimeMillis()-ms)+" ms to complete");
}
public static String returnsNonNull(int i) {
return "Foo "+i+" Bar";
}
public static void doNothing() {
}
You will see, there is hardly any difference between these two tests. The second one (with the null-check) is sometimes even faster than the first one, meaning they both are pretty much indistinguishable when it comes to resource use.
Now to the second point:
You are actually making the programmers work more, not less. Except if there are absolutely no functions in your whole project and framework that ever return null the programmer now has to look up the function each time to check if he has to do a null-check or not. Seeing that about every framework in Java can under some conditions return null in some functions you are not reducing the workload for your programmers.
You said you want a warning to appear when they do a null-check where it is not necessary because of your #Nonnull-annotation. So what they will do is they type out the whole null-check and then get a warning and have to remove it again. See what I mean?
Also what if you make a mistake in your code and mark something as #Nonnull that can return null?
What I'd do is write it into the Javadoc under #return. Then the programmer can decide what he does, which is usually better than forcing others to write code your style.

Related

Avoid duplicated code 'cause of null objects? [duplicate]

I use x != null to avoid NullPointerException. Is there an alternative?
if (x != null) {
// ...
}
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
Where null is a valid response in terms of the contract; and
Where it isn't a valid response.
(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)
"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.
public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.
Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the Null Object pattern:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
Compare:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
to
ParserFactory.getParser().findAction(someInput).doSomething();
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got #Nullable and #NotNull.
You can use in method and parameters, like this:
#NotNull public static String helloWorld() {
return "Hello World";
}
or
#Nullable public static String helloWorld() {
return "Hello World";
}
The second example won't compile (in IntelliJ IDEA).
When you use the first helloWorld() function in another piece of code:
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.
Using parameter
void someMethod(#NotNull someParameter) { }
if you write something like:
someMethod(null);
This won't compile.
Last example using #Nullable
#Nullable iWantToDestroyEverything() { return null; }
Doing this
iWantToDestroyEverything().something();
And you can be sure that this won't happen. :)
It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other #Nullable #NotNull implementations.
See blog post More flexible and configurable #Nullable/#NotNull annotations.
If null-values are not allowed
If your method is called externally, start with something like this:
public void method(Object object) {
if (object == null) {
throw new IllegalArgumentException("...");
}
Then, in the rest of that method, you'll know that object is not null.
If it is an internal method (not part of an API), just document that it cannot be null, and that's it.
Example:
public String getFirst3Chars(String text) {
return text.subString(0, 3);
}
However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.
If null is allowed
This really depends. If find that I often do something like this:
if (object == null) {
// something
} else {
// something else
}
So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?
It's actually rare for me to use the idiom "if (object != null && ...".
It may be easier to give you examples, if you show examples of where you typically use the idiom.
Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.
The example given by Alex Miller looks like this:
public String getPostcode(Person person) {
return person?.getAddress()?.getPostcode();
}
The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.
Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.
Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.
If undefined values are not permitted:
You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see Preferences > Java > Compiler > Errors/Warnings/Null analysis.
If undefined values are permitted:
If you want to define a new API where undefined values make sense, use the Option Pattern (may be familiar from functional languages). It has the following advantages:
It is stated explicitly in the API whether an input or output exists or not.
The compiler forces you to handle the "undefined" case.
Option is a monad, so there is no need for verbose null checking, just use map/foreach/getOrElse or a similar combinator to safely use the value (example).
Java 8 has a built-in Optional class (recommended); for earlier versions, there are library alternatives, for example Guava's Optional or FunctionalJava's Option. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.
If you have to deal with an API which might return nulls, you can't do much in Java. Xtend and Groovy have the Elvis operator ?: and the null-safe dereference operator ?., but note that this returns null in case of a null reference, so it just "defers" the proper handling of null.
Only for this situation -
Not checking if a variable is null before invoking an equals method (a string compare example below):
if ( foo.equals("bar") ) {
// ...
}
will result in a NullPointerException if foo doesn't exist.
You can avoid that if you compare your Strings like this:
if ( "bar".equals(foo) ) {
// ...
}
With Java 8 comes the new java.util.Optional class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.
They work like that:
An optional object for a given type (Fruit) is created as the return type of a method. It can be empty or contain a Fruit object:
public static Optional<Fruit> find(String name, List<Fruit> fruits) {
for (Fruit fruit : fruits) {
if (fruit.getName().equals(name)) {
return Optional.of(fruit);
}
}
return Optional.empty();
}
Now look at this code where we search a list of Fruit (fruits) for a given Fruit instance:
Optional<Fruit> found = find("lemon", fruits);
if (found.isPresent()) {
Fruit fruit = found.get();
String name = fruit.getName();
}
You can use the map() operator to perform a computation on--or extract a value from--an optional object. orElse() lets you provide a fallback for missing values.
String nameOrNull = find("lemon", fruits)
.map(f -> f.getName())
.orElse("empty-name");
Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.
In an API built from scratch using Optional whenever a return value might be empty, and returning a plain object only when it cannot be null (convention), the client code might abandon null checks on simple object return values...
Of course Optional could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.
Optional offers other convenient methods, such as orElse that allow the use of a default value, and ifPresent that works with lambda expressions.
I invite you to read this article (my main source for writing this answer) in which the NullPointerException (and in general null pointer) problematic as well as the (partial) solution brought by Optional are well explained: Java Optional Objects.
Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections
Example:
String foo;
...
if( StringUtils.isBlank( foo ) ) {
///do something
}
or (depending on what you need to check):
String foo;
...
if( StringUtils.isEmpty( foo ) ) {
///do something
}
The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.
Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)
public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
return read(new StringReader(xml), true, validationEventHandler);
}
And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)
Example on how to use this static classf from spring(org.springframework.util.Assert)
Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
If you consider an object should not be null (or it is a bug) use an assert.
If your method doesn't accept null params say it in the javadoc and use an assert.
You have to check for object != null only if you want to handle the case where the object may be null...
There is a proposal to add new annotations in Java7 to help with null / notnull params:
http://tech.puredanger.com/java7/#jsr308
I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... i.e. - it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.
Sometimes, you have methods that operate on its parameters that define a symmetric operation:
a.f(b); <-> b.f(a);
If you know b can never be null, you can just swap it. It is most useful for equals:
Instead of foo.equals("bar"); better do "bar".equals(foo);.
Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.
When the exception is thrown, examine the stack trace and work through the bug.
The Google collections framework offers a good and elegant way to achieve the null check.
There is a method in a library class like this:
static <T> T checkNotNull(T e) {
if (e == null) {
throw new NullPointerException();
}
return e;
}
And the usage is (with import static):
...
void foo(int a, Person p) {
if (checkNotNull(p).getAge() > a) {
...
}
else {
...
}
}
...
Or in your example:
checkNotNull(someobject).doCalc();
Null is not a 'problem'. It is an integral part of a complete modeling tool set. Software aims to model the complexity of the world and null bears its burden. Null indicates 'No data' or 'Unknown' in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the 'who will guard
the guardians' problem.
If you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null.
An alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user.
For an 'unknown question' give 'unknown answer'. (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.
public Photo getPhotoOfThePerson(Person person) {
if (person == null)
return null;
// Grabbing some resources or intensive calculation
// using person object anyhow.
}
Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.
getPhotoOfThePerson(me.getGirlfriend())
And it fits with new coming Java API (looking forward)
getPhotoByName(me.getGirlfriend()?.getName())
While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases
public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException
public static MyEnum parseMyEnumOrNull(String value);
And don't loathe to type <alt> + <shift> + <j> (generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.
/**
* #return photo or null
*/
or
/**
* #return photo, never null
*/
This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but NullPointerException is subclass of an Exception. Thus it is a form of Throwable that indicates conditions that a reasonable application might want to catch (javadoc)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (according to creators of Java) it is appropriate, as for me, to catch NullPointerException.
public Photo getGirlfriendPhoto() {
try {
return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());
} catch (NullPointerException e) {
return null;
}
}
Questions could arise:
Q. What if getPhotoDataSource() returns null?
A. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized to be fail-fast in case of programmer errors.
Q. Redundant code could be executed and unnecessary resources could be grabbed.
A. It could take place if getPhotoByName() would try to open a database connection, create PreparedStatement and use the person name as an SQL parameter at last. The approach for an unknown question gives an unknown answer (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.
Q. This approach has a performance penalty due to the try closure opening.
A. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (source), and many others).
PS. This approach will be as reasonable to use as the separate error-handling code from "regular" code principle is reasonable to use in some place. Consider the next example:
public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
try {
Result1 result1 = performSomeCalculation(predicate);
Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
Result3 result3 = performThirdCalculation(result2.getSomeProperty());
Result4 result4 = performLastCalculation(result3.getSomeProperty());
return result4.getSomeProperty();
} catch (NullPointerException e) {
return null;
}
}
public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
SomeValue result = null;
if (predicate != null) {
Result1 result1 = performSomeCalculation(predicate);
if (result1 != null && result1.getSomeProperty() != null) {
Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
if (result2 != null && result2.getSomeProperty() != null) {
Result3 result3 = performThirdCalculation(result2.getSomeProperty());
if (result3 != null && result3.getSomeProperty() != null) {
Result4 result4 = performLastCalculation(result3.getSomeProperty());
if (result4 != null) {
result = result4.getSomeProperty();
}
}
}
}
}
return result;
}
PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was intentionally designed by the Java creators because NPE is a subclass of Exception. We have a precedent in Java history when ThreadDeath is an Error not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an Error than ThreadDeath! But it is not.
Check for 'No data' only if business logic implies it.
public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
if (personId == null)
return;
DataSource dataSource = appContext.getStuffDataSource();
Person person = dataSource.getPersonById(personId);
if (person != null) {
person.setPhoneNumber(phoneNumber);
dataSource.updatePerson(person);
} else {
Person = new Person(personId);
person.setPhoneNumber(phoneNumber);
dataSource.insertPerson(person);
}
}
and
public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
if (personId == null)
return;
DataSource dataSource = appContext.getStuffDataSource();
Person person = dataSource.getPersonById(personId);
if (person == null)
throw new SomeReasonableUserException("What are you thinking about ???");
person.setPhoneNumber(phoneNumber);
dataSource.updatePerson(person);
}
If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by Thread.defaultUncaughtExceptionHandler (for you to define and use your favorite logger or other notification mechanizm). If not set, ThreadGroup#uncaughtException will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.
Java 7 has a new java.util.Objects utility class on which there is a requireNonNull() method. All this does is throw a NullPointerException if its argument is null, but it cleans up the code a bit. Example:
Objects.requireNonNull(someObject);
someObject.doCalc();
The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:
Parent(Child child) {
if (child == null) {
throw new NullPointerException("child");
}
this.child = child;
}
becomes
Parent(Child child) {
this.child = Objects.requireNonNull(child, "child");
}
Ultimately, the only way to completely solve this problem is by using a different programming language:
In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
In Nice, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.
Common "problem" in Java indeed.
First, my thoughts on this:
I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..
So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).
The way I solve this problem is this:
First, I follow this convention:
All public methods / API always check its arguments for null
All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...
And finally, in the code, the first line of the public method goes like this:
ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();
Note that addParam() returns self, so that you can add more parameters to check.
Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).
void validate() throws ValidationException;
The message will contain the following text if, for example, "plans" is null:
"Illegal argument value null is encountered for parameter [plans]"
As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).
And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.
This way, the code is clean, easy maintainable and readable.
Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.
My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.
Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.
In addition to using assert you can use the following:
if (someobject == null) {
// Handle null here then move on.
}
This is slightly better than:
if (someobject != null) {
.....
.....
.....
}
Just don't ever use null. Don't allow it.
In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).
Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!
This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.
class C {
private final MyType mustBeSet;
public C(MyType mything) {
mustBeSet=Contract.notNull(mything);
}
private String name = "<unknown>";
public void setName(String s) {
name = Contract.notNull(s);
}
}
class Contract {
public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}
The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.
Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.
As explained in the wiki:
Optional<T> is a way of replacing a nullable T reference with a
non-null value. An Optional may either contain a non-null T reference
(in which case we say the reference is "present"), or it may contain
nothing (in which case we say the reference is "absent"). It is never
said to "contain null."
Usage:
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.
Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.
In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.
WRAPPING TO OPTION<T>
Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively
public Optional<Service> getRefrigertorControl() {
Service s = new RefrigeratorService();
//...
return Optional.ofNullable(s);
}
As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of(). One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.
SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?
Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.
Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);
Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.
#FunctionalInterface
public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.
It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.
We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:
public static Optional<HomeServices> get() {
service = Optional.of(service.orElse(new HomeServices()));
return service;
}
Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.
Finally, here is our NPE as well as null check-free code:
import java.util.Optional;
public class HomeServices {
private static final int NOW = 0;
private static Optional<HomeServices> service;
public static Optional<HomeServices> get() {
service = Optional.of(service.orElse(new HomeServices()));
return service;
}
public Optional<Service> getRefrigertorControl() {
Service s = new RefrigeratorService();
//...
return Optional.ofNullable(s);
}
public static void main(String[] args) {
/* Get Home Services handle */
Optional<HomeServices> homeServices = HomeServices.get();
if(homeServices != null) {
Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
refrigertorControl.ifPresent(HomeServices::switchItOn);
}
}
public static void switchItOn(Service s){
//...
}
}
The complete post is NPE as well as Null check-free code … Really?.
I like articles from Nat Pryce. Here are the links:
Avoiding Nulls with Polymorphic Dispatch
Avoiding Nulls with "Tell, Don't Ask" Style
In the articles there is also a link to a Git repository for a Java Maybe Type which I find interesting, but I don't think it alone could decrease the
checking code bloat. After doing some research on the Internet, I think != null code bloat could be decreased mainly by careful design.
I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.
NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.
Now to the answer:
Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.
Of course, experience is the better way to understand and apply this suggestion.
Byte!
Probably the best alternative for Java 8 or newer is to use the Optional class.
Optional stringToUse = Optional.of("optional is there");
stringToUse.ifPresent(System.out::println);
This is especially handy for long chains of possible null values. Example:
Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
.map(f -> f.getBar())
.map(b -> b.getBaz())
.map(b -> b.getInt());
Example on how to throw exception on null:
Optional optionalCarNull = Optional.ofNullable(someNull);
optionalCarNull.orElseThrow(IllegalStateException::new);
Java 7 introduced the Objects.requireNonNull method which can be handy when something should be checked for non-nullness. Example:
String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();
May I answer it more generally!
We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...
So there is no difference between:
if(object == null){
//you called my method badly!
}
or
if(str.length() == 0){
//you called my method badly again!
}
They both want to make sure that we received valid parameters, before we do any other functions.
As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.
To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.
Just a sample:
getCustomerAccounts(#NotEmpty String customerId,#Size(min = 1) String accountType)
Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.
You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)
public class Car {
#NotNull
private String manufacturer;
#NotNull
#Size(min = 2, max = 14)
private String licensePlate;
#Min(2)
private int seatCount;
// ...
}
I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.
In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.
Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.
Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?
It's worth considering such cases in order to avoid absurd results.
Never initialise variables to null.
If (1) is not possible, initialise all collections and arrays to empty collections/arrays.
Doing this in your own code and you can avoid != null checks.
Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.
// Bad
ArrayList<String> lemmings;
String[] names;
void checkLemmings() {
if (lemmings != null) for(lemming: lemmings) {
// do something
}
}
// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};
void checkLemmings() {
for(lemming: lemmings) {
// do something
}
}
There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.
This is the most common error occurred for most of the developers.
We have number of ways to handle this.
Approach 1:
org.apache.commons.lang.Validate //using apache framework
notNull(Object object, String message)
Approach 2:
if(someObject!=null){ // simply checking against null
}
Approach 3:
#isNull #Nullable // using annotation based validation
Approach 4:
// by writing static method and calling it across whereever we needed to check the validation
static <T> T isNull(someObject e){
if(e == null){
throw new NullPointerException();
}
return e;
}
Java 8 has introduced a new class Optional in java.util package.
Advantages of Java 8 Optional:
1.) Null checks are not required.
2.) No more NullPointerException at run-time.
3.) We can develop clean and neat APIs.
Optional - A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
For more details find here oracle docs :-
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

Use try-catch to avoid lengthy null checking? [duplicate]

Sometimes I face I must write a piece of code like this (usually it have more nested if and more complex structure but for the example is enought)
public void printIt(Object1 a){
if (a!=null){
SubObject b= a.getB();
if (b!=null){
SubObject2 c=b.getC();
if(c!=null){
c.print();
}
}
}
}
when I dont need to know what failed and if something is null do nothing, an approach could be
public void printIt(Object1 a){
try{
a.getB().getC().print();
}catch (NullPointerException e) {
}
}
Is there something wrong in this second form like performance or other kind of issues?
The exception version (similar to chains using Groovy's safe-navigation operator ?.) makes it really easy to take the Law of Demeter (or as I call it, Demeter's Strongly-Worded Suggestion) and make it your plaything for the night.
Similarly, deeply-nested if-statements leads to difficult-to-read code, and underneath it all, the same "violation" exists, and the cyclomatic complexity of such methods is high.
public void printIt(Object1 a) {
if (null == a) {
return;
}
SubObject b = a.getB();
if (null == b) {
return;
}
SubObject2 c = b.getC();
if (null == c) {
return;
}
c.print();
}
I'd rather see LAMs (Little Auxiliary Methods) in appropriate places that encapsulate the checks and pretty much eliminate the need for the question altogether.
Yes. The second version will have terrible performance.
Don't use exceptions for normal control flow. Effective Java item 57: use exceptions only for exceptional situations.
==UPDATE==
Even ignoring performance issues (exceptions are faster than they once were, according to my benchmark, but not nearly as fast as a simple if check), it's really code-smelly to use exceptions for standard program flow like this. JVM bytecode has special optimizations it can do for null checks, even in if statements. The first code sample is vastly preferred.
public void printIt(Object1 a){
if(a==null){
throw new IllegalArgumentException("a was null, but this is not allowed here."),
}
[...]
Fail fast and fail hard. If a shoud not be null, throw an Exception. This will make your code more stable and reliable.
So if I would have to decide between your a) and your b), I would choose a). But if a mustn't be null there, you would hide an error-situation.
The wrongest part of the second version is that when a NPE happens inside the getB(), getC() it will be silently ignored. As already mentioned, exceptions are for exceptional cases.
Using exceptions is always a bad idea in terms of performance, no matter how slow the mechanism used to be and is now. Whenever an exception is thrown, the full stack will be unrolled to create the stack trace. Thus, like Lois Wasserman said, you should not rely on them for (regular) program flow but for exceptional cases.
The nested ifs aren't the definition of beauty, but will give you the ability to print additional information like 'B is null' etc.
The answer is use version A.
It is generally considered "bad design" to use Exceptions for flow control. Exceptions are for the "exceptional", especially NPEs which are totally avoidable using null checks. Further, using null checks, you can tell (ie log) which term is null (you won't know where the null is with your version B).
Note that performance is not an issue any more throwing exceptions (the stack trace for example is only built if you use it). It's a matter of clean code.
However, there are some case where using exceptions for flow control is unavoidable, for example the exceptions thrown from SimpleDateFormat.parse(), because there isn't a reasonable way to tell before making the call that your input is not parsable.
Definitely (a) but you should restructure the method to avoid nesting the if statements as mentioned in a previous answer. Exceptions are not the performance hit they once were but are still much slower than checking for null and should never be used for program flow control like this. If an object can be null you should check for it but if it is not allowed you should fail fast at the point you assign the object reference. In many circumstances you can have default implementations (empty list is a good example) to avoid nulls altogether which results in much cleaner code. Avoid nulls whenever you can.
Using Java 8 optional:
Optional.ofNullable(a)
.map(Object1::getB)
.map(SubObject::getC)
.ifPresent(Object2::print);
If you migrate to Java 8 you can use Optional and Lambdas. First, you need to rewrite your classes to return Optional of each type:
class Object1 {
private SubObject b;
Optional<SubObject> getB() {
return Optional.ofNullable(b);
}
}
class SubObject {
private SubObject2 c;
Optional<SubObject2> getC() {
return Optional.ofNullable(c);
}
}
class SubObject2 {
#Override
public String toString() {
return "to be printed";
}
}
Now, you can chain the calls without the risk of NullPointerExceptions in a concise way:
a.getB()
.flatMap(SubObject::getC)
.ifPresent(System.out::println);
See the Oracle's article Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional! for more information.
A code should never include exception handlers for unchecked exceptions. A null check should always be used for an object reference which has a chance of being null.

What does the Java assert keyword do, and when should it be used?

What are some real life examples to understand the key role of assertions?
Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default.
An example:
public Foo acquireFoo(int id) {
Foo result = null;
if (id > 50) {
result = fooService.read(id);
} else {
result = new Foo(id);
}
assert result != null;
return result;
}
Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).
Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.
This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:
// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
return a + b;
}
While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:
// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
final int result = a + b;
assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
return result;
}
Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.
Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.
This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.
Assertions are a development-phase tool to catch bugs in your code. They're designed to be easily removed, so they won't exist in production code. So assertions are not part of the "solution" that you deliver to the customer. They're internal checks to make sure that the assumptions you're making are correct. The most common example is to test for null. Many methods are written like this:
void doSomething(Widget widget) {
if (widget != null) {
widget.someMethod(); // ...
... // do more stuff with this widget
}
}
Very often in a method like this, the widget should simply never be null. So if it's null, there's a bug in your code somewhere that you need to track down. But the code above will never tell you this. So in a well-intentioned effort to write "safe" code, you're also hiding a bug. It's much better to write code like this:
/**
* #param Widget widget Should never be null
*/
void doSomething(Widget widget) {
assert widget != null;
widget.someMethod(); // ...
... // do more stuff with this widget
}
This way, you will be sure to catch this bug early. (It's also useful to specify in the contract that this parameter should never be null.) Be sure to turn assertions on when you test your code during development. (And persuading your colleagues to do this, too is often difficult, which I find very annoying.)
Now, some of your colleagues will object to this code, arguing that you should still put in the null check to prevent an exception in production. In that case, the assertion is still useful. You can write it like this:
void doSomething(Widget widget) {
assert widget != null;
if (widget != null) {
widget.someMethod(); // ...
... // do more stuff with this widget
}
}
This way, your colleagues will be happy that the null check is there for production code, but during development, you're no longer hiding the bug when widget is null.
Here's a real-world example: I once wrote a method that compared two arbitrary values for equality, where either value could be null:
/**
* Compare two values using equals(), after checking for null.
* #param thisValue (may be null)
* #param otherValue (may be null)
* #return True if they are both null or if equals() returns true
*/
public static boolean compare(final Object thisValue, final Object otherValue) {
boolean result;
if (thisValue == null) {
result = otherValue == null;
} else {
result = thisValue.equals(otherValue);
}
return result;
}
This code delegates the work of the equals() method in the case where thisValue is not null. But it assumes the equals() method correctly fulfills the contract of equals() by properly handling a null parameter.
A colleague objected to my code, telling me that many of our classes have buggy equals() methods that don't test for null, so I should put that check into this method. It's debatable if this is wise, or if we should force the error, so we can spot it and fix it, but I deferred to my colleague and put in a null check, which I've marked with a comment:
public static boolean compare(final Object thisValue, final Object otherValue) {
boolean result;
if (thisValue == null) {
result = otherValue == null;
} else {
result = otherValue != null && thisValue.equals(otherValue); // questionable null check
}
return result;
}
The additional check here, other != null, is only necessary if the equals() method fails to check for null as required by its contract.
Rather than engage in a fruitless debate with my colleague about the wisdom of letting the buggy code stay in our code base, I simply put two assertions in the code. These assertions will let me know, during the development phase, if one of our classes fails to implement equals() properly, so I can fix it:
public static boolean compare(final Object thisValue, final Object otherValue) {
boolean result;
if (thisValue == null) {
result = otherValue == null;
assert otherValue == null || otherValue.equals(null) == false;
} else {
result = otherValue != null && thisValue.equals(otherValue);
assert thisValue.equals(null) == false;
}
return result;
}
The important points to keep in mind are these:
Assertions are development-phase tools only.
The point of an assertion is to let you know if there's a bug, not just in your code, but in your code base. (The assertions here will actually flag bugs in other classes.)
Even if my colleague was confident that our classes were properly written, the assertions here would still be useful. New classes will be added that might fail to test for null, and this method can flag those bugs for us.
In development, you should always turn assertions on, even if the code you've written doesn't use assertions. My IDE is set to always do this by default for any new executable.
The assertions don't change the behavior of the code in production, so my colleague is happy that the null check is there, and that this method will execute properly even if the equals() method is buggy. I'm happy because I will catch any buggy equals() method in development.
Also, you should test your assertion policy by putting in a temporary assertion that will fail, so you can be certain that you are notified, either through the log file or a stack trace in the output stream.
When should Assert be used?
A lot of good answers explaining what the assert keyword does, but few answering the real question, "when should the assert keyword be used in real life?" The answer:
Almost never
Assertions, as a concept, are wonderful. Good code has lots of if (...) throw ... statements (and their relatives like Objects.requireNonNull and Math.addExact). However, certain design decisions have greatly limited the utility of the assert keyword itself.
The driving idea behind the assert keyword is premature optimization, and the main feature is being able to easily turn off all checks. In fact, the assert checks are turned off by default.
However, it is critically important that invariant checks continue to be done in production. This is because perfect test coverage is impossible, and all production code will have bugs which assertions should help to diagnose and mitigate.
Therefore, the use of if (...) throw ... should be preferred, just as it is required for checking parameter values of public methods and for throwing IllegalArgumentException.
Occasionally, one might be tempted to write an invariant check that does take an undesirably long time to process (and is called often enough for it to matter). However, such checks will slow down testing which is also undesirable. Such time-consuming checks are usually written as unit tests. Nevertheless, it may sometimes make sense to use assert for this reason.
Do not use assert simply because it is cleaner and prettier than if (...) throw ... (and I say that with great pain, because I like clean and pretty). If you just cannot help yourself, and can control how your application is launched, then feel free to use assert but always enable assertions in production. Admittedly, this is what I tend to do. I am pushing for a lombok annotation that will cause assert to act more like if (...) throw .... Vote for it here.
(Rant: the JVM devs were a bunch of awful, prematurely optimizing coders. That is why you hear about so many security issues in the Java plugin and JVM. They refused to include basic checks and assertions in production code, and we are continuing to pay the price.)
Here's the most common use case. Suppose you're switching on an enum value:
switch (fruit) {
case apple:
// do something
break;
case pear:
// do something
break;
case banana:
// do something
break;
}
As long as you handle every case, you're fine. But someday, somebody will add fig to your enum and forget to add it to your switch statement. This produces a bug that may get tricky to catch, because the effects won't be felt until after you've left the switch statement. But if you write your switch like this, you can catch it immediately:
switch (fruit) {
case apple:
// do something
break;
case pear:
// do something
break;
case banana:
// do something
break;
default:
assert false : "Missing enum value: " + fruit;
}
Assertions are used to check post-conditions and "should never fail" pre-conditions. Correct code should never fail an assertion; when they trigger, they should indicate a bug (hopefully at a place that is close to where the actual locus of the problem is).
An example of an assertion might be to check that a particular group of methods is called in the right order (e.g., that hasNext() is called before next() in an Iterator).
What does the assert keyword in Java do?
Let's look at the compiled bytecode.
We will conclude that:
public class Assert {
public static void main(String[] args) {
assert System.currentTimeMillis() == 0L;
}
}
generates almost the exact same bytecode as:
public class Assert {
static final boolean $assertionsDisabled =
!Assert.class.desiredAssertionStatus();
public static void main(String[] args) {
if (!$assertionsDisabled) {
if (System.currentTimeMillis() != 0L) {
throw new AssertionError();
}
}
}
}
where Assert.class.desiredAssertionStatus() is true when -ea is passed on the command line, and false otherwise.
We use System.currentTimeMillis() to ensure that it won't get optimized away (assert true; did).
The synthetic field is generated so that Java only needs to call Assert.class.desiredAssertionStatus() once at load time, and it then caches the result there. See also: What is the meaning of "static synthetic"?
We can verify that with:
javac Assert.java
javap -c -constants -private -verbose Assert.class
With Oracle JDK 1.8.0_45, a synthetic static field was generated (see also: What is the meaning of "static synthetic"?):
static final boolean $assertionsDisabled;
descriptor: Z
flags: ACC_STATIC, ACC_FINAL, ACC_SYNTHETIC
together with a static initializer:
0: ldc #6 // class Assert
2: invokevirtual #7 // Method java/lang Class.desiredAssertionStatus:()Z
5: ifne 12
8: iconst_1
9: goto 13
12: iconst_0
13: putstatic #2 // Field $assertionsDisabled:Z
16: return
and the main method is:
0: getstatic #2 // Field $assertionsDisabled:Z
3: ifne 22
6: invokestatic #3 // Method java/lang/System.currentTimeMillis:()J
9: lconst_0
10: lcmp
11: ifeq 22
14: new #4 // class java/lang/AssertionError
17: dup
18: invokespecial #5 // Method java/lang/AssertionError."<init>":()V
21: athrow
22: return
We conclude that:
there is no bytecode level support for assert: it is a Java language concept
assert could be emulated pretty well with system properties -Pcom.me.assert=true to replace -ea on the command line, and a throw new AssertionError().
An assertion allows for detecting defects in the code. You can turn on assertions for testing and debugging while leaving them off when your program is in production.
Why assert something when you know it is true? It is only true when everything is working properly. If the program has a defect, it might not actually be true. Detecting this earlier in the process lets you know something is wrong.
An assert statement contains this statement along with an optional String message.
The syntax for an assert statement has two forms:
assert boolean_expression;
assert boolean_expression: error_message;
Here are some basic rules which govern where assertions should be used and where they should not be used. Assertions should be used for:
Validating input parameters of a private method. NOT for public methods. public methods should throw regular exceptions when passed bad parameters.
Anywhere in the program to ensure the validity of a fact which is almost certainly true.
For example, if you are sure that it will only be either 1 or 2, you can use an assertion like this:
...
if (i == 1)    {
...
}
else if (i == 2)    {
...
} else {
assert false : "cannot happen. i is " + i;
}
...
Validating post conditions at the end of any method. This means, after executing the business logic, you can use assertions to ensure that the internal state of your variables or results is consistent with what you expect. For example, a method that opens a socket or a file can use an assertion at the end to ensure that the socket or the file is indeed opened.
Assertions should not be used for:
Validating input parameters of a public method. Since assertions may not always be executed, the regular exception mechanism should be used.
Validating constraints on something that is input by the user. Same as above.
Should not be used for side effects.
For example this is not a proper use because here the assertion is used for its side effect of calling of the doSomething() method.
public boolean doSomething() {
...    
}
public void someMethod() {       
assert doSomething();
}
The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code:   
boolean enabled = false;    
assert enabled = true;    
if (enabled) {
System.out.println("Assertions are enabled");
} else {
System.out.println("Assertions are disabled");
}
A real world example, from a Stack-class (from Assertion in Java Articles)
public int pop() {
// precondition
assert !isEmpty() : "Stack is empty";
return stack[--num];
}
In addition to all the great answers provided here, the official Java SE 7 programming guide has a pretty concise manual on using assert; with several spot-on examples of when it's a good (and, importantly, bad) idea to use assertions, and how it's different from throwing exceptions.
Link
Assert is very useful when developing. You use it when something just cannot happen if your code is working correctly. It's easy to use, and can stay in the code for ever, because it will be turned off in real life.
If there is any chance that the condition can occur in real life, then you must handle it.
I love it, but don't know how to turn it on in Eclipse/Android/ADT . It seems to be off even when debugging. (There is a thread on this, but it refers to the 'Java vm', which does not appear in the ADT Run Configuration).
Here's an assertion I wrote in a server for a Hibernate/SQL project. An entity bean had two effectively-boolean properties, called isActive and isDefault. Each could have a value of "Y" or "N" or null, which was treated as "N". We want to make sure the browser client is limited to these three values. So, in my setters for these two properties, I added this assertion:
assert new HashSet<String>(Arrays.asList("Y", "N", null)).contains(value) : value;
Notice the following.
This assertion is for the development phase only. If the client sends a bad value, we will catch that early and fix it, long before we reach production. Assertions are for defects that you can catch early.
This assertion is slow and inefficient. That's okay. Assertions are free to be slow. We don't care because they're development-only tools. This won't slow down the production code because assertions will be disabled. (There's some disagreement on this point, which I'll get to later.) This leads to my next point.
This assertion has no side effects. I could have tested my value against an unmodifiable static final Set, but that set would have stayed around in production, where it would never get used.
This assertion exists to verify the proper operation of the client. So by the time we reach production, we will be sure that the client is operating properly, so we can safely turn the assertion off.
Some people ask this: If the assertion isn't needed in production, why not just take them out when you're done? Because you'll still need them when you start working on the next version.
Some people have argued that you should never use assertions, because you can never be sure that all the bugs are gone, so you need to keep them around even in production. And so there's no point in using the assert statement, since the only advantage to asserts is that you can turn them off. Hence, according to this thinking, you should (almost) never use asserts. I disagree. It's certainly true that if a test belongs in production, you should not use an assert. But this test does not belong in production. This one is for catching a bug that's not likely to ever reach production, so it may safely be turned off when you're done.
BTW, I could have written it like this:
assert value == null || value.equals("Y") || value.equals("N") : value;
This is fine for only three values, but if the number of possible values gets bigger, the HashSet version becomes more convenient. I chose the HashSet version to make my point about efficiency.
Assertions are checks which may get switched off. They're rarely used. Why?
They must not be used for checking public method arguments as you have no control over them.
They should not be used for simple checks like result != null as such checks are very fast and there's hardly anything to save.
So, what's left? Expensive checks for conditions really expected to be true. A good example would be the invariants of a data structure like RB-tree. Actually, in ConcurrentHashMap of JDK8, there are a few such meaningful asserts for the TreeNodes.
You really don't want to switch them on in production as they could easily dominate the run time.
You may want to switch them on or off during tests.
You definitely want to switch them on when working on the code.
Sometimes, the check is not really expensive, but at the same time, you're pretty sure, it'll pass. In my code, there's e.g.,
assert Sets.newHashSet(userIds).size() == userIds.size();
where I'm pretty sure that the list I just created has unique elements, but I wanted to document and double check it.
To recap (and this is true of many languages not just Java):
"assert" is primarily used as a debugging aid by software developers during the debugging process. Assert-messages should never appear. Many languages provide a compile-time option that will cause all "asserts" to be ignored, for use in generating "production" code.
"exceptions" are a handy way to handle all kinds of error conditions, whether or not they represent logic errors, because, if you run into an error-condition such that you cannot continue, you can simply "throw them up into the air," from wherever you are, expecting someone else out there to be ready to "catch" them. Control is transferred in one step, straight from the code that threw the exception, straight to the catcher's mitt. (And the catcher can see the complete backtrace of calls that had taken place.)
Furthermore, callers of that subroutine don't have to check to see if the subroutine succeeded: "if we're here now, it must have succeeded, because otherwise it would have thrown an exception and we wouldn't be here now!" This simple strategy makes code-design and debugging much, much easier.
Exceptions conveniently allow fatal-error conditions to be what they are: "exceptions to the rule." And, for them to be handled by a code-path that is also "an exception to the rule ... "fly ball!"
Here's another example. I wrote a method that finds the median of the values in two sorted arrays. The method assumes the arrays are already sorted. For performance reasons, it should NOT sort the arrays first, or even check to ensure they're sorted. However, it's a serious bug to call this method with unsorted data, and we want those bugs to get caught early, in the development phase. So here's how I handled those seemingly conflicting goals:
public static int medianOf(int[] a, int[] b) {
assert assertionOnlyIsSorted(a); // Assertion is order n
assert assertionOnlyIsSorted(b);
... // rest of implementation goes here. Algorithm is order log(n)
}
public static boolean assertionOnlyIsSorted(int[] array) {
for (int i=1; i<array.length; ++i) {
if (array[i] < array[i-1]) {
return false;
}
return true;
}
}
This way, the test, which is slow, is only performed during the development phase, where speed is less important than catching bugs. You want the medianOf() method to have log(n) performance, but the "is sorted" test is order n. So I put it inside an assertion, to limit its use to the development phase, and I give it a name that makes it clear it's not suitable for production.
This way I have the best of both worlds. In development, I know that any method that calls this incorrectly will get caught and fixed. And I know that the slow test to do so won't affect performance in production. (It's also a good illustration of why you want to leave assertions off in production, but turn them on in development.)
Assertion are basically used to debug the application or it is used in replacement of exception handling for some application to check the validity of an application.
Assertion works at run time. A simple example, that can explain the whole concept very simply, is herein - What does the assert keyword do in Java? (WikiAnswers).
Assertions are disabled by default. To enable them we must run the program with -ea options (granularity can be varied). For example, java -ea AssertionsDemo.
There are two formats for using assertions:
Simple: eg. assert 1==2; // This will raise an AssertionError.
Better: assert 1==2: "no way.. 1 is not equal to 2";
This will raise an AssertionError with the message given displayed too and is thus better. Although the actual syntax is assert expr1:expr2 where expr2 can be any expression returning a value, I have used it more often just to print a message.
I don’t know what the history is behind this feature in Java. But I have an idea about what assert can be used for that I don’t think has been brought up in this thread.
Say you have an enum which you switch on:(†)
public enum Veggie {
CAULIFLOWER,
CARROT,
}
// Another class
switch (veggie) {
case CAULIFLOWER: value = 5;
case CARROT: value = 3;
}
†: Maybe good Java compilers/tooling will catch missing enum values statically. In that case just imagine that you find some bug and you fix it. Then you can add a regression test in the code proper using the technique described below.
There’s no good default case for this. So you really want to make sure that you cover all values. You want to make sure that you update the switch block whenever you add a new enum variant:
public enum Veggie {
CAULIFLOWER,
CARROT,
TOMATO,
}
But it turns out that this code is called right when the user loads a particular view in your web application. And the view can persist in spite of this error: it would be a bug but it’s not worth interfering with the loading of the view (let’s say that the user is just presented with a few wrong numbers). So you just log a warning:
switch (veggie) {
case CAULIFLOWER: value = 5;
case CARROT: value = 3;
default: nonExhaustiveMatchOnEnum();
// […]
public static void nonExhaustiveMatchOnEnum() {
String errorMessage: "Missing veggie";
logger.warn(errorMessage);
}
But you do want this fail immediately when you are developing the code—you the developer can fix such a bug in five minutes, unlike the users of your web application.
So you can just add an assert false:
public static void nonExhaustiveMatchOnEnum() {
String errorMessage: "Missing veggie";
assert false : errorMessage;
logger.warn(errorMessage);
}
Now the app will crash locally but only log a warning on production (assuming you use java -ea locally but not in production).
Basically, "assert true" will pass and "assert false" will fail. Let's looks at how this will work:
public static void main(String[] args)
{
String s1 = "Hello";
assert checkInteger(s1);
}
private static boolean checkInteger(String s)
{
try {
Integer.parseInt(s);
return true;
}
catch(Exception e)
{
return false;
}
}
assert is a keyword. It was introduced in JDK 1.4. The are two types of asserts
Very simple assert statements
Simple assert statements.
By default all assert statements will not be executed. If an assert statement receives false, then it will automatically raise an assertion error.

Simple, general-interest, code-analyzers based, Java questions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
OK, after reviewing some code with PMD and FindBugs code analyzers, i was able to do great changes on the reviewed code. However, there are some things i don't know how to fix. I'll iterate them bellow, and (for better reference) i will give each question a number. Feel free to answer to any/all of them. Thanks for your patience.
1. Even tough i have removed some of the rules, the associated warnings are still there, after re-evaluate the code. Any idea why?
2. Please look at the declarations :
private Combo comboAdress;
private ProgressBar pBar;
and the references to objects by getters and setters :
private final Combo getComboAdress() {
return this.comboAdress;
}
private final void setComboAdress(final Combo comboAdress) {
this.comboAdress = comboAdress;
}
private final ProgressBar getpBar() {
return this.pBar;
}
private final void setpBar(final ProgressBar pBar) {
this.pBar = pBar;
}
Now, i wonder why the first declaration don't give me any warning on PMD, while the second gives me the following warning :
Found non-transient, non-static member. Please mark as transient or provide accessors.
More details on that warning here.
3. Here is another warning, also given by PMD :
A method should have only one exit point, and that should be the last statement in the method
More details on that warning here.
Now, i agree with that, but what if i write something like this :
public void actionPerformedOnModifyComboLocations() {
if (getMainTree().isFocusControl()) {
return;
}
....//do stuffs, based on the initial test
}
I tend to agree with the rule, but if performance of the code suggest multiple exit points, what should i do?
4. PMD gives me this :
Found 'DD'-anomaly for variable 'start_page' (lines '319'-'322').
when i declare something like :
String start_page = null;
I get rid of this info (level of warning is info) if i remove the assignment to null, but..i got an error from IDE, saying that the variable could be uninitialized, at some point later in the code. So, i am kind of stuck with that. Supressing the warning is the best you can do?
5. PMD Warning :
Assigning an Object to null is a code smell. Consider refactoring.
This is the case of a singletone use of GUI components or the case of a method who returns complex objects. Assigning the result to null in the catch() section it's justified by the need to avoid the return of an incomplete/inconsistent object. Yes, NullObject should be used, but there are cases where i don't want to do that. Should i supress that warning then?
6. FindBugs warning #1:
Write to static field MyClass.instance from instance method MyClass.handleEvent(Event)
in the method
#Override
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Dispose: {
if (e.widget == getComposite()) {
MyClass.instance = null;
}
break;
}
}
}
of the static variable
private static MyClass instance = null;
The variable allows me to test whether the form is already created and visible or not, and i need to force the re-creation of the form, in some cases. I see no other alternative here. Any insights? (MyClass implements Listener, hence the overrided handleEvent() method).
7. FindBugs warning #2:
Class MyClass2 has a circular dependency with other classes
This warning is displayed based on simple imports of other classes. Do i need to refactor those imports to make this warning go away? Or the problem relies in MyClass2?
OK, enough said for now..expect an update, based on more findings and/or your answers. Thanks.
Here are my answers to some of your questions:
Question number 2:
I think you're not capitalizing the properties properly. The methods should be called getPBar and setPBar.
String pBar;
void setPBar(String str) {...}
String getPBar() { return pBar};
The JavaBeans specification states that:
For readable properties there will be a getter method to read the property value. For writable properties there will be a setter method to allow the property value to be updated. [...] Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods. Thus if the argument name is "fred", it will assume that the reader method is "getFred" and the writer method is "setFred". Note that the property name should start with a lower case character, which will be capitalized in the method names.
Question number 3:
I agree with the suggestion of the software you're using. For readability, only one exit point is better. For efficiency, using 'return;' might be better. My guess is that the compiler is smart enough to always pick the efficient alternative and I'll bet that the bytecode would be the same in both cases.
FURTHER EMPIRICAL INFORMATION
I did some tests and found out that the java compiler I'm using (javac 1.5.0_19 on Mac OS X 10.4) is not applying the optimization I expected.
I used the following class to test:
public abstract class Test{
public int singleReturn(){
int ret = 0;
if (cond1())
ret = 1;
else if (cond2())
ret = 2;
else if (cond3())
ret = 3;
return ret;
}
public int multReturn(){
if (cond1()) return 1;
else if (cond2()) return 2;
else if (cond3()) return 3;
else return 0;
}
protected abstract boolean cond1();
protected abstract boolean cond2();
protected abstract boolean cond3();
}
Then, I analyzed the bytecode and found that for multReturn() there are several 'ireturn' statements, while there is only one for singleReturn(). Moreover, the bytecode of singleReturn() also includes several goto to the return statement.
I tested both methods with very simple implementations of cond1, cond2 and cond3. I made sure that the three conditions where equally provable. I found out a consistent difference in time of 3% to 6%, in favor of multReturn(). In this case, since the operations are very simple, the impact of the multiple return is quite noticeable.
Then I tested both methods using a more complicated implementation of cond1, cond2 and cond3, in order to make the impact of the different return less evident. I was shocked by the result! Now multReturn() is consistently slower than singleReturn() (between 2% and 3%). I don't know what is causing this difference because the rest of the code should be equal.
I think these unexpected results are caused by the JIT compiler of the JVM.
Anyway, I stand by my initial intuition: the compiler (or the JIT) can optimize these kind of things and this frees the developer to focus on writing code that is easily readable and maintainable.
Question number 6:
You could call a class method from your instance method and leave that static method alter the class variable.
Then, your code look similar to the following:
public static void clearInstance() {
instance = null;
}
#Override
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Dispose: {
if (e.widget == getComposite()) {
MyClass.clearInstance();
}
break;
}
}
}
This would cause the warning you described in 5, but there has to be some compromise, and in this case it's just a smell, not an error.
Question number 7:
This is simply a smell of a possible problem. It's not necessarily bad or wrong, and you cannot be sure just by using this tool.
If you've got a real problem, like dependencies between constructors, testing should show it.
A different, but related, problem are circular dependencies between jars: while classes with circular dependencies can be compiled, circular dependencies between jars cannot be handled in the JVM because of the way class loaders work.
I have no idea. It seems likely that whatever you did do, it was not what you were attempting to do!
Perhaps the declarations appear in a Serializable class but that the type (e.g. ComboProgress are not themselves serializable). If this is UI code, then that seems very likely. I would merely comment the class to indicate that it should not be serialized.
This is a valid warning. You can refactor your code thus:
public void actionPerformedOnModifyComboLocations() {
if (!getMainTree().isFocusControl()) {
....//do stuffs, based on the initial test
}
}
This is why I can't stand static analysis tools. A null assignment obviously leaves you open to NullPointerExceptions later. However, there are plenty of places where this is simply unavoidable (e.g. using try catch finally to do resource cleanup using a Closeable)
This also seems like a valid warning and your use of static access would probably be considered a code smell by most developers. Consider refactoring via using dependency-injection to inject the resource-tracker into the classes where you use the static at the moment.
If your class has unused imports then these should be removed. This might make the warnings disappear. On the other hand, if the imports are required, you may have a genuine circular dependency, which is something like this:
class A {
private B b;
}
class B {
private A a;
}
This is usually a confusing state of affairs and leaves you open to an initialization problem. For example, you may accidentally add some code in the initialization of A that requires its B instance to be initialized. If you add similar code into B, then the circular dependency would mean that your code was actually broken (i.e. you couldn't construct either an A or a B.
Again an illustration of why I really don't like static analysis tools - they usually just provide you with a bunch of false positives. The circular-dependent code may work perfectly well and be extremely well-documented.
For point 3, probably the majority of developers these days would say the single-return rule is simply flat wrong, and on average leads to worse code. Others see that it a written-down rule, with historical credentials, some code that breaks it is hard to read, and so not following it is simply wrong.
You seem to agree with the first camp, but lack the confidence to tell the tool to turn off that rule.
The thing to remember is it is an easy rule to code in any checking tool, and some people do want it. So it is pretty much always implemented by them.
Whereas few (if any) enforce the more subjective 'guard; body; return calculation;' pattern that generally produces the easiest-to-read and simplest code.
So if you are looking at producing good code, rather than simply avoiding the worst code, that is one rule you probably do want to turn off.

Avoiding NullPointerException in Java

I use x != null to avoid NullPointerException. Is there an alternative?
if (x != null) {
// ...
}
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
Where null is a valid response in terms of the contract; and
Where it isn't a valid response.
(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)
"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.
public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.
Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the Null Object pattern:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
Compare:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
to
ParserFactory.getParser().findAction(someInput).doSomething();
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got #Nullable and #NotNull.
You can use in method and parameters, like this:
#NotNull public static String helloWorld() {
return "Hello World";
}
or
#Nullable public static String helloWorld() {
return "Hello World";
}
The second example won't compile (in IntelliJ IDEA).
When you use the first helloWorld() function in another piece of code:
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.
Using parameter
void someMethod(#NotNull someParameter) { }
if you write something like:
someMethod(null);
This won't compile.
Last example using #Nullable
#Nullable iWantToDestroyEverything() { return null; }
Doing this
iWantToDestroyEverything().something();
And you can be sure that this won't happen. :)
It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other #Nullable #NotNull implementations.
See blog post More flexible and configurable #Nullable/#NotNull annotations.
If null-values are not allowed
If your method is called externally, start with something like this:
public void method(Object object) {
if (object == null) {
throw new IllegalArgumentException("...");
}
Then, in the rest of that method, you'll know that object is not null.
If it is an internal method (not part of an API), just document that it cannot be null, and that's it.
Example:
public String getFirst3Chars(String text) {
return text.subString(0, 3);
}
However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.
If null is allowed
This really depends. If find that I often do something like this:
if (object == null) {
// something
} else {
// something else
}
So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?
It's actually rare for me to use the idiom "if (object != null && ...".
It may be easier to give you examples, if you show examples of where you typically use the idiom.
Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.
The example given by Alex Miller looks like this:
public String getPostcode(Person person) {
return person?.getAddress()?.getPostcode();
}
The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.
Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.
Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.
If undefined values are not permitted:
You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see Preferences > Java > Compiler > Errors/Warnings/Null analysis.
If undefined values are permitted:
If you want to define a new API where undefined values make sense, use the Option Pattern (may be familiar from functional languages). It has the following advantages:
It is stated explicitly in the API whether an input or output exists or not.
The compiler forces you to handle the "undefined" case.
Option is a monad, so there is no need for verbose null checking, just use map/foreach/getOrElse or a similar combinator to safely use the value (example).
Java 8 has a built-in Optional class (recommended); for earlier versions, there are library alternatives, for example Guava's Optional or FunctionalJava's Option. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.
If you have to deal with an API which might return nulls, you can't do much in Java. Xtend and Groovy have the Elvis operator ?: and the null-safe dereference operator ?., but note that this returns null in case of a null reference, so it just "defers" the proper handling of null.
Only for this situation -
Not checking if a variable is null before invoking an equals method (a string compare example below):
if ( foo.equals("bar") ) {
// ...
}
will result in a NullPointerException if foo doesn't exist.
You can avoid that if you compare your Strings like this:
if ( "bar".equals(foo) ) {
// ...
}
With Java 8 comes the new java.util.Optional class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.
They work like that:
An optional object for a given type (Fruit) is created as the return type of a method. It can be empty or contain a Fruit object:
public static Optional<Fruit> find(String name, List<Fruit> fruits) {
for (Fruit fruit : fruits) {
if (fruit.getName().equals(name)) {
return Optional.of(fruit);
}
}
return Optional.empty();
}
Now look at this code where we search a list of Fruit (fruits) for a given Fruit instance:
Optional<Fruit> found = find("lemon", fruits);
if (found.isPresent()) {
Fruit fruit = found.get();
String name = fruit.getName();
}
You can use the map() operator to perform a computation on--or extract a value from--an optional object. orElse() lets you provide a fallback for missing values.
String nameOrNull = find("lemon", fruits)
.map(f -> f.getName())
.orElse("empty-name");
Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.
In an API built from scratch using Optional whenever a return value might be empty, and returning a plain object only when it cannot be null (convention), the client code might abandon null checks on simple object return values...
Of course Optional could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.
Optional offers other convenient methods, such as orElse that allow the use of a default value, and ifPresent that works with lambda expressions.
I invite you to read this article (my main source for writing this answer) in which the NullPointerException (and in general null pointer) problematic as well as the (partial) solution brought by Optional are well explained: Java Optional Objects.
Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections
Example:
String foo;
...
if( StringUtils.isBlank( foo ) ) {
///do something
}
or (depending on what you need to check):
String foo;
...
if( StringUtils.isEmpty( foo ) ) {
///do something
}
The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.
Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)
public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
return read(new StringReader(xml), true, validationEventHandler);
}
And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)
Example on how to use this static classf from spring(org.springframework.util.Assert)
Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
If you consider an object should not be null (or it is a bug) use an assert.
If your method doesn't accept null params say it in the javadoc and use an assert.
You have to check for object != null only if you want to handle the case where the object may be null...
There is a proposal to add new annotations in Java7 to help with null / notnull params:
http://tech.puredanger.com/java7/#jsr308
I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... i.e. - it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.
Sometimes, you have methods that operate on its parameters that define a symmetric operation:
a.f(b); <-> b.f(a);
If you know b can never be null, you can just swap it. It is most useful for equals:
Instead of foo.equals("bar"); better do "bar".equals(foo);.
Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.
When the exception is thrown, examine the stack trace and work through the bug.
The Google collections framework offers a good and elegant way to achieve the null check.
There is a method in a library class like this:
static <T> T checkNotNull(T e) {
if (e == null) {
throw new NullPointerException();
}
return e;
}
And the usage is (with import static):
...
void foo(int a, Person p) {
if (checkNotNull(p).getAge() > a) {
...
}
else {
...
}
}
...
Or in your example:
checkNotNull(someobject).doCalc();
Null is not a 'problem'. It is an integral part of a complete modeling tool set. Software aims to model the complexity of the world and null bears its burden. Null indicates 'No data' or 'Unknown' in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the 'who will guard
the guardians' problem.
If you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null.
An alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user.
For an 'unknown question' give 'unknown answer'. (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.
public Photo getPhotoOfThePerson(Person person) {
if (person == null)
return null;
// Grabbing some resources or intensive calculation
// using person object anyhow.
}
Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.
getPhotoOfThePerson(me.getGirlfriend())
And it fits with new coming Java API (looking forward)
getPhotoByName(me.getGirlfriend()?.getName())
While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases
public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException
public static MyEnum parseMyEnumOrNull(String value);
And don't loathe to type <alt> + <shift> + <j> (generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.
/**
* #return photo or null
*/
or
/**
* #return photo, never null
*/
This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but NullPointerException is subclass of an Exception. Thus it is a form of Throwable that indicates conditions that a reasonable application might want to catch (javadoc)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (according to creators of Java) it is appropriate, as for me, to catch NullPointerException.
public Photo getGirlfriendPhoto() {
try {
return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());
} catch (NullPointerException e) {
return null;
}
}
Questions could arise:
Q. What if getPhotoDataSource() returns null?
A. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized to be fail-fast in case of programmer errors.
Q. Redundant code could be executed and unnecessary resources could be grabbed.
A. It could take place if getPhotoByName() would try to open a database connection, create PreparedStatement and use the person name as an SQL parameter at last. The approach for an unknown question gives an unknown answer (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.
Q. This approach has a performance penalty due to the try closure opening.
A. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (source), and many others).
PS. This approach will be as reasonable to use as the separate error-handling code from "regular" code principle is reasonable to use in some place. Consider the next example:
public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
try {
Result1 result1 = performSomeCalculation(predicate);
Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
Result3 result3 = performThirdCalculation(result2.getSomeProperty());
Result4 result4 = performLastCalculation(result3.getSomeProperty());
return result4.getSomeProperty();
} catch (NullPointerException e) {
return null;
}
}
public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
SomeValue result = null;
if (predicate != null) {
Result1 result1 = performSomeCalculation(predicate);
if (result1 != null && result1.getSomeProperty() != null) {
Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
if (result2 != null && result2.getSomeProperty() != null) {
Result3 result3 = performThirdCalculation(result2.getSomeProperty());
if (result3 != null && result3.getSomeProperty() != null) {
Result4 result4 = performLastCalculation(result3.getSomeProperty());
if (result4 != null) {
result = result4.getSomeProperty();
}
}
}
}
}
return result;
}
PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was intentionally designed by the Java creators because NPE is a subclass of Exception. We have a precedent in Java history when ThreadDeath is an Error not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an Error than ThreadDeath! But it is not.
Check for 'No data' only if business logic implies it.
public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
if (personId == null)
return;
DataSource dataSource = appContext.getStuffDataSource();
Person person = dataSource.getPersonById(personId);
if (person != null) {
person.setPhoneNumber(phoneNumber);
dataSource.updatePerson(person);
} else {
Person = new Person(personId);
person.setPhoneNumber(phoneNumber);
dataSource.insertPerson(person);
}
}
and
public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
if (personId == null)
return;
DataSource dataSource = appContext.getStuffDataSource();
Person person = dataSource.getPersonById(personId);
if (person == null)
throw new SomeReasonableUserException("What are you thinking about ???");
person.setPhoneNumber(phoneNumber);
dataSource.updatePerson(person);
}
If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by Thread.defaultUncaughtExceptionHandler (for you to define and use your favorite logger or other notification mechanizm). If not set, ThreadGroup#uncaughtException will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.
Java 7 has a new java.util.Objects utility class on which there is a requireNonNull() method. All this does is throw a NullPointerException if its argument is null, but it cleans up the code a bit. Example:
Objects.requireNonNull(someObject);
someObject.doCalc();
The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:
Parent(Child child) {
if (child == null) {
throw new NullPointerException("child");
}
this.child = child;
}
becomes
Parent(Child child) {
this.child = Objects.requireNonNull(child, "child");
}
Ultimately, the only way to completely solve this problem is by using a different programming language:
In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
In Nice, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.
Common "problem" in Java indeed.
First, my thoughts on this:
I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..
So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).
The way I solve this problem is this:
First, I follow this convention:
All public methods / API always check its arguments for null
All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...
And finally, in the code, the first line of the public method goes like this:
ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();
Note that addParam() returns self, so that you can add more parameters to check.
Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).
void validate() throws ValidationException;
The message will contain the following text if, for example, "plans" is null:
"Illegal argument value null is encountered for parameter [plans]"
As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).
And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.
This way, the code is clean, easy maintainable and readable.
Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.
My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.
Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.
In addition to using assert you can use the following:
if (someobject == null) {
// Handle null here then move on.
}
This is slightly better than:
if (someobject != null) {
.....
.....
.....
}
Just don't ever use null. Don't allow it.
In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).
Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!
This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.
class C {
private final MyType mustBeSet;
public C(MyType mything) {
mustBeSet=Contract.notNull(mything);
}
private String name = "<unknown>";
public void setName(String s) {
name = Contract.notNull(s);
}
}
class Contract {
public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}
The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.
Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.
As explained in the wiki:
Optional<T> is a way of replacing a nullable T reference with a
non-null value. An Optional may either contain a non-null T reference
(in which case we say the reference is "present"), or it may contain
nothing (in which case we say the reference is "absent"). It is never
said to "contain null."
Usage:
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.
Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.
In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.
WRAPPING TO OPTION<T>
Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively
public Optional<Service> getRefrigertorControl() {
Service s = new RefrigeratorService();
//...
return Optional.ofNullable(s);
}
As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of(). One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.
SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?
Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.
Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);
Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.
#FunctionalInterface
public interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.
It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.
We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:
public static Optional<HomeServices> get() {
service = Optional.of(service.orElse(new HomeServices()));
return service;
}
Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.
Finally, here is our NPE as well as null check-free code:
import java.util.Optional;
public class HomeServices {
private static final int NOW = 0;
private static Optional<HomeServices> service;
public static Optional<HomeServices> get() {
service = Optional.of(service.orElse(new HomeServices()));
return service;
}
public Optional<Service> getRefrigertorControl() {
Service s = new RefrigeratorService();
//...
return Optional.ofNullable(s);
}
public static void main(String[] args) {
/* Get Home Services handle */
Optional<HomeServices> homeServices = HomeServices.get();
if(homeServices != null) {
Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
refrigertorControl.ifPresent(HomeServices::switchItOn);
}
}
public static void switchItOn(Service s){
//...
}
}
The complete post is NPE as well as Null check-free code … Really?.
I like articles from Nat Pryce. Here are the links:
Avoiding Nulls with Polymorphic Dispatch
Avoiding Nulls with "Tell, Don't Ask" Style
In the articles there is also a link to a Git repository for a Java Maybe Type which I find interesting, but I don't think it alone could decrease the
checking code bloat. After doing some research on the Internet, I think != null code bloat could be decreased mainly by careful design.
I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.
NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.
Now to the answer:
Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.
Of course, experience is the better way to understand and apply this suggestion.
Byte!
Probably the best alternative for Java 8 or newer is to use the Optional class.
Optional stringToUse = Optional.of("optional is there");
stringToUse.ifPresent(System.out::println);
This is especially handy for long chains of possible null values. Example:
Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
.map(f -> f.getBar())
.map(b -> b.getBaz())
.map(b -> b.getInt());
Example on how to throw exception on null:
Optional optionalCarNull = Optional.ofNullable(someNull);
optionalCarNull.orElseThrow(IllegalStateException::new);
Java 7 introduced the Objects.requireNonNull method which can be handy when something should be checked for non-nullness. Example:
String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();
May I answer it more generally!
We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...
So there is no difference between:
if(object == null){
//you called my method badly!
}
or
if(str.length() == 0){
//you called my method badly again!
}
They both want to make sure that we received valid parameters, before we do any other functions.
As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.
To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.
Just a sample:
getCustomerAccounts(#NotEmpty String customerId,#Size(min = 1) String accountType)
Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.
You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)
public class Car {
#NotNull
private String manufacturer;
#NotNull
#Size(min = 2, max = 14)
private String licensePlate;
#Min(2)
private int seatCount;
// ...
}
I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.
In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.
Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.
Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?
It's worth considering such cases in order to avoid absurd results.
Never initialise variables to null.
If (1) is not possible, initialise all collections and arrays to empty collections/arrays.
Doing this in your own code and you can avoid != null checks.
Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.
// Bad
ArrayList<String> lemmings;
String[] names;
void checkLemmings() {
if (lemmings != null) for(lemming: lemmings) {
// do something
}
}
// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};
void checkLemmings() {
for(lemming: lemmings) {
// do something
}
}
There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.
This is the most common error occurred for most of the developers.
We have number of ways to handle this.
Approach 1:
org.apache.commons.lang.Validate //using apache framework
notNull(Object object, String message)
Approach 2:
if(someObject!=null){ // simply checking against null
}
Approach 3:
#isNull #Nullable // using annotation based validation
Approach 4:
// by writing static method and calling it across whereever we needed to check the validation
static <T> T isNull(someObject e){
if(e == null){
throw new NullPointerException();
}
return e;
}
Java 8 has introduced a new class Optional in java.util package.
Advantages of Java 8 Optional:
1.) Null checks are not required.
2.) No more NullPointerException at run-time.
3.) We can develop clean and neat APIs.
Optional - A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
For more details find here oracle docs :-
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

Categories