How to remove code duplication in this PHP code?

78 views Asked by At

Is there a good way to remove duplication in this code:

        if ($design->unit_system=="English")
        {
            define('LIMIT_AF', '200');
            define('LIMIT_BF', '0');
            define('LIMIT_CM', '50');
            define('LIMIT_DB', '50');
            define('LIMIT_FB', '100');                            
        }
        else if ($design->unit_system=="Metric")
        {
            define('LIMIT_AF', convert(200, 'gpm', 'm3h'));
            define('LIMIT_BF', convert(0, 'gpm', 'm3h'));
            define('LIMIT_CM', convert(50, 'gpm', 'm3h'));
            define('LIMIT_DB', convert(50, 'psi', 'bar'));
            define('LIMIT_FB', convert(100, 'psi', 'bar'));
        }

I am struggling as to if any effort will be more complicated than what I have now.

2

There are 2 answers

4
JohnKiller On BEST ANSWER

What about this - updated according to OP edits:

$constants = array(
    'LIMIT_AF' => array(200, 'gpm', 'm3h'),
    'LIMIT_BF' => array(0, 'gpm', 'm3h'),
    'LIMIT_CM' => array(50, 'gpm', 'm3h'),
    'LIMIT_DB' => array(50, 'psi', 'bar'),
    'LIMIT_FB' => array(100, 'psi', 'bar'),
);

foreach($constants as $key => $info){
    if($design->unit_system=="English"){
        define($key, $info[0]);
    }elseif($design->unit_system=="Metric"){
        define($key, convert($info[0], $info[1], $info[2]));
    }
}
0
AMADANON Inc. On

This to me yells "configuration file".

Alternatively, you could put the values in an array, and then process them after:

$settings=array('LIMIT_AF'=>200,...);
foreach ($settings as $name=>$value) {
    if (design->unit_system=="English") {
        define($name,$value);
    } else if ($design->unit_system=="Metric") {
        define($name,convert($value,'gpm','m3h'));
    } else {
        ## DONT FORGET TO THROW AN EXCEPTION rather than have these undefined!
    }   
}