NullPointerException error - java

I am developing in Eclipse a new Java project which uses an existing application (I have added its jar in my project build path). When I create an object of a class (say Model) from this existing application and use any of its methods,
Model model = new Model();
model.start();
I get the following error:
Exception in thread "main" java.lang.NullPointerException
at main.gui.mainwindow.MainWindow.run(MainWindow.java:56)
at main.gui.ApplicationController.main(ApplicationController.java:21)
When I create only the Model object (without calling its method), no error is given and my application works perfectly, does anyone know where the problme may lie? Thanks in advance!

It sounds like there is an uninitialized value inside of your Model class and when you call start(), the class is trying to use the uninitialized value.
You might want to provide a concrete example rather than being Vague. You could be trying to use a class that has a dependency that you haven't set before trying to use some specific part of the class.
If Model (or whatever the real class may be) is something developed by somebody there, I would suggest asking them what could be going wrong or what you might be missing.

The oracle documentations says:
Thrown when an application attempts to
use null in a case where an object is
required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.
Applications should throw instances of
this class to indicate other illegal
uses of the null object.
Check if anything in here matches your case. It is impossible to say more without actually seeing the code.

Related

Null Pointer Exception in Hadoop Reduce method?

I'm building an inverted index and currently getting a null pointer exception in reduce when using context.write. Can anyone spot why? I presume something to do with serialising as I've never done that before? The error also happens when I print out h.
Two things that I can spot directly regarding the serialization without a stacktrace:
HMapValue needs a default constructor, it can't be created by Hadoop without one
In the default constructor you need to initialize the ArrayListWritable correctly (not null and it needs the setClass method to deserialize correctly.
Turns out it was because I had iterated over the data set twice (the line int df = Iterables.size(values); tricked me). The iterator hadn't reset hence the main block of reduce didnt run and finally I hit a null pointer because I tried accessing my data that hadn't even initialised.

What to do in findXY method if no such object exists?

Assume I have a Java method
public X findX(...)
which tries to find an Object of type X fulfilling some conditions (given in the parameters). Often such functions cannot guarantee to find such an object. I can think of different ways to deal with this:
One could write an public boolean existsX(...) method with the same signature which should be called first. This avoids any kind of exceptions and null handling, but probably you get some duplicate logic.
One could just return null (and explain this in javadoc). The caller has to handle it.
One could throw a checked exception (which one would fit for this?).
What would you suggest?
The new Java 8 Optional class was made for this purpose.
If the object exists then you return Optional.of(x) where x is the object, if it doesn't then return Optional.empty(). You can check if an Optional has an object present by using the isPresent() method and you can get the object using get().
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
If you can't use Optional I would go with option 2.
In the case of 1. You'd be doing double work, first you have to check if X exists, but if it does, you're basically discarding the result, and you have to do the work again in findX. Although the result of existsX could be cached and checked first when calling findX, this would still be an extra step over just returning X.
In the case of 3. To me this comes down to usability. Sometimes you just know that findX will return a result (and if it doesn't, there is a mistake somewhere else), but with a checked exception, you would still have to write the try and (most likely empty) catch block.
So option 2 is the winner to me. It doesn't do extra work, and checking the result is optional. As long as you document the null return, there should be no problems.
Guava (potentially other libraries, too) also offers an Optional class that might be worth exploring if your project uses Guava since you seem to not use Java 8.
If you
don't/can't/won't use Java 8 and its accompanying Optional type
don't want another library dependency (like Guava) for a single class implementation
but
you want something more robust than methods that can return null for which you have to have a check in all consumers (which was the standard before Java 8)
then writing your own Optional as an util class is the easiest option.

Not throwing business exceptions, but returning value

I have the following method:
public void Foo addFoo(String name);
This methods adds Foo to some structure. In the same time, it checks if Foo by given name already exist. I can throw some FooNameConflictException, but I would not, since I don't consider this as exception - this is something that can happens, and it is part of the business flow of the application.
Instead, I would return the information if Foo by given name already exist. What is the pragmatical way to do this? What should I return in case when name already exist?
Return null - and this is pure ugly as null does not means anything and it is not extensible and... ugly.
Return Foo with some internal status that indicates that Foo is NEW or EXISTING. However, we must carefully design state change from NEW -> EXISTING, i.e. I am not sure when this would happened, and may fail in multi-threaded environments.
Make new class FooOperation or FooAdding that compose of Foo instance and additional flag(s) that brings more information about the addition process.
I may go with generic variant of #3 and have class like Either, but then you are bound to two values (left or right).
I see solution #3 as the only pragmatical in this case. Am I missing something?
By experience, in your case if the name is a key of a Foo object, I would return the Foo object related to the name if found.
Hence the user of the method will use the Foo object returned, not caring if it's a new object or already existing object. If you must know the state of the Foo object, maybe add a state attribute in it.
Personally, i'd still go for the exception but include a check if it exists in your calling code.
Thus, your normal business flow includes a check for a name conflict and appropriate reaction. Calling addFoo despite a conflict will then result in an exception being thrown.
If you wanted to, you could combine check + handling + call to addFoo in its own method and probably even let that have an effect on the visibility of addFoo (make it private or whatever works best in your case).
The typical alternative to me would be c-style: Always return a result code and let the calling code branch based on it (success, nameConflict, ...)

Best Practice: Java attributes might be null

So I have a constructor with 5 different variables, where three of which might be null. It accepts user input and the user does not have to enter anything for three of the five attributes.
Therefore, if the user did not enter anything, the object is created using null for all missing values.
obj = new Object(String, null, null, null, String);
Now I am wondering what would be best practice to cope with this.
I can think of three different scenarios:
Deal with it only in the class using the constructor, i.e. always query whether the value is null (e.g. if(getSomeAttribute == null) { //do something }
Deal with it within the object class, i.e. always return some default value for each missing attribute instead of null
Deal with it within the object lcass, i.e. have helper-methods like isAttributeSet(), returning a boolean value indicating whether the attributes are set, that is: not null.
Although I have problems with the last two, as I think I might run into problems with default values, as sometimes it might hard to know if it is a default value; if I'd always check I could just as well check for null instead of inserting a default value first;
Same with the last one, if I have to check the helper-method, I could just as well check for null directly.
What my problem is with this situation, is that sometimes I might not be the one using the getter and setter methods; how should the one using it know there might be null attributes and which that are.
I know, I should document that within my object class, but still I am wondering if there is a "best practice" way to cope with this.
I believe it should be unusual to always check the documentary (or if there is none, the whole class) for something as simple as this.
Maybe I should not even start with null values within my constructor in the first place? But I think I would run into the same kinds of problems, anyway, so that would not really solve my problem
Read Bloch, Effective Java, 2nd ed. Item 2: "Consider a builder when faced with many constructor parameters."
Excellent advice in an excellent book.
Using a builder pattern would help with the constructor, however the main problem is to do with the design of the class - you want to be sure when you call a get/set method that it isn't one of the null/optional members.
You could use polymorphism to have two objects each with an interface that only exposes the getters and setters supported by the concrete implementation. This makes it impossible to call the wrong getters/setters and it is obvious what the intention is.

IllegalArg Vs null check

If I have a class like
class A
{
Private B b;
X getX()
{
X x = b.newClient().call();
}
}
Here should I be checking if b is null ? How should this be handled ? Using exceptions (for e.g. this isnt really an argument so does throwing an illegalArgument make sense here ? or simply logging an error ?
private B b is part of your hidden, internal implementation (i.e. It's not part of the public API, used by clients of your class). So it's not a client's problem that b is null, it's your problem, as the developer of the class.
Imagine if you were trying to use some shiny new library you got off GitHub:
MagicAnythingParser parser = new MagicAnythingParser();
parser.parse(myDocument);
and the call to parse threw an exception that said "intakeManifold is null". You'd be thinking "What the hell?!"
Little did you know, that you were expected to first make a call like:
parser.setupParseRules(someRuleset);
and internally, this created some object and assigned it to intakeManifold.
A much better scenario would be, if MagicAnythingParser did a good job of tracking its internal state, and instead threw something like an IllegelStateException("No parse rules applied. You must call setupParseRules first.")
My whole point is, you should develop the public API of your classes, with the clients in mind (even if that client is you.) Try to ensure that your objects are always in a "good state" - and when you cannot, throw meaningful exceptions, that make it blindingly obvious what the problem was.
Do you have a strategy for handling the possibility of a null pointer? I.e. if the variable should NEVER be null, and therefore indicates a bug, then you might not want to hide it. I'm a fan of letting the system blow up in my face so that the fault is found quickly and the root cause determined easily.
If your code is designed to carry on anyway, for example when processing batches and you don't want one fault in a batch item to kill the whole batch, then you can log it or whatever. But otherwise just let the NPE do it's thing.
Checking if b is null in getX does not buy you much. You are trading one runtime exception for another. You really want to know why b is null.
I would recommend making b final and setting it through the constructor. Perform your null check in the constructor.

Categories

Resources