3 ms·
The traditional options are Java are: 1. Assume parameters aren't null, and then everything breaks and you fix it. 2. Assume ANY object can be null, and check
by kazagistar 11y ago
The traditional options are Java are:
1. Assume parameters aren't null, and then everything breaks and you fix it.
2. Assume ANY object can be null, and check them all, in every single method, and create correct handling in each case. Basically no one does this.
3. Try to figure out which things can be null or not depending on context. Sometimes you are still wrong, and get NPEs. This is what people actually do.
By defensive programming, do you mean #2? Because that kinda sucks compared to just using Optionals.
- quicksilver03 11y ago#1 is what most programmers do, basically fragile code that can break at any time. #2 is what I do. I'm not a great programmer, but keeping this sort of discipline means that my code has fewer trivial (and time-wasting) bugs.
- jdmichal 11y agoI do option (2) for every parameter in every non-private method in my Java code. I have a template in my IDE to write the check; all I do is invoke the template, type the variable name, and hit enter. I even document the throw in the javadoc comments. It's not hard, and it's the right thing to do.
- vvanders 11y agoYeah, even when using get() with Optional it's a great way to give semantics to the function that require you to stop for a second. Annotations don't really cut it for most IDEs/Lints.
- specialist 11y ago#1 is standard practice #2 Optionals are syntactic sugar for null checks.