Skip to content

Comment on Deprecating: java.util.Optional.get()?parent

Comments

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.

#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.

Yeah, 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.

I 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.

#1 is standard practice

#2 Optionals are syntactic sugar for null checks.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.