What is the best way to perform a dependent addition / subtraction operation?

4

It is common when you first encounter this doubt.

I have to perform an operation that is dependent on a condition:

Example 1

$operacao = 'somar';

$valor1 = 5;
$valor2 = 10;
$saldo = null;

if($operacao == 'somar'){
    $saldo = $valor1 + $valor2;
}else{
    $saldo = $valor1 - $valor2;
}

if($saldo != null){
    echo $saldo;
}

Example 2

$operacao = 'somar';

$valor1 = 5;
$valor2 = 10;
$saldo = null;

$valor2 *= (($operacao == 'somar') ? 1 : -1);
$saldo = $valor1 + $valor2;

if($saldo != null){
    echo $saldo;
}

Question

What is the best way to accomplish this task, so that it does not occupy many lines, not much memory?

    
asked by anonymous 26.01.2016 / 12:40

1 answer

3

It really tastes.

Many people like the first one because it seems clearer.

For me both are clear. Anyone who understands programming well can understand any of them well.

Some people will say that the second example is a clever way to do the same.

And this can be good or bad depending on the context. Many times the term is used pejoratively.

I would probably do so, after all the second example is not equivalent to the first:

$operacao = 'somar';

$valor1 = 5;
$valor2 = 10;
$saldo = null;

$saldo = $valor1 + $valor2 * ($operacao == 'somar' ? 1 : -1);

if($saldo != null) {
    echo $saldo;
}

Or you could use:

$saldo = $valor1 + ($operacao == 'somar' ? $valor2 : -$valor2);

Maybe I had a function for this, simplified:

function InvertSignalConditional($value, $condition) {
    return $condition ? -$value, $value)
}

Notice the inversion I made to be correct. After all you want the inversion if the condition is true.

In some cases you can opt for one more than the other because you are more expressive of what you intend. Some will say that the first example of the question is more expressive. This is an imperative way of seeing things. For those who know functional programming, which is much more expressive than the imperative, you know that the second example is preferred.

    
26.01.2016 / 12:54