3 ms·
I've been told many times that it's better to eliminate edge cases. I still don't really believe it as a universal law. When explaining the algorithm "remove a
by Smaug123 10y ago
I've been told many times that it's better to eliminate edge cases. I still don't really believe it as a universal law.
When explaining the algorithm "remove an element from a linked list" to someone else, I would say "starting at the head, go along the list until you find the element; then delete the element". When explaining the algorithm "delete an element from a linked list", I would say "if you're at the head, update the head to be the next element; otherwise update the `next` property of the previous element to be the `next` property of the current element". It's so naturally a two-case problem that I'd be really surprised if anyone came up with the one-case answer first. Therefore, the two-case answer is the more readable to someone who has not seen the code before, because it corresponds to their intuition about how the algorithm should work.
As a bonus, it's clear to me that the naive algorithm is correct, but I have to do mental work to convince myself that the one-liner algorithm is correct. (I'm saying nothing about the code; only the algorithms.)
I agree much more with the reduced complexity of the later example (initialising the edges of a square), and I actually think it's worth double-counting the corners in this instance because the code is so much cleaner. (EDIT: Although I suppose the easy fix doesn't detract from the ease-of-reading, so actually it's avoidable.) In that instance, there's doubt about which is the natural algorithm to pick: one could conceivably come up with "initialise the top and bottom, then initialise the left and right", or "initialise the zeroth element of each side, then the first of each side, then…" as one's first attempt at solving the problem. Therefore I like this particular simplification.
- marcosdumay 10y ago> I still don't really believe it as a universal law. If you were doing kernel development, you would. If you were writing enterprise CRUD applications, you wouldn't even think about it, and if you were developing hight throughput middleware, you'd switch that law on and off depending on where you are on the code. Or, at least, s/would/should/.
- apk17 10y ago> It's so naturally a two-case problem that I'd be really surprised if anyone came up with the one-case answer first. [Raises hand] I always did it Linus' way in C (way before him); I don't remember if I ever had the need in assembly before.
- Smaug123 10y agoFair enough. I stand surprised! How would you describe the algorithm to a friend, then?