Breaking Down Complex Boolean Logic for Readability

πŸ“– 2 minutes read

When you have complex boolean conditions, don’t cram them into one giant expression. Break them into named variables that explain what you’re checking, not just how.

Before (hard to read)

if ($record->getConfig()?->getKey() === null && is_string($record->api_plugin) && app(ConfigRepository::class)->configsFor($record->api_plugin)->containsOneItem() && method_exists($record->api_plugin, 'getClients') && app($record->api_plugin)->getClients()->contains(fn (Client $client) => !$client->getConfig() instanceof DynamicConfig) === false) {
    $record->setConfig(app(ConfigRepository::class)->configsFor($record->api_plugin)->first());
}

This works, but it’s a wall of logic. What are we actually checking?

After (self-documenting)

if ($record->getConfig()?->getKey() === null && is_string($record->api_plugin)) {
    $configs = app(ConfigRepository::class)->configsFor($record->api_plugin);
    
    $hasOnlyOneConfig = $configs->containsOneItem();
    $pluginSupportsClients = method_exists($record->api_plugin, 'getClients');
    
    $allClientsUseDynamicConfigs = $pluginSupportsClients
        && app($record->api_plugin)->getClients()
            ->contains(fn (Client $client) => !$client->getConfig() instanceof DynamicConfig) === false;
    
    if ($hasOnlyOneConfig && $pluginSupportsClients && $allClientsUseDynamicConfigs) {
        $record->setConfig($configs->first());
    }
}

Now it’s obvious:

  • We’re checking if there’s only one config
  • We’re checking if the plugin supports clients
  • We’re checking if all clients use dynamic configs

The variable names document the intent, not just the implementation. Future-you (or your teammates) will thank you.

Bonus: This makes debugging easier. You can dump individual conditions to see which one is failing.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *