Table of Contents
π 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.
Leave a Reply