News for hackers. Stuff that matters.
Re:Special Cases Are a Code Smell by fenomas on Thursday January 24, 2019 @11:42PM (#18995613)
I'm profoundly unconvinced by this. "Handle special cases, then do the thing" is such a widespread, nigh-universal pattern that I don't think it hides anything from the programmer. It's the pattern used by any function that checks its inputs!

Rejiggering an algorithm so as not to have special cases just puts cognitive load on whoever reads the code to suss out what the original algorithm was. "Why does this algorithm require its input array to be padded with zeroes? Oh I see, it doesn't - the developer just did that to remove some if statements."

Re:Special Cases Are a Code Smell by dpark on Friday January 25, 2019 @01:19AM (#18995959)
This feels very much to me like architecture astronaut behavior. This overwhelming drive to pull "elegance" out of everything mundane or tediously complicated.

Yes, you can sometimes rewrite your algorithm to eliminate "special cases", but if you do it at the cost of comprehensibility, it's not a net gain. In the case of these examples, we're not really even talking about "special cases", but edge cases, where you literally need to deal with an edge in the data. In the case of the neighbor sums, edge cases were masked by padding. In the case of the staircase, the edge is just obfuscated by the doubled labels and then hidden in a modulo operation. These are totally fine except that they seem to provide no value except "elegance", and they come at a high cost in terms of understandability. (The first step is literally "transform to a different problem", so now you need to understand the original problem as well as the new problem, and how they relate.)

I'm all for elegance when it comes bundled with understandability or legibility or performance or even simplicity. But often it actually means "clever" and it's an extremely subjective measure that delivers little to no value and is prone to causing problems later.

Re:Special Cases Are a Code Smell by arethuza on Friday January 25, 2019 @04:42AM (#18996752)
That first example in the article was interesting because it made me realise that I have a strong aversion to pushing the complexity into the data rather than into the code. Modifying the list seems to me that it could be a cause of other bugs (what if the list is re-used and something depends on it?).
Re:Special Cases Are a Code Smell by DarkWiiPlayer on Friday January 25, 2019 @05:20AM (#18996885)
Never mind bugs, imagine that array has 5 million elements. Good luck re-allocating and copying that to add an element at the start and another at the end.
Re:Special Cases Are a Code Smell by dpark on Friday January 25, 2019 @02:57PM (#19001872)
I don't like the approach of pointlessly reallocating the array this way, but 5 million elements is not a problem on any machine built in the last 20 years. That's just 20 megs for 4-byte integers. With modern GC, this is cheap. It's not something you'd want to do in a tight loop (the copy time will start to matter), but for something like the example, the cost (in machine terms) is negligible.
Re:Special Cases Are a Code Smell by pure-awesome on Friday January 25, 2019 @06:30AM (#18997146)
I also experienced an instinctual aversion to padding the array that I can't really motivate (honestly) except to say "I don't like it."

The version with special cases feels cleaner to me.

Re:Special Cases Are a Code Smell by scrabble on Friday January 25, 2019 @10:01AM (#18998467)
Padding the array is a bit of a code smell. You can't just pad an array without allocating a new block of memory. After allocation you need to copy the array into the new space. This is a significant amount of overhead to a fairly straightforward and efficient algorithm.
Re:Special Cases Are a Code Smell by arethuza on Friday January 25, 2019 @10:39AM (#18998843)
Well, that's easy to fix - copy your array into a linked list so you an insert elements at the head efficiently. ;-)
Re:Special Cases Are a Code Smell by klyrs on Friday January 25, 2019 @11:53AM (#18999786)
Yes, the real problem with this implementation is the data structure they use. But is `next == null` a special case? ogod what do we do?!
Re:Special Cases Are a Code Smell by banku_brougham on Saturday January 26, 2019 @07:35PM (#19009560)
This is interesting. Is it possible to implement a linked list while eliminating the end of the list ‘edge case’, in the fashion of the parent article?
Re:Special Cases Are a Code Smell by pure-awesome on Monday January 28, 2019 @06:55AM (#19016774)
Create a "sentinel" node which represents null and also points to itself, perhaps?
Re:Special Cases Are a Code Smell by klyrs on Friday January 25, 2019 @11:47AM (#18999727)
> we're not really even talking about "special cases", but edge cases

Indeed. This article has a bit of a smell. Sacrifice performance to the almighty gods of your opinions about elegant code? It doesn't make code less buggy. It verges on a holier-than-thou attitude, that case-y code is Bad(TM), with a sequence of increasingly-contrived examples.

And in fact, lots of algorithms are unavoidably case-y. Teaching programmers to sneer at bounds-checking, as this article does, is downright irresponsible. Sure; the right language might do that for you -- but whether it's a default value or a runtime error, a programmer's failure to fully explore the edge cases will result in incorrect behavior, crashes or both.

Re:Special Cases Are a Code Smell by klmr on Friday January 25, 2019 @06:50AM (#18997230)
I do feel that elegant implementations are superior to others (all other things being equal). However, we need to be careful how we define “elegant”. For instance, while I fundamentally understand the drive to eliminate special cases, I don’t think that zero-padding the input (or concatenating the reversed input) is necessarily more elegant. It certainly incurs a nontrivial runtime overhead (unless done via lazy data structures, in which case we’ve just hidden the special cases).
Re:Special Cases Are a Code Smell by DarkWiiPlayer on Friday January 25, 2019 @05:39AM (#18996962)
Those examples clearly show how used programmers have gotten to the ease of use that languages like Ruby (the one used in the examples) provide. "Just pad the array with zeroes" sounds like an easy enough idea until you realize this might imply reallocating several gigabytes of memory depending on the size of your data set, possibly even running out of memory.

Either way, the example implementation assumes the first and last elements are treated as having only one neighbor; which seems like an odd specification for the algorithm in the first place. To me it seems like the source of this code smell is a bit further up in the call stack.

As for the second example, it becomes even more obvious how inefficient the "better" solution is. Just copy the entire array except the last element, in reverse order no less (so it can't just be memcpy()'d). This is what happens when you teach kids Ruby (or php, or pythin or...) because the job market demands it, but not the fundamentals (i.e. C, C++, Pascal, etc.).

As for elegance, both "improved" examples seem extremely ugly to me. Not only do they turn a clearly readable if statement into something more magical, they also mutate their data before operating on it. Turning 5 lines of structured code into a one-line abomination isn't elegant, it's dumb. It decreases maintainability. It increases complexity. It makes room for errors to hide. It's, to put it simply, bad coding style.

Re:Special Cases Are a Code Smell by nikanj on Friday January 25, 2019 @08:41AM (#18997761)
And if you argue against this insanity at a code review, some clod is going to misquote Knuth at you. "Don't prematurely optimize" doesn't mean "just alloc half a gig of memory, and profile later if performance is unsatisfactory."
Re:Special Cases Are a Code Smell by efdee on Friday January 25, 2019 @08:47AM (#18997800)
Ironically, complaining about the elegant solution of padding the array with "well this is going to suck on a multi-gigabyte in-memory dataset" is pretty much the definition of premature optimization. Chances are very high his dataset is not multi-gigabyte in-memory.
Re:Special Cases Are a Code Smell by dahart on Friday January 25, 2019 @10:03AM (#18998493)
Not really. Making a one-time allocation for a linear pass through an array is almost always bad. It’s often just as bad for many small arrays as it is for one big array.

The idea to not prematurely optimize was never intended to be a free pass to use wasteful practices everywhere until there’s a horrible problem, it’s more about avoiding factoring your code into something you can’t maintain. Generally speaking, baking your corner cases into your precondition code is more dangerous than avoiding allocations.

The idea was also not to leave concerns about performance completely off the table until your application is correct; it is assumed that you are making somewhat reasonable choices for your unoptimized code and your architecture, not that you are actively trying to slow things down with unnecessary allocations.

Re:Special Cases Are a Code Smell by DarkWiiPlayer on Friday January 25, 2019 @01:21PM (#19000710)
I disagree with two points of what you said. The first is that you call something that copies an arbitrarily long memory section to avoid two ifs "elegant", the other is everything else.

Elegant code uses less instructions, clear structure and is in general one of the better implementations in terms of performance. The suggested implementation shifts the workload into standard ruby functionality, but multiplies it by many times in the process; turns the clear structure of two conditionals into weird data trasnformations that and ultimately performs much worse than just the two extra ifs.

The multi-gigabyte-dataset was obviously an extreme example (yet one that may very well happen in practice). The point is, bad code like that is inevitable going to slow down an application, the question is whether you care about speed at all. Arguably, if you're using ruby, you probably don't.

Premature optimization usually refers to taking straight-forward code and making it more complex based on certain performance assumptions, like unrolling loops or writing inline assembly. This is bad because, well written code is most of the time fast enough, and if it does need optimizations, that will become clear soon enough.

Choosing not change your code in a way that considerably impacts performance based on ones individual perception of cleverness and elegance, however, is not an optimization; it's avoiding a dumb mistake that will bite you in the ass later on.

Re:Special Cases Are a Code Smell by taco_emoji on Friday January 25, 2019 @01:44PM (#19000999)
Padding with zeroes doesn't have to involve reallocating anything--you could wrap the array in an iterator that first yields 0, then yields each array element, then yields 0 again.

E.g. in C# using Linq:

    foreach (var num in myArray.Prepend(0).Append(0)) { /* blah */ }
Re:Special Cases Are a Code Smell by westoncb on Thursday January 24, 2019 @11:55PM (#18995674)
> Rejiggering an algorithm so as not to have special cases just puts cognitive load on whoever reads the code to suss out what the original algorithm was.

Sometimes that's how it goes, but other times the special cases were a result of just not knowing the original problem well enough to think of a clean solution that really captures its essence, and the special cases are evidence of a sort of resultant duct taping.

Agreed though, what you're describing definitely happens and I'm not a fan.

Re:Special Cases Are a Code Smell by zapzupnz on Friday January 25, 2019 @12:09AM (#18995724)
I'm glad I read this comment straight after I read the article because you've convinced me not to eliminate special cases in this particular manner.

I'm sure special case elimination is useful and sometimes necessary for clarity, but only if not done at the expensive of said clarity.

I would be open to seeing some examples that make clearer sense, though. A video I found much more convincing was Embracing Algorithms[1] from Apple's WWDC 2018. I just watched it last week, and I found the ways it broke down and deobfuscated rather simple problems into easier solutions that describe the problem and solution more concisely to be superior to what was in the article.

[1]: https://developer.apple.com/videos/play/wwdc2018/223/

Re:Special Cases Are a Code Smell by voidhorse on Friday January 25, 2019 @12:34AM (#18995824)
I think it depends on the situation. For example, under a functional paradigm the first problem is solvable as a special form of fold. The functional paradigm has tons of concepts backing it that make solving it in a ‘foldlike’ manner clear (which would involve the sort of padding the author suggests). In fact, the elimination of the special case is just a utilization of a monoidal operation and identity. In a lot of contexts “monoid” is a bunch of Mumbo jumbo, but in some functional languages it’s an incredibly clear way to go about resolving the issue. It’d also be perceived as more elegant than pattern matching against the first and last element of a list using some kind of predicate (aka a guard).

I think a suggestion to think about your reader foremost resides at the core of your comment, and I think that’s what’s most important. In a context that’s predominantly iterative or object oriented you’re completely right—the special case pattern is far more pervasive and you’d be doing your readers no favors by abandoning it. However if you could expect your readers to come equipped with a host of functional idioms, the elimination suggestion isn’t so bad (at least from a semantic/comprehension standpoint, ignoring performance).

Re:Special Cases Are a Code Smell by pure-awesome on Friday January 25, 2019 @06:33AM (#18997159)
I'm struggling to understand your motivation at the abstract level. Would it be possible to provide a snippet of Haskell code with an example of a solution implemented this way?
Re:Special Cases Are a Code Smell by riskable on Friday January 25, 2019 @09:23AM (#18998054)
My thoughts exactly... The French have a saying,

"With enough 'ifs' you could Paris in a bottle."

This is what we, as software developers, do! We create conditions to make (amazing) things happen!

Conditionals are the bread and butter of programming. They're what allow us to "fix" things in short order. They give us the flexibility to make our software work in a seemingly infinite number of situations.

They also make debugging easier! Waking through the logic of even a zillion conditionals is quite straightforward and gives you that, "aha!" moment pretty quickly. Whereas walking through an algorithm that only works on a weirdly transformed data set just has us scratching our heads wondering why the previous developer felt the need to, "fuck with the data" instead of just writing a few clear and concise conditionals.

Conditionals are also easy to split up! They give you lots of clear options if they start to "grow out of control" as it were. Whereas transforming the data in various code paths can rapidly create debugging nightmares!

Re:Special Cases Are a Code Smell by chriswarbo on Friday January 25, 2019 @11:08AM (#18999167)
The tradeoff is that conditionals increase the number of paths through the code. It's like Tony Hoare said:

> There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.

I hit this problem the other day, writing some code to divide a set of items evenly into N subsets. I wrote a bunch of property tests for this, but kept having problems with the way it was handling remainders. I could have made the tests pass by adding a few more conditionals, but instead I tried to solve it using no more than one conditional plus a handful of arithmetic operations.

The reason I constrained myself was that those test failures were a precious resource to help me understand the problem. Adding complexity to the solution could have produced a correct implementation, but I felt it would more likely out-smart my test suite. I would rather work with something that's clearly broken in an obvious way, rather than possibly broken in an unknown way.

Eventually, I came to realise that the requirements I'd come up with were inconsistent!

Re:Special Cases Are a Code Smell by userbinator on Thursday January 24, 2019 @11:56PM (#18995678)
Indeed, in the first example the special cases should really be moved out of the loop too, so you have the code looking like this:

    - code for left edge
    - code for body
    - code for right edge
Now, both you and the machine don't have to keep thinking about the edge cases every time through the loop body. It's a win-win situation.
Re:Special Cases Are a Code Smell by elephantum on Friday January 25, 2019 @12:21AM (#18995775)
It means you have two extra special cases: 1) list is empty; 2) left edge is the right edge (I.e. length is 1)
Re:Special Cases Are a Code Smell by riskable on Friday January 25, 2019 @09:34AM (#18998161)
Nothing that can't be solved with more conditionals!

Conditionals are great because they're clear and concise...

    if not list: # Can't do anything with this
         return # or raise error
    if len(list) < 3: # Ditto
         return #ditto
Sure, there's more code but it's not bad code. It's just straightforward stuff that's easy to read and debug (if necessary).
Re:Special Cases Are a Code Smell by wtetzner on Friday January 25, 2019 @10:26AM (#18998716)
"Programmers are not to be measured by their ingenuity and their logic but by the completeness of their case analysis."

- Alan Perlis

Re:Special Cases Are a Code Smell by jfengel on Friday January 25, 2019 @11:07AM (#18999160)
Does that really cover everything that goes into a good measure of their code? ;-)
Re:Special Cases Are a Code Smell by klyrs on Friday January 25, 2019 @12:02PM (#18999879)
It's a good baseline. I once wrote a paper featuring about 20 pages of case analysis. This makes me good programmer, yes? Well okay I wrote a dozen paragraphs of code and a theorem-checking algorithm, and abused that algorithm to populate a human-readable latex template, and published that without shame. Such a good programmer.
Re:Special Cases Are a Code Smell by wtetzner on Friday January 25, 2019 @01:22PM (#19000719)
No, I would say that it's necessary but not sufficient.
Re:Special Cases Are a Code Smell by cabaalis on Friday January 25, 2019 @07:30AM (#18997374)
Exactly: In the first example, they take an array, copy it and add extraneous data for the sole purpose of eliminating a couple if statements?

I'm not perfect either, but that deficiency for the sake of elegance is technical debt. A year later, when that piece of code is running thousands of times over thousands of numbers, nobody is going to know why it does what it does. Just that the system throws random out of memory errors or something.

Re:Special Cases Are a Code Smell by phkahler on Friday January 25, 2019 @08:15AM (#18997604)
>> Exactly: In the first example, they take an array, copy it and add extraneous data for the sole purpose of eliminating a couple if statements?

The IF statements are not even necessary. Compute the sum for the first elements neighbors first (sum[0]=element[1]) and the last element (sum[n-1]=element[n-2]) Then loop over the remaining elements with no conditionals.

I agree with the author that it's probably better to pad it than to have conditionals at every iteration, but for this problem there is no need to have a conditional at all.

Re:Special Cases Are a Code Smell by dpark on Friday January 25, 2019 @03:15PM (#19002062)
Your algorithm breaks for lists of size 0 or 1.
Re:Special Cases Are a Code Smell by diminoten on Friday January 25, 2019 @02:21AM (#18996164)
Cognitive load isn't some anathema to all of programming. The trick isn't to avoid it, the trick is to isolate it.

Pretending like cognitive load is never worth the effort is wrong.

Re:Special Cases Are a Code Smell by richmarr on Friday January 25, 2019 @05:05AM (#18996834)
I see where you're going with this, but to be useful you need to split cognitive load (and the complexity it processes) into two groups.

There's complexity inherent to the problem and complexity that's incidental to the problem.

Cognitive load inherent to the problem should be isolated.

Cognitive load required to deal with incidental complexity (such as clumsy abstractions, etc) is a waste of time and should absolutely be minimised.

Re:Special Cases Are a Code Smell by ummonk on Friday January 25, 2019 @02:29AM (#18996188)
I think where you can easily handle the edge cases, as done in the first and third` examples here, it's a good idea, because it's far easier to check correctness of the algorithm.

In the particular case you mentioned it's perfectly reasonable to explain why the array is getting padded in a code comment.