1

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.

1
  • 4
    IMO this is clear enough as it is. Commented Nov 18, 2014 at 22:32

2 Answers 2

2

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]));
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

that's good but there may be an occasional different physical quantity -- updated the question ...
I suppose it may be when I have more unit systems, but so far I don't see that happening
implementing it now. btw, it took me a minute to figure out why info[1] wouldn't parse -- no $!
sorry, typed that from my phone :)
1

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!
    }   
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.