Search code examples
phpcode-duplication

How to remove code duplication in this PHP code?


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.


Solution

  • 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]));
        }
    }