4 ms·
Related, one technique I like to use even though it's more verbose is to replace booleans with enumerations. For instance, maybe you have something that could b
by overgard 4y ago
Related, one technique I like to use even though it's more verbose is to replace booleans with enumerations. For instance, maybe you have something that could be selected or not. I generally think instead of having "true" be selected and "false" be not selected, it's better just to have ListItem::Selected and ListItem::Unselected. That way when you pass things to a function, instead of reading a lot of true/false things in random places, you can see "ListItem::Selected" instead. Small upfront cost for a lot of readability down the line.
Typescript is nice for this in that you can use strings but enforce that they're in some set.
- msm_ 4y agoI agree, but without pattern matching converting "boolean-like" enums get tedious. For example: 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.
- gpderetta 4y agoYou can of course use a switch statement and the compiler will warn if the cases are not exhaustive for the enum.