112 points · by signa11 · 3y ago · 164 comments
char *p = NULL;
...
if (p && *p != ' ') { ... }
If you write bool p_non_null = (p != NULL);
bool char_non_space = (*p != ' ');
if p_non_null && char_ non_space { ... }
Oops. alias not_null = (bool)p;
alias not_space = (*p != ' ');
if (not_null && not_space) {
This may bite you in another way, but living in a world where everything gets evaluated asap-y isn’t syntactically easy either.Would be also nice to have this:
alias __cache foo = <heavy(expr())>;
if (foo && foo.length && foo[0].x) {
`foo` only evaluates once. auto not_null = [&]{ return (bool)p; };
auto not_space = [&]{ return (*p != ' '); };
if (not_null() && not_space()) {
It's not quite as ergonomic but it works.As an aside. I was curious if the compiler will optimize in the short circuit even if you extract the eagerly evaluated named booleans. However I was pretty sure the rules of c++ are against you and tests show this to be the case
But if you simulate the alias keyword with lambdas then the result after optimization are the same
It will optimize, but not necessarily what you wanted... Because null dereference is UB (with default compiler flags), it's allowed to elide null check.
#DEFINE NOT_NULL(x) (bool)x
#DEFINE NOT_SPACE(x) ( ' ' != *x )
// ...
if ( NOT_NULL(v) && NOT_SPACE(v) ) { ... }The reason is mainly the many language construct of C++ cover most traditional use cases of macros when programming C while at the same time being much less error prone than macros.
A sibling show how one easily can achieve the very same thing using short lambdas instead. That variant is also bound to the scope one is currently in, and in order to have that safety with a macro one would need to undefine the macros afterwards. One would also need to check that they are not yet defined beforehand, and if so restore the previous macro afterwards in order to not break completely unrelated code in case of macro name clashes.
Define your booleans as functions of no args. A sample in Python:
var = 'abc'
var_contains_a = lambda: 'a' in var
var_shorter_than_5 = lambda: len(var) < 5
if var_contains_a() and var_shorter_than_5():
print(var)Taking the last top-level statement, the `if`:
if var_contains_a() and var_shorter_than_5: #note the lack of parens for the second
print(var)
This will print a string of any length that contains 'a' (or any other collection that implements `in` and does, in fact, contain an element, 'a'). The second function is passed directly as a boolean expression, and being a function, it resolves to true.I'm curious as to if it's feasible to syncretise these two aspects of variable evaluation into a shared feature that makes async and sync code feel alike.
That's how Haskell works. Everything is lazily evaluated, and in the case that evaluation is needed now, the "seq" function obtains it (https://wiki.haskell.org/Seq).
bool char_non_space = p_non_null && (*p != ' ');But I don't understand your "inefficient" point. At the end of the day, everything gets turned into SSA. So expression-per-line and nested-expressions generates the same code, right?
bool dirty = ...;
bool success = doExpensiveCalculation(...);
vs if (dirty && doExpensiveCalculation)
{ if (p_non_null = (p != NULL)) && (char_non_space = (*p != ' ')) { ... }
But where the IDE only shows the LHS of the expression as: if p_non_null && char_ non_space { ... }
But also where the IDE makes it easier to write the earlier full expression above.Also, the initial code:
bool p_non_null = (p != NULL);
bool char_non_space = (*p != ' ');
if p_non_null && char_ non_space { ... }
This could simply be analyzed by the compiler to not store the named boolean variables in the first place, and to evaluate them inline in the if-condition so as to allow for the short-circuiting to occur fine. if (someLongNamedVarIsNotUnknown && someLongNamedMapCountIsZero)
return false;
else
return true;
This is not the same, but I'd suspect there might be a bug in the code above if (someLongNamedVarIsUnknown) {
return false; // Can't do much
}
if (someLongNamedMapCountIsZero) {
return false; // Nothing to do
}
// Do stuff
return true
The named booleans suggested here help adding clarity, but more often than not they'll end up being single-use (const) variables that just paraphrase their definitions. In these cases I'd rather avoid introducing a variable, and rely in comments if I really need to explain something.Interesting. With the same axioms I come to the opposite conclusion. That comments are to be avoided except when strictly necessary, and giving names to concepts via intermediate const variables is one of the best weapons in that fight. Ie. make your code read as close to what the comment would be (but simply via naming) makes it very clear when the names no longer match the behavior, in contrast to comments which have a tendency to bit rot.
That's ok. The worst tradeoff in the "named booleans" pattern proposed in the blog post is that it misses the whole point of chaining predicate evaluations, which is leveraging short-circuiting to prevent further predicates from being evaluated.
Chaining logical comparisons and the way they short-circuit is specially important when a predicate has preconditions and/or is expensive and/or has side-effects.
If your predicates are hard to read you don't fix that mess with "named booleans". You fix them by extracting them to a pure function like
isNotUnknown(_someLongNamedVar) && isNotEmpty(_someLongNamedVar)Says who? IME relying on short circuiting is useful and idiomatic in C and C++ code, e.g.:
if (callback && callback->run()) { ... }
In your opinion would it be better to write: if (callback) {
if (callback->run()) {
..
}
}
The situation is even more awkward if you try to avoid || short-circuiting, since you need to duplicate the body of the conditional.You've got it all backwards. Short-circuiting is not used to avoid side effects. Short-circuiting is used to avoid needless calls to any predicate, which can have and often do has side-effects, and if it doesn't have today it might have tomorrow.
If you don't call them when you don't have to, your code is in a better shape.
And let's not pretend that unconditionally macode with side effects when you don't have to is a good practice.
The point is not performance. The point is readability, and expressing things clearly and with the appropriate level of detail and leaving out nesting and scope. Safety and performance are important but secondary advantages.
const value = if (a) {
return true
} else {
return switch (b) {
case 1: return false
default: return undefined
}
} value := (if a then True
else (
case b is
when 1 => False,
when others => Undefined
)); const value = [&]() {
if (a) {
return true;
}
return switch (b) {
case 1: return false;
default: return undefinied;
}
}(); let value = if a { true } else { match b { 1 => false, _ => undefined } };
And notice that because now we're a function our relationship to the world changed, how does your immediately invoked lambda do this? let value = if a { true } else { match b { 1 => false, 2 => return foo, _ => undefined }};
With expression syntax returning from the function we're in is fine† but in your lambda you can't do that, you need control flow logic outside the lambda to handle it.† You might wonder about the inferred type of this expression since it might return. The type of the return expression in Rust is ! aka Never, which is an empty type. In the same way that N + 0 == N in integer arithmetic, any type plus an empty type is the original type again in type arithmetic, so the type of the expression isn't altered.
Still the syntax is a bit confusing. In ML languages (f# and also rust are somehow descendants of ML) you can just use if .. else if .. else expressions. They work like ternaries! But easier readable. Nested ternaries are useful, but get really hard to read very fast. (x = condition1 ? A : condition2 ? B : C;)
if ((_someLongNamedVar != FooLongNameEnum::Unknown) && (_someLongNamedMap.count (_someLongNamedVar) == 0))
really not too bad? And easily enforcable and automated checkable by your favourite tool..
Named vars for subexpressions often helpful too.. but especially here you loose short-circuiting?
(Not very C++ specific topic btw..?)
if (b1 && (b2 != b3))
rather than if ((b1) && (b1 != b3))99.9% when the condition is "too hard to read" it's because the condition is too hard to read, period, and the correct fix is to restructure the code to have readable branch conditions, not to throw parentheses on there to make a monster expression slightly less confusing.
It's like discussing the chemistry of air fresheners instead of taking the trash out more often.
There are certainly times when I take the name approach nonetheless, but more like a last resort, or when I expect full contact stepthrough with a debugger. If I deem it likely that I will get by with merely brackets and copious amounts of whitespace, that's what I'll do.
deliveryTime = 3;
if (primeMember) {
deliveryTime = 1;
}
you can pass in a `Membership memberType` value that contains the required information, so the above conditional turns into just the assignment deliveryTime = memberType.deliveryTime;
This is more amenable to extension and contraction: you can add or remove different classes of delivery times without changing the logic in which it's used.You can even use private constructors and public static fields to create a list of "constants" containing the known member types, like the `Membership.REGULAR` and `Membership.PRIME`, retaining the property of the code not being able to use an invalid membership type.
This can be used also for more complicated conditionals like the one in the article, by having a factory method that copies the right "constant" composite value based on whatever logic is desired.
On the downside, this breaks single-assignment, binding style variables. That is, now deliveryTime can’t be final/val/const.
I wish I had a better solution. Lisp did this so well with if/cond/etc as expressions.
One example of a language without that implicit conversion is Java. It's fairly annoying to have to put a "!= 0" whenever you want to convert a number to a boolean, but it does avoid a lot of programming mistakes within if conditions.
But it is sad that in $current_year, we're still fighting boring, solved problems.
I'm not saying C++ is a great language, it's not, but if you remove the secu then shoot you in the foot, it's your fault.
-Wall -Werror does not catch the error described in the blog.
It does get caught by a static analyzer though [0].
2. This would be caught by static analyzer
See Compiler Explorer example here [0]
if (cheapCheck() && expensiveCheck()) { ... }
is not equivalent to bool cheap = cheapCheck();
bool expensive = expensiveCheck();
if (cheap && expensive) { ... }
unless we're in a lazy pure functional language.And in any case the author misidentified the problem and solution. The problem is that C++ coerces bool to int. I'm 99% sure there's a warning for that that you can turn into an error.
bool cheap = cheapCheck();
bool expensive = cheap && expensiveCheck();
if (expensive) { ... } if (
(_someLongNamedVar != FooLongNameEnum::Unknown) &&
(_someLongNamedMap.count(_someLongNamedVar) == 0)
) {
// do something
} if (true
&& condition1
&& condition2
&& condition3
) {
...
}
If you ever need to change the set of conditions, the diff will cleanly add/remove whole lines. if ( condition1
&& condition2
&& condition3
) {
...
}
Obviously the best alternative is to switch to a prefix language and sidestep the issue entirely: (when
(and
(condition1)
(condition2)
(condition3))
...)1. Avoid overly long and complex condition expressions - break them up for readability.
2. If a part of a long expression has obvious meaning, assign it to a temporary (probably saving a comment); if it doesn't, break a line after it. I don't like assigning variables with arbitrary names that simply duplicate the expression calculating them.
3. `true` and `false` are magic numbers. Calling `my_function(my_data, false)` is quite the hazard in my view: It makes the reader rather likely to fail to notice the exact semantics. I would expect, say,
enum : bool { dont_save_copy = false, save_copy_to_file = true };
my_function(myData, dont_save_copy)
4. This is relevant to almost any language! Even functional ones, where you would be encouraged to use "let" or "with" instead of super-complicated unbroken expressions. If you're writing APL though... you need super-memory and a discipline of steel :-) if (_someLongNamedVar != FooLongNameEnum::Unknown && _someLongNamedMap.count(_someLongNamedVar) == 0)
does exactly what it’s supposed to.This is C++.
The most basic thing has been deprecated but is still supported for backwards compatibility.
Boolean is a perfectly cromulent data type that you can return from a function directly.
if (x1 < y1) return true;
if (x2 < y2) return true;
if (x3 < y3) return true;
return false;
I wouldn't want to replace the last two lines with `return (x3 < y3)`, even though that's functionally the same thing.In this contrived example, we could just return a single compound condition, but hopefully it's clear that there are cases where doing so would make more of a mess, too.
bool is_db_open() {
return (db != NULL);
}
bool is_time_to_report() {
if (n_errors >= limit) {
return true;
}
return false;
// a little confusing way
return n_errors >= limit;
}
Also, if there’s a chance of an additional condition, they can be easily be added and documented. if (n_errors >= limit) {
return true; // too many errors
}
if (now() >= deadline) {
return true; // periodic
}
return false;
For the same reason I often do this: if (x == 0) {
return 0; // not `x`the lengths of names of entities, in any programming language, should be related to their scope - small scope, small names. and as limiting scope is what you should be doing all the time, almost all names should be short.
also, unless you really know what you are doing, don't use leading underscores, or underscores in general, in c or c++.
here is something i wrote a while back, which admitedly does not too much address the single underscore issue: https://punchlet.wordpress.com/2009/12/01/letter-the-second/
Typescript is nice for this in that you can use strings but enforce that they're in some set.
ConnectionMode connectionMode;
if (useHttpsCheckbox.selected == ListItem::Selected) {
connectionMode = ConnectionMode::Https;
} else if (useHttpsCheckbox.selected == ListItem::Unselected) {
connectionMode = ConnectionMode::Http;
} else {
shouldNeverHappen();
}
In the real world there are often even longer chains like this - I found that bool-like variables ofter mean slightly different things at different layers of abstraction.And also, you could simplify that by ignoring the `else` entirely, but there are no guarantees that it won't break later. For example another contributor may add ConnectionMode::TryHttpsElseHttp, and compiler won't help us. Languages with pattern matching don't have this particular problem.
This is actually something I think the C++ standard should address soon. There are cases when extern functions which aren't appropriately pure are still "optional." The example par excellence is debug logging, should one choose to not use macros.
I tend not to work that way, but it’s really a matter of personal style. I do it to reduce the verbosity of my code (which tends to be fairly verbose, in other ways –especially comments). I will, occasionally, encounter the bug he mentions, but not particularly frequently.
If this wording means to convey that the complete test in the wrong code version is always giving the inverse of the correct version, then that statement is wrong. The truth tables, using 0 and 1 for false and true ("false" and "true" look too messy here):
The buggy code:
0 1+ <- second condition
0 1 1
1 1 0
^- first condition
The fixed code: 0 1+ <- second condition
0 0 0
1 1 0
^- first condition
i.e. the test as a whole is not inverted if the first subcondition is true.As has been pointed out, there are cases where it's not efficient or correct, but in general it's very useful. (Been coding since 1965, not always C++ obviously).
A very confusing article.
Why are we even still talking about C++?
There is a lot of code out there already written in C++ and a lot of people working on that code. Not to mention an active standards body.
Expect to be hearing about C++ for a long time to come
bool usersHairColorMatchesThisMonthsAdsColour = _user.hair == HairColour::Red;
bool userFeetSizeFitsInShoe = _user.feetSize <= _requestedShoe.size;
bool shoePriceFitsInUserBudget = _requestedShoe.price <= BudgetHelpers::Calculator(_user);
bool shoeIsProbablyOkayForUser = usersHairColorMatchesThisMonthsAdsColour && userFeetSizeFitsInShoe && shoePriceFitsInUserBudget;
if(shoeIsProbablyOkayForUser)
That they compare, with the "uglier": // this months ad campaign color is red
if(_user.hair == HairColor::Red && _user.feetSize <= _requestedShoe.size && _requestedShoe.price <= BudgetHelpers::Calculator(_user))
I very much prefer the latter, I'm sorry (except it needs some new lines, of course). It performs better (that `BudgetHelper::Calculator` doesn't look very cheap ;) but crucially it is, to me personally, more "readable". First, I find a comment easier to read than a variable name, particularly when you use the not so readable dromedaryCaseToCrambleWordsInLongSentences. Thus, a variable adds no value when it's only used once (arguably, it adds more noise, since one has to go twice through the same text). And it is often debatable how a programmers poor translation of code into English adds any value: in fact, I find `_user.feetSize <= _requestedShoe.size` to be way more succint, precise and easier to parse than `userFeetSizeFitsInShoe`.We really need to get over this school of thought that "the more wordy your variables the more readable" because it is simply not true. You don't have to go all the other way to the other end and write code using greek letters like in math. Meet somewhere in the middle, be aware of context and use the tools of the language (e.g. lexical scoping) to your power.
Unlike many of these bloggers want us to believe, you can't just boil "readability" down to some simple universal rules, and only experience makes the master. Taste, preference, purpose and context take a big part. As such, I find it useless to talk about "readable" code: readable for who? A law text, a maths paper, a school maths book, a user manual, a tutorial, a novel, a HN comment... they may all be written in English and with great skill in consideration for their "readability" by their target audiences, yet manifest completely different styles even when discussing the same topics.
For me, I like my code like I often enjoy most good writting: succint and precise. Wordy variables that add no value or abstraction are of little use to me.
hair_col_matches && size_fits && in_budget
is less than half the length and imho more readable because it doesn't turn each variable intoNeedlesslyWordyCamelCaseSentences.> you can't just boil "readability" down to some simple universal rules
Yes, in the end blindly following rules doesn't turn out as well as understanding why those best practices exist in the first place.