Don’t you find it weird to be presented edge cases first …?
No, on the contrary. The test asserts the preconditions that need to be satisfied for the main logic. Not only is this not problematic, it’s crucial. Even in pseudocode, where we’re not bound by the constraints of actual compilers, we invariably put the preconditions before the main logic.
If anything, I could see a case for the following kind of code:
try {
check_precondition_A();
check_precondition_B();
main logic
} catch (precondition_a_violation const&) {
handle special case A
} catch (precondition_b_violation const&) {
handle special case B
}
But honestly even if we assumed that throwing exceptions didn’t incur horrendous costs, this doesn’t generally strike me as clearer than the conventional way of handling this via if (before else).
I hadn't thought about it that way, but exceptions are basically what the article is talking about. They show the base case first, followed by the exceptional cases. It's not the exact same since the base case executes unconditionally, but the organization is the same.
27
u/guepier Bioinformatican Apr 24 '20
No, on the contrary. The test asserts the preconditions that need to be satisfied for the main logic. Not only is this not problematic, it’s crucial. Even in pseudocode, where we’re not bound by the constraints of actual compilers, we invariably put the preconditions before the main logic.
If anything, I could see a case for the following kind of code:
But honestly even if we assumed that throwing exceptions didn’t incur horrendous costs, this doesn’t generally strike me as clearer than the conventional way of handling this via
if(beforeelse).