Send to a Friend

LostInParadise's avatar

What is the balance in programming between brevity and understandability?

Asked by LostInParadise (31921points) September 16th, 2011

Let me give a small example to illustrate what I mean, a simple programming problem of a type that I am sure has been solved many times before. I needed to know how many days it has been since the previous Thursday, where the answer is 0 if the current day is Thursday.

The way that a typical non-mathematically oriented programmer would do this would be to call a function to get the day of the week of the current day and store it in a variable wkday. (In the language I was using, the function return value goes from 1 for Sunday to 7 for Saturday). Then go through all the 7 cases and assign the number of days to some variable daysBack. This is perfectly reasonable. It takes negligible computer time and would require a single comment to indicate what is going on, saying something like /* Find number of days since previous Thursday */.

This solution upset my aesthetic sense. Since Thursday is 5, why not just calculate wkDay – 5? The problem of course occurs if wkDay comes before Thursday. We end up with a negative number telling how to get to the following Thursday. The solution is to add 7 to get back to the previous Thursday. So the code would look like:

daysBack = wkDay – 5
if daysBack < 0 then
daysBack = daysBack + 7

How to get rid of that annoying if statement? Oh, we are just doing modular arithmetic, so I could write:

daysBack = (wkDay – 5) mod 7

The problem here is that most programming languages, will not change negative numbers to positive ones. -3 and -10 mod 7 come back as -3. There is a simple solution. Add 7 to the value in parentheses. What we get is congruent mod 7 to the original with no negatives to worry about.

daysBack = (wkDay + 2) mod 7

The problem now is that anyone looking at this final solution will have a hard time figuring out what the code does, including me if I have to revisit the code. It will require an additional comment, countering any justification that I might have of making the program more readable.

Having spent all this time to come up with a one line solution, I am sticking with it. Should I have just stuck with the original?

Using Fluther

or

Using Email

Separate multiple emails with commas.
We’ll only use these emails for this message.