sj95126 wrote:
I try to keep my code simple and straightforward. I'm not wild about overly complex compound statements. Sure, they might save a few bytes and a few clock ticks, but that's not worth the confusion of "why the heck did I do that?" down the road. The trade-off is that I always feel my code has an amateurish look to it. I don't mean so amateurish that I used an if-then-else as though I don't know how to use a ternary operator. It just looks too simple. Maybe that's the way you always view your own code.
That's generally the mark of a great programmer. You should strive to express your ideas in ways that are easy to read. If it is hard to read, you are either doing something really clever or really stupid. And cleverness is in short supply, usually.
It is usually helpful to get the code size down. More lines are more of a burden on everything, but most importantly, on the people reading your code, including yourself. This is, of course, not generally true. It also depends on the complexity of those lines. For example, today I wrote this statement:
Code:
is_tn = (is_tn & ~(1ul << i)) | ((is_tn >> (nfd - 1 + i)) & (1ul << i));
This statement has a bug in it. I don't know if you can see it without context. (In context, nfd is guaranteed to be larger than i.) But most of all, it just looks ugly, so I rewrote it:
Code:
if (is_tn & (1ul << (nfd - 1)))
is_tn |= 1ul << i;
else
is_tn &= ~(1ul << i);
And boom, suddenly I know what is going on. This time, it is admittedly longer, but one should strive for more understandable code over "faster" code.
I do like ternary operators if they can make an idea appear more clearly. I often fix up code like
Code:
if (some_condition)
set_color(foo, RED);
else
set_color(foo, GREEN);
with a ternary operator, because I want it to be clear that a color is being set. And after disentangling a web of logical operators today, I really don't get why the ternary operator gets singled out so often. The logical operators can do just as much damage if their number grows large enough.
sj95126 wrote:
And look at open source code for ideas.
Oof, those can be really hit or miss. Some open source projects, like musl, can be downright therapeutic, yes, but some others not so much. Busybox seems to be making an effort, though. newlib on the other hand is really great if you're in the mood for some horror and you misplaced your Lovecraft collection.
bzt wrote:
They keep thinking about the issue in their sleep and even when they "take a bath".
If I had a penny for every time I solved a bug on the toilet... I'd have tuppence!