0
Is it a better practice to perform an error check before or after the code?
For example, if the user enters a number outside the expected range, is it better to account for it before the calculation, or after?
2 odpowiedzi
+ 3
I assume by calculation you mean the implementation of whatever is supposed to occur.
If there's some range that a user must enter then extra work is a waste of resources because you'll tell the user to enter a new number anyways. Plus the code may fail. It doesn't make sense to do the work before handling the problem.
For example, say someone enters an invalid credit card. Would you still process the payment and give them their receipt?
Alternatively, you can check errors before or after the code in a function, not just user input.
Sound programs may use what are called invariants with pre conditions and post conditions. Invariants are what must be true. The pre conditions are what must hold prior to the functions main execution (e.g., value not being null, or being larger than 0). Post conditions are checked after execution (e.g., the function for adding an element to the linked list has its size increase and a new non null element).
This is typically enforced with assertions (and some if statements).
+ 1
I understand, so it depends on a purpose of the code. Thank you.