I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
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!