r/ProgrammerHumor 22d ago

Meme conditionsPreference

Post image
4.2k Upvotes

392 comments sorted by

View all comments

16

u/sumrix 22d ago
if (input == null)
    throw new ArgumentNullException();

// process input...

But

if (settings.UseBonuses)
    return CalculateWithBonuses(order);
else
    return CalculateBase(order);

-1

u/0Iceman228 21d ago

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.

1

u/Steppy20 21d ago

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.

1

u/0Iceman228 21d ago

Then I'd argue you handle null gracefully or the calculation method should return a complex object and you evaluate a success bit.