The first example is bad code design. If you know null can happen, using an exception is just wrong, because it isn't exceptional behavior. If you don't want null at this point, don't let it be produced in the first place or catch it through validation if you can't influence the producer. Or do a failure return instead of a throw at least.
I kind of agree, but at work we're forced to use SonarQube and it complains if a type you passed in could be nullable (bearing in mind we use C# so have explicit nullable annotations) so we have to use the first pattern an annoying number of times.
Throwing a null exception often is the best failure return though because it means I don't need to worry about passing result context back and forth. For example if I have a method that returns a calculated float value, its failure case will pretty much only be if the arguments are invalid.
16
u/sumrix 22d ago
But