Skip to main content

The Sum of All Sums

Published: October 04, 2010

Several years ago, we had a foreign contractor write some code for one of our applications. One piece involved create some javascript to sum numbers on a dynamically generated page.

About a year ago, I rewrote it - you see he had coded 4 functions; Sum1, Sum2, Sum3, and Sum4. Sum1, Sum2, and Sum3 were identical except that different bugs had been fixed in each piece of code over time by other developers, so they didn't "look" identical at first blush. That was confusing. Not to mention it was a little intimidating and scary to fix up each function so that all of the bugs were corrected in a way that didn't modify the behavior of the framework that depended on these functions. Who knows, maybe someone coded in a way that made Sum3 work correctly for them...

The real surprise though, was Sum4. It presented a completely different problem. One might have assumed that it was simply a fourth sum. Imagine my surprise when I realized that it was not a fourth sum at all! It was in fact, the sum of all sums (Sum1 + Sum2 + Sum3)! A grand total. Even worse, it didn't use Sum1, Sum2, or Sum3 to do this. Instead, it was simply a (very poor) copy of the code original code for Sum1, Sum2, and Sum3! Of course, completely different bugs had been fixed inside this function when compared to the current versions of Sum1, Sum2, and Sum3. Woah.

Long story short I ended up rewriting the code. We now have a single Sum(x) function that can do the work of sum1, sum2, sum3, etc... and we have a TotalOfAllSums() function that is aware of the number of summations we have on a webpage, and it simply calls sum(x) to determine the total. Simple, and, now we can implement a fourth Sum in the future without having to resort to naming it "Sum5" and copying and pasting say... Sum3 to get us started.