A simple best practices question that I haven’t seen addressed in the introductory programming books I’ve read…
If a function or method does an action but does not return real data, an example being a function that increments a class property or a database value, should it always return a boolean success value?
Part of me says “of course, duh”, and then part of me says my code would quickly overflow with boolean success checks on every little operation.
Currently I check success on critical functions, but not on cascading functions that run if the critical check is passed, on the assumption that the success of the first ensures valid data/success of the following ones.
But I’m just a hobbyist. What do the pros do?
Returning success values when you don’t expect something to fail is generally bad design. You can forget to check the return values or check them in the wrong way, and if you start to use different values for different errors, things quickly get out of hand. (
-1: success or failiure? It depends on the writer!)Instead, you should use exceptions for exceptional circumstances. When exceptions are unhandled, they usually cause the termination of the application, which certainly makes you remember to check them. Their syntax is clear and you don’t litter your code with checks.
You haven’t specified a language, so here’s a VB.NET example that divides a number:
You can use it without checking the success value, but you can still handle errors using
Try...Catchstatements:(Not that I’m saying you should guard against divide-by-zero in this way; filter your input!)
If you do forget to make that check, you’ll soon be reminded in the testing phase instead of having your code silently fail. It’s also much cleaner, and the scope of a
Try...Catchcan be as large as you want, perhaps handling any error occurring in a particular error-prone method and throwing them away. Who knows?So, generally, use exceptions. If you find yourself planning to handle them, though, you need to do validation.