Objects.requireNonNull
is a helpful method to spot NullPointerExceptions effectively while developing. But in fact it's throwing a RuntimeException which could crash the application (the worst thing ever in production).
Which brings up the question – is it safe to use this method on production or just in development?
Java Programming Practices – Is Using Objects.requireNonNull() in Production Bad Practice?
javaprogramming practices
Best Answer
Objects.requireNonNull
is basically function precondition. This is very similar to assertions since they can also be used as preconditions. So asking whether we should useObjects.requireNonNull
is the same as asking whether we should keep assertions in development and in production. Opinions of experts:Other thoughts in ShipWithAssertionsOn
My opinion:
You should use it for situations:
Let's play devil's advocate:
Suppose customer is making an order and you get an error in
sendMail
function that sends email about order state to customer. Since program broke in the middle of order it is not clear what is the state of that order. Order could be made without sending email to customer. Since making an order is primary objective we should not assert insendMail
.Suppose that we did not add assert in
sendEmail
the program still crashed because of invalid arguments Fail-Fast tells us that we should have added assert. Since that would give us more knowledge about the error.Suppose that we added error handling in
sendEmail
for invalid parameters. We notice the problem some time later from error logs and some customers complaining. Other customer still can make an order and don't notice missing email. Now we are left with dilemma of what other functions should have error handling too.