3 ms·
When I have an if clause that is too complicated to work out how to correctly invert it (because while I understand de Morgan's just fine, it can get very detai
by jerf 8y ago
When I have an if clause that is too complicated to work out how to correctly invert it (because while I understand de Morgan's just fine, it can get very detailed), I find it far preferable to start factoring out the expression, e.g. if I need to invert,
if ((a and b) or (a and c and not d)) and not e)
should be something more like
orderSubmitted = a and b
orderValid = a and c and not d
orderNotYetFulfilled = (orderSubmitted or orderValid) and not e
if not orderNotYetFulfilled {
# code here
}
Ideally, a through e are also named something reasonable enough that the variable declarations read cleanly.
The raw de Morgan's transform is only necessary if it's a performance optimization, and in 2019 the conditions for that to be an issue are very, very precise.
- rowanG077 8y agoI assume the compiler can easily optimize something like that similar to constant folding. Isn't that the case?
- jerf 8y agoIn most cases I'd expect so. The rare cases I was thinking of was on the order of "I'm on an embedded system using a crappy compiler and I can't change it and I literally can't afford extra bytes for boolean values the compiler won't optimize away", and on the other end, "I'm in the cloud and my code has confused the optimizer and I have to code this inner loop incredibly carefully because it's going to be called several billion times per second". Maybe the odd other corner case here or there. There shouldn't be much in-between in 2019 where writing the clauses out this way will have a materially negative impact on one's code, and it should have a generally very positive one.
- p2t2p 8y agoIn this case I'd probably write an inline function which would accept all those booleans and then return (x && y) || (a && b) && !(c != d) //pseudo example of complex condition Or write a bunch of macros given that if you're on embedded 99.999% probability you're writing C.