by jlebar · 6y ago · 0 comments
Instead of
string x;
switch (y) {
case 0: x = "foo"; break;
case 1: x = "bar"; break;
}
try an IIFE! string x = [&] {
case(y) {
case 0: return "foo";
case 1: return "bar";
}
}();
Once you get used to reading it, there are a bunch of advantages. Among them, you can't forget a "break", and you can't forget to assign into `x`. string x = y ? "foo" : "bar";
or if y can take more values than 0 or 1, then that strongly suggests it should become a table lookup: string x = some_strings[y];Regarding the ternary, nested ternary expressions aren't the most readable thing.
Regarding table lookup, sure but only if all values of y are sequential integers.
It seems to me the extra safety it provides actually makes it harder for a novice to break your code?
Unless you mean strictly in the sense of "harder to break compilation", but I'm not sure that's a good thing (insert obligatory mention of Rust here)
Did you consider that it is possible that everybody can read the second example but may need to spend more time reading it to comprehend if they haven't seen it before and may make mistake interpreting the code?
Did you consider not every company is Intel or Google and there is a lot of companies that can't get "top 1% talent"?
Readability is about making it easy to understand the code, without putting effort into reading.
Readability is important because code is written once and red many times by people who may need to read a lot of code and don't want to spend much time trying to understand every line of it.
Same benefits that you also get with:
string x
= y == 0 ? "foo"
: y == 1 ? "bar"
: "baz"
;
Only, using ?: additionally forces you via syntax to specify what x's value should be when all prior conditions fail. In both your examples, x is undefined when y is neither 0 nor 1. auto succ = [](int i) { return i + 1; };
To make variables in the surrounding scope visible (i.e., create a closure) you have to specify that they're available and how. Grabbing a reference to all variables in scope you could do: int x = 0;
auto inc_x = [&] () { return x++; };
This makes x available via reference so it can be modified. If you just want the value: int x = 0;
auto always_one = [=] () { return x + 1; };
And you can constrain which variables are visible within the lambda: int x,y;
auto foo = [&x] (auto n) { x += n; };
The return type can be determined by the compiler, or they can be made explicit (I chose not to). The first examples all returned integers, the last one has void return type.