Re: Checking for null parameter
OK... Let me take you back to what was the meaning of this whole
discussion because I believe that the thing is going out of hand. The
discussion was about CHECKING a null reference, not HANDLING. Here is
an example:
public class ChatExample {
private Connection conn;
public ChatExample() {
// I intentionally forget to instantiate the conn
}
public void connect() throws ConnectionException {
try {
conn.connect();
} catch (ConnectionExcetpion e) {
// Delegate the exception
throw new ConnectionException("Connection failed in Chat",e);
}
}
public sendMessage(String message) throws ConnectionException {
try {
conn.sendMessage(message);
} catch (ConnectionException e) {
// Delegate the exception
throw new ConnectionException("Couldn't send message in
Chat",e);
}
}
class Connection {
public void connect() throws ConnectionException {
// Do socket connection etc. etc.
}
public void sendMessage(String message) throws ConnectionException
{
// Send the message using sockets etc. etc.
}
}
}
public class Main {
public static void Main() {
// Catch and log any exceptions that wheren't planned without
crashing
try {
startProgram();
} catch (NullPointerException e) {
// Log it and inform user
} catch (Exception e) {
// Same here (probably combining with the above exception
wouldn't have any difference
}
}
private void startProgram {
// Do anything
// At some point you want to send a message
ChatExcample chat = new ChatExample();
chat.sendMessage("Hello world");
}
}
OK, now, did you notice that I forgot to instantiate the conn
attribute? That is a bug, which means that the user can NEVER send a
message simply because it is a NPE and it will stay that way no matter
what. Notice also that I didn't try to check for it, for example, I
didn't do this:
if ( conn == null ) {
// log and inform
} else {
conn.connect();
}
Because I believe that if conn is null, it is a bug! And the program
doesn't work, so you have to fix it. You can check in main method for
NPE of any object in your program, thus avoiding checking them in
every single method.
Notice also that I didn't even check if the String message isn't null.
The same thing applies here, if it is null, that is a bug of the
developer that uses my code, so he has to fix it. I don't care for
checking a NPE. It is obvious that I need the String in order to send
the message. It is obvious in any case that a method that accepts any
object reference needs to be non-null. Otherwise I would state it in
the Javadoc (if the object is null, this method would behave like
this, otherwise like this).
So, to start from the beggining of this discussion, in my opinion,
CHECKING for NPE isn't necessary. If there is one, then that is a bug
and you have to fix it. If you want to log it you can, but you don't
need to CHECK it whether any object you are about to use is null or
not. Handling the NPE is another thing. In my example, I did handle
the NPE, but I didn't check it.