This may be obvious to some, but I have approached the same problem in many different ways without thinking too much about it over the years. In an effort to write cleaner easier code to read I settled n a pattern I am happy with, so I’d like to share.
The typical problem: You have code (Language doesn’t matter much) that accepts a number parameters / inputs. You can;t always rely on those inputs being there, so you need to have defaults. There are several things to check for before going to your default settings. Might be check if the input exists, if it matches certain values, and if it’s a certain variable type.
you could end up writing it like this:
if(isset($_POST[‘display’])){
if($_POST[‘display’] == ‘[]‘){
$display = ‘default’;
}else{
$display = json_decode($_POST[‘display’]);
}
}else{
$display = ‘default’;
}
?>
it’s not THAT bad, but it definitely has more conditional branches than necessary, and when you have several variables to do that sort of thing to, it gets ugly fast.
the alternative I like is to set your default, run your check on the input, and only override the default if it passes all the checks. Like so:
if(isset($_POST[‘display’])){
if($_POST[‘display’] != ‘[]‘){
$display = json_decode($_POST[‘display’]);
}
}
Then when you have several variables / inputs you can define all the defaults first and together in a “Configuration Defaults” section then have all of the input override check after.
Hopefully the process of writing this post will prevent me from ever using the much uglier method. Enjoy.






Leave a reply