I have reasonably complicated logic for if statements. I am currently using:
if(numerical_evaluation) {
if ((!boolOne && boolTwo) || !boolThree){
//do stuff
}
}
where boolOne, boolTwo, and boolThree are logical operations (perhaps x < y
or 'myObject->getBool' etc).
I do not know a better way to make this easily readable without nesting the ||
condition within a third if
statement.
The reason I am having difficulty is that the or
operator makes it such that it seems a third if
statement might be warranted.
One option would be to do this.
Or, I could do something like
if(x <= y) {
bool boolFour = false;
if ((!boolOne && boolTwo))
boolFour = true;
if (boolFour || !boolThree){
//do stuff
}
}
Maybe even make a separate function to try to validate everything or combinations into a single return value?
Alternatively, I could attempt to restructure the code in such a way this is not required, which may require significant amounts of time to do.
My question: What is the best way to format complicated if
questions - which include more complicated evaluations than just if (!A && B && C)
variations? It seems things get hopelessly unreadable (especially when you have complicated evaluations for boolOne, boolTwo, etc) when you include ||
statements in combination with &&
statements into one line. Do the same principles from - Best way to format if statement with multiple conditions - apply here too or are there fundamental differences when using a variety of logical operators?
This:
bool boolFour = false;
if ((!boolOne && boolTwo))
boolFour = true;
can be expressed much more clearly as:
bool const boolFour = !boolOne && boolTwo;
By giving boolFour
a good, descriptive name, this approach of breaking down complex expressions and naming subexpressions can make code much more readable, much easier to understand, and much easier to debug.
If a complex expression is used in multiple places, a function should be used to encapsulate the common logic. If the expression is only used in one place, though, it is preferable to break up the expression locally and use named const variables, to keep the logic close to where it is used.