Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 5030232
Votes 33
Synopsis Add Nice Option types to Java to prevent NullPointerExceptions
Category java:specification
Reported Against 1.4.2
Release Fixed
State 11-Closed, duplicate of 6207924, request for enhancement
Priority: 5-Very Low
Related Bugs 4492260 , 6514490 , 6207924
Submit Date 12-APR-2004
Description


A DESCRIPTION OF THE REQUEST :
Nice is a Java derived language that offers language level support for prevention of NullPointerExceptions.  I propose that this support be added to the Java language.

Type safety in Nice
http://nice.sourceforge.net/safety.html#id2433011

Option types
http://nice.sourceforge.net/manual.html#optionTypes

Since this is a language change, with the potential to break much old code (as well as uncover many old bugs) it should be introduced along with a compiler flag.

JUSTIFICATION :
NullPointerExceptions are extremely common, yet often offer very little information about the real source of the problem.  While they are a runtime problem, adding the requested compiler support would often allow them to be detected and eliminated at compile time.

See:

The Dangling Composite bug pattern
http://www-106. customer .com/developerworks/library/j-diag2

The Null Flag bug pattern
http://www-106. customer .com/developerworks/library/j-diag3.html

While it is possible to use aggressive run-time checking to detect bugs earlier at run-time, this has a number of disadvantages.

- It doesn't detect bugs at compile time
- It places the burden on the programmer
- It adds to the clutter of the code
- It assumes that code will handle nulls correctly, unless the code specifies otherwise.  This assumption is usually false.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Variable declarations without the ? prefix assert that they must not be null.  Variable declarations with the ? prefix may be null.  Based on this knowledge, the compiler should produce an error for code that may produce a NullPointerException, when this feature is enabled.
ACTUAL -
There is no current compile support for this.

---------- BEGIN SOURCE ----------
	void foo(String arg) {...}
	
	void bar(?String arg) {
		if (arg != null) {
			//Here Nice knows arg is not null, so it can
			// be passed to a method which takes a String.
			foo(arg);
		}
		foo(arg); //Here arg may or may not be null,
			  //so Nice gives a compilation error.
	}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
There are some obvious work-arounds, but they all fall far short of adding this support to the language.

1) Use Nice instead of Java.  This means decreased tool support, lack of supporting vendors, etc..
2) Use a static bytecode analysis tool to detect NullPointerExceptionS.  While such a tool is possible, I am unaware of one.
3) Aggressively check for nulls in programs.  This clutters code much more than language support would.  Worse yet, it only allows problems to be detected earlier at run time, instead of at compile time.
(Incident Review ID: 249785) 
======================================================================
Posted Date : 2006-11-20 22:04:34.0
Work Around
N/A
Evaluation
Probably a good idea. JSR305 might define a standard annotation to mean 'non-null'.
Posted Date : 2006-11-20 22:04:34.0

In Nice, a type name like String is non-nullable by default, and you have to say ?String for the nullable String type. We could not possibly accept this default in Java. Since 6207924 accepts that types are nullable by default, I am making it the master request for non-nullable types.
Posted Date : 2006-12-11 13:05:48.0
Comments
  
  Include a link with my name & email   

Submitted On 27-APR-2004
keithkml
I think this would be better off as a "@NonNull" attribute
with Java 1.5's new attributes syntax. One problem with this
is that local variables can't be annotated.


Submitted On 03-MAY-2004
CurtCox
Using a "@NonNull" attribute biases code the wrong way. 
Code should be assumed to break if given nulls, unless it is
specifically coded to handle them.  Adding a "@Nullable"
attribute when appropriate would be preferable.  If a
compiler flag is available, I don't see any advantages of
using attributes over a language change.  I know a language
change is a big deal, but so are null pointer problems.


Submitted On 27-MAY-2004
kentyman
Or, since all Java code to date assumes that null is possible, we could add a qualifier to specify what cannot be null. The obvious thing that comes to mind is using C++'s & to specify a reference that always references something. So for example:

String& string = "string can never be null";


Submitted On 28-NOV-2004
chaker_nakhli
I think it is not a good idea for two reasons. First, this may lead to false-positives, especially in multithreaded programs. Second, I think that it would be difficult (impossible?) to detect all these situations in a concervative way (due to late-binding, multithreading etc.)


Submitted On 28-NOV-2004
chaker_nakhli
I think it is not a good idea for two reasons. First, this may lead to false-positives, especially in multithreaded programs. Second, I think that it would be difficult (impossible?) to detect all these situations in a concervative way (due to late-binding, multithreading etc.)


Submitted On 28-NOV-2004
chaker_nakhli
I think it is not a good idea for two reasons. First, this may lead to false-positives, especially in multithreaded programs. Second, I think that it would be difficult (impossible?) to detect all these situations in a concervative way (due to late-binding, multithreading etc.)


Submitted On 04-JAN-2005
wwk_killer
chaker_nakhli, I don


Submitted On 04-JAN-2005
wwk_killer
chaker_nakhli, I don't understand what can be your case against. How multithreading can affect compile-time analysis?

The rules of nullability propagation are simple:
1. After checks for (object != null), this conditional branch guarantees that object is @NonNull;
2. If @NonNull is not guaranteed at some point, any call with such parameter is an error, at least warning must be issued.
3. If variable assigned with some "new Object()", it is "@NonNull" until next assignment;
4. If return results of some method is @NonNull, assignment is @NonNull + code like "return null" if an error.

This will bring Developer's attention to possible NPE cases at least, that's VERY useful. 

Probably, it will help isolate code layers in complex systems: at some layer, we put all that checks and know for sure that code below is safe from NPE.

Things to consider:
1. Libraries -- will somebody enhance this? (I'd suggest to allow such commits to Open Source Community well-known people -- if they be able to handle this without serious errors);
2. Collections / arrays -- will there be a syntax for Collections / arrays that hold only @NonNulls?

One more workaround -- use /* @NonNull */ comments + separate analysis tool. 
Volunteers? 8-)


Submitted On 11-APR-2005
hlovatt
The reason that it is difficult to ensure in a multi-threaded environmant that something isn't null is that you test that it isn't null and then another thread sets it to null. Static checking or simple dynamic checking won't catch this.

You need to make a copy, test this copy, and then use the copy (assuming that it is non-null). Therefore ensuring non-null comes with a little runtime overhead.


Submitted On 11-APR-2005
hlovatt
You do not get the advantages stated in this RFE if the instance of a class is marked as not null. In particular this RFE states that code clutter would be reduced. This isn


Submitted On 11-APR-2005
hlovatt
Post got cut off for some reason :( 2nd try ...

You do not get the advantages stated in this RFE if the instance of a class is marked as not null. In particular this RFE states that code clutter would be reduced. This isn't true; if you write a class the methods in this class still need to deal with null, equals, compareTo, etc. This is because you have no control over the user of the class who can still declare a nullable instance and therefore equals, compareTo, etc. still need to deal with null.

What is needed is not the ability to mark an instance of the class as not null; but the ability to be able to mark the class itself as not null, where a class marked not null means that no instances whatsoever of this class can be null.


Submitted On 07-MAY-2005
keithkml
My project Nully at http://nully.dev.java.net allows the use of @NonNull annotations to check nullness in the Java editor, at compile time, and at run time.


Submitted On 01-FEB-2006
CurtCox
This page contains some papers that discuss related issues:
http://research.microsoft.com/~leino/papers.html


Submitted On 08-FEB-2006
remi_forax
IntelliJ IDEA support this kind of feature 
http://www.jetbrains.com/idea/documentation/howto.html

Eclipse have plan to support it
https://bugs.eclipse.org/bugs/show_bug.cgi?id=110030

and java spec ??


Submitted On 09-FEB-2006
kcpeppe
"2. If @NonNull is not guaranteed at some point, any call with such parameter is an error, at least warning must be issued."

This is where I get confused. Aside from a few trivial cases how can the compiler devine runtime behavior. Maybe it's the idea that is confused and not me?

One other point, is passing null to a method a null pointer exception or a IllegalArgumentException. This is (of course) assuming  that passing null to a method should not be allowed but I guess adding the annotion signals that intent.

looks like misguided language bloat IMHO, vote -1.


Submitted On 10-FEB-2006
zipwow
Null pointer errors are a major source of late-cycle bugs.  (bugs caught by integration/acceptance testing).  In addition, handling of the null case is an aspect of your API that cannot be specified programmatically.  

Knowing that an API may or may not return null would make for clearer APIs and better code.


Submitted On 25-APR-2006
rzwitserloot
Syntax proposal: Instead of defaulting to non-null, default to potential-null. Then you get:

String! x;  //This may not be null

then add the 'null check' operator:

private String! name;

public BackwardsCompatibleConstructor(String input) {
    this.name = input!;   //! operator: Identity UNLESS operand is null,
    //then throw NullPointerException at this point.
}

existing code will compile with no problems in this scheme, the compiler always knows the meaning of exclamation marks (boolean inverse is prefix, this is postfix), I think it's quite readable, and interoperating with older code is a breeze. Furthermore, with this mechanism, complicated branch calculations are no longer required - that is, the example in the main post showing that the compiler is supposed to 'predict' IF statements is no longer neccessary; that fragment would be replaced with some null-check operator based solution.

A warning can be emitted for superfluous null-checks (null-checking primitives or already null-safe types).


Submitted On 26-MAR-2007
verdyp
Before tring to add new syntax for references, why not creating a derived type for NonNull references? It would be enough to say that that class implements a NonNullable interface while also being derived from the normal class?
So:

public interface StringNotNull extends String implements NotNullable {...}

But... String is final and can't be subclassed (even if a null value implies no backing store)! And yes, not being able to enforce the NotNull type attribute for local variables is a problem for strict type safety.

It seems that the cleanest solution would be to use true reference types with & like in C or C++...
But then, how to enforce it without changing the binary compatility? May be by making the @NonNull annotation internally generated by the compiler, that will also create the necessary assert statement in the generated code for local variables. The compiler would then have to check this annotation at compile-time when using references to other classes, and at runtime as well with Reflection when getting Method instances...


Submitted On 03-MAY-2007
(wwk_killer writes)
To kcpeppe, hlovatt  and verdyp:

Please note this RFE relates to VARIABLES, not OBJECTS. In Java, variable is either a reference to some object, or null. Would be great to mark that certain variable is not going to be null and have compiler to help you by static code analysis. Runtime behavior is not affected -- just code won't compile unless there is mathematical (!!!) guarantee that variable will never be null.



PLEASE NOTE: JDK6 is formerly known as Project Mustang