A peer of mine is working on a report that displays the weekly (Sunday to Saturday) advance of every employee in our small consultancy firm. There's a piece of code he wrote that shows the columns corresponding to the days in the target week. His algorithm is the following:
- Get which day of the week the first day of the month is. If it's Sunday, set a flag to zero; otherwise, set it to one.
- Iterate through all the days of month. If it's Sunday, increment the flag. Then, if the flag's value is equal to the week to be displayed, show the column corresponding to the current day; otherwise, hide the column.
Of course, the flag indicates what the current week is.
I suggested another algorithm:
- Get which days of the month are the first (F) and last (L) days of the specified week. For example, the first week of October 2009 starts on Tuesday 1st and ends on Saturday 3rd.
- Iterate through the columns corresponding to days 1 to F-1, and hide them.
- Iterate through the columns corresponding to days F to L, and show them.
- Iterate through the columns corresponding to days L+1 to DaysOfMonth, and hide them.
The "difficult" part in my algorithm is part 1. I mean "difficult" as in "difficult to understand", because the algorithmic complexity of doing it is constant. And my algorithm has the advantage of having tighter loop. My peer's loop does a comparison for every day of the month. Mine doesn't.
This was a little example and you might say that over-optimizing here is a bit too paranoid. But his programming style doesn't change a bit when we write actual performance-critical code.
His code is also full of these tests:
/* doSomething() doesn't change the state of the relevant variables. */
if (condition)
{
flag++;
if (flag > test)
doSomething();
}
else
if (flag >= test)
doSomething();
When, of course, it can be done like this:
if (flag >= test);
doSomething();
if (condition)
flag++;
What do I do?!?!?!
EDIT: I corrected the comparisons in the code samples.