r/java • • Jun 27 '16

Null pointer exceptions hell

http://dobegin.com/npe-hell/
0 Upvotes

18 comments sorted by

View all comments

-4

u/yogazook Jun 28 '16

And yet they're the easiest exceptions to avoid. It's actually pretty much programming 101: 1) don't return null, and/or 2) check to make sure it's not null before you do something that can throw an NPE.

var element = null;
element.getAttribute("id");
    // crash

Yeah, no shit.

1

u/battlmonstr Jun 28 '16

Sure. My point is that if you do something really dumb, then the compiler/parser should be able to stop you and warn you until it's too late. When you fix this bug for 1000th time it's not funny anymore. It's often not your own code.

1

u/yogazook Jun 29 '16

Better than the compiler is a good IDE, such as IntelliJ. Better than that is a decent test suite, with test methods like

public void should_not_blow_up_if_x_is_null(){
}

1

u/battlmonstr Jun 29 '16

Unit testing is a possible approach, but I don't quite see how it's better than a simple "if (x != null)" check (you need it anyway probably). When adding such a test you need to think about it yourself upfront. This test certainly reassures that it's not null, and helps with regressions. You could also add assertions/preconditions for that matter.

IntelliJ is great, I use it all the time, but in its core it is only as good as the language itself (maybe a little bit better).

1

u/QshelTier Jun 30 '16

Checking for null is okay (well, not really, it sucks) but having a compiler that refuses to create a binary if you forget it is better.