4 ms·
That assumes the read of the field will happen immediately after this class is instantiated. Which is, of course, not likely to be the case in real code. Which
by lostcolony 5y ago
That assumes the read of the field will happen immediately after this class is instantiated. Which is, of course, not likely to be the case in real code.
Which is why NPEs are inherently problematic. If something is null, and it's being read, it means an implicit contract violation happened -before- the read (i.e., that field should have been set somewhere), and you -have no idea where-. Better to fail fast with a cleaner message when this ErrorResponse object is created, than when the null message is attempted to be used somewhere further down the call stack and you have no idea why it's null.
Or more succinctly, "to instantly alert you to a bug and/or contract violation" is not what NPEs do. They alert you when you attempt to read a value that has not been set; they do not alert you when you failed to set a value you should have set. If you have a constructor and something should not be null in it, at least assert that it is not null so it fails fast; don't wait for it to be read who knows how much later and fail only then.
- trav4225 5y agoOh, agreed 100%. Thanks for the clarification. This is indeed what I do. I heavily enforce contracts (something some of my coworkers do not appreciate ;-). Perhaps we don't agree on everything here, though, because I still do not see any problems with the existence of NPEs. However, I do appreciate language features that allow you to enforce non-nullability at compile time if desired.