Post by JohnCYou should always assume that code you write will be modified by someone
else when you are not around (gone to another job, on vacation, ...) and
that that person will be half as intelligent as you are.
Thus, CLARITY should be the primary goal, not whether you find it obvious or
not.
if ( a == b )
y = x + 1;
else
y = x;
It is immaterial whether or not the line
y = x + ( a == b );
would work or not.
Clarity is very important, but one must ask: clear for whom?
Some complex solutions can still be very clear in code, but the
solution is inherently difficult. Some solutions are simple to
understand in the naive case, but a decent implementation requires a
more ... creative ... solution.
Any problem involving domain-specific knowledge is going to be clear
to those who work in that area, and not-so-clear to others.
For example, if you do a lot of low-level work twiddling bits, then
some things are second nature to you that are as foreign as Urdu to
others. That doesn't mean you shouldn't code it, it means that others
need to have a certain proficiency. I suggest that we define
"clarity" of code to be "clear to a competant programmer familiar in
the problem domain."
Problem:
How do you find 2 numbers that differ by no more than 2 bits?
The question is easy to comprehend, but the naive
loop-through-the-bits solution is clunky, slow(er), and probably the
first thing that most everyone thinks of, but argubly the worst
solution. Implementing an idea that is clear using clunky code is
catering to the wrong ideal. It certainly "works" but is anything but
beautiful. Below, I wrote 3 implementations to the problem stated
above, each better than the previous, though the first two have a lot
in common and I consider poor solutions. IMHO, the final solution is
light, elegant, fast, visually pleasing, and is clearly the optimal
solution. (Only "downside" is that it's a little more complicated
due to the bitwise logic behind it.)
bool differs_2_bits_at_most_BAD(
unsigned int num1,
unsigned int num2)
{
int diff_count = 0;
for (int i = 0; i < 32; ++i)
{
if ((num1 & 1) != (num2 & 1))
{
++diff_count;
if (diff_count > 2)
{
return false;
}
}
num1 >>= 1;
num2 >>= 1;
}
return true;
}
bool differs_2_bits_at_most_BETTER(
unsigned int num1,
unsigned int num2)
{
int diff_count = 0;
unsigned int bits = num1 ^ num2;
unsigned int mask = 1;
for (int i = 0; i < 32; ++i)
{
if (bits & mask)
{
if (++diff_count > 2)
{
return false;
}
}
mask <<= 1;
}
return true;
}
bool differs_2_bits_at_most_BEST(
unsigned int num1,
unsigned int num2)
{
unsigned int bits = (num1 ^ num2);
bits &= bits - 1;
bits &= bits - 1;
return bits == 0;
}
Which is the clearest?
--
Chris (TeamB);