Tuesday, August 24, 2010

The problem with Java, or null-proof logging in Android

So this is really irritating. I keep getting exceptions in Android when my logging string happens to be null, e.g.
Log.d("DEBUG", my_string);
if my_string is null, then I get an exception and execution halts. Not what I want. I want the null nature of my_string to be reported and execution to continue.

The verbose location solution is:
if (my_string != null) {
Log.d("DEBUG", my_string);
}
or:
Log.d("DEBUG", my_string == null ? "NULL":my_string);
but really I'd like to modify the Log.d static method so that check is included by default. Something I could easily do in ruby, but no equivalent I know of in Java that doesn't involve creating some new class and then modifying all my existing calls to this method throughout my code ...