|
|
|
|
|
by latencyloser
2674 days ago
|
|
I write Java daily, I haven't seen one in a production environment in... at least recent memory. Most common NPEs I've seen can be resolved by doing two things: 1) for returning a single, nullable value, wrap it in Optional. 2) Never return null collections, always default to an empty collection instead. More nuanced ones can often be caught by using all args constructors and requiring the constructor values with Objects.requiresNonNull() or similar. Using spring? Don't use field or setter injection, always constructor so the above applies as well. Making the state of your objects largely immutable means their state is more consistent and what is null and when becomes a lot less surprising. Lastly, write good tests. If you're exhausting the behavior of your system with tests, these things are much less likely to surprise you later. NPEs are definitely a problem with Java, but they're a very avoidable one as well. Edit: I don't understand the downvotes. The parent said they're a huge deal and I'm disagreeing because I think they're relatively simple to avoid? |
|
Most issues in software fall into this category, though. The issue with Java’s null is that it’s not type safe. The language is generally a strongly typed language, except in the case of null. And until Value Types land, there is no way to express nullability to the compiler.
The arguments you make aren’t all that different than the undefined behavior arguments with C. “Just follow these simple rules and you’ll avoid all issues”, a compiler should do that for you IMO.
I can’t wait for Value Types in Java, at that point we can have real Option types.