I have a few logic that looks like
if(a){
if(b){
if(c){
//do something
}else{
//do something
}
}else{
if(c){
//do something
}else{
//do something
}
}else{
if(b){
if(c){
//do something
}else{
//do something
}
}else{
if(c){
//do something
}else{
//do something
}
}
What is the best way tot implement this into readable logic? I dont want to do some big OOP surgery to make it readable because the do something is just one liner. Solution in C/C++ is appreciated
Since the conditions are boolean, and apparently independent, treat them as bits in a word and switch on them:
#include <cstdio>
#define COMPOSE(a,b,c) ( ((!!(a)) << 2) | ((!!(b))<<1) | (!!(c)) )
int f(int i, int j, int k) {
switch(COMPOSE( i==j, i+j<k, k!=42)) {
case COMPOSE(true, true, true):
printf("yo\n");
break;
case COMPOSE(true, true, false):
printf("ye\n");
break;
case COMPOSE(true, false, true):
printf("ya\n");
break;
}
}
int main () {
f(1,1,1);
}
If all //do something are fundamentally different, you don't have much choice (afaik).
For code style I would prefer
if ( a && b && c )
{
}
else if ( a && b && !c )
{
}
else if ( a && !b && c )
...
This removes the necessity of multiple levels of indentation and makes it clear which condition is actually satisfied.
Side note: obviously a && b && !c can be stated as a && b because !(a && b && c) and the use of else if. I would leave it there anyway because the compiler might optimize it and the code looks cleaner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With