Break Up Compound Conditions into Separate Sub-conditions [VD9]

Break Up Compound Conditions into Separate Sub-conditions [VD9]

Tip VD9

Just like a single boolean variable for a simple boolean condition can communicate more than not having a well-named variable, breaking up sub-conditions of a compound boolean expression into separate variables can create more self-documenting code for a reader.

Some boolean conditions just involve one underlying condition. However, it is common for “compound” boolean conditions to exist that are made up of multiple sub-conditions.

When dealing with complex boolean expressions, it's often helpful to break them down into smaller, more manageable parts. By introducing additional intermediate local boolean variables for certain sub-conditions, you can make the overall expression easier to read, understand, and debug. These intermediate variables can then be combined to form the final condition for a single boolean variable used in an if statement. Note that you don't necessarily need to have a separate local boolean variable for each individual boolean comparison - if there are multiple comparisons that are clearly closely related, it's may better to just have a single local boolean variable for that compound condition rather than introduce names that would be awkward to understand.

Finally, having well-named boolean variables for conditions is a way to help ensure that you actually understand the problem you're solving. Difficulties in naming a variable are a sign that the programmer does not yet fully understand the problem. In such cases, if code appears to work, it might not actually - so spend time double-checking your logic and trying to create well-named variables to communicate that understanding.

Bottom line - don't be afraid to introduce additional intermediate local boolean variables to make complex boolean expressions easier to read, understand, and debug.

Related content