27
Mar

Config Defaults with OverRides pattern

   Posted by: admin   in Software Development

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:

<?php
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:

$display = ‘default’;
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.

Share and Enjoy:
  • Digg
  • Technorati
  • Google Bookmarks
  • del.icio.us
  • Facebook
  • StumbleUpon
This entry was posted on Friday, March 27th, 2009 at 8:29 am and is filed under Software Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a reply

Name (*)
Mail (will not be published) (*)
URI
Comment