Is there any way to reduce the if’s of my code?

Asked

Viewed 102 times

-2

function updateUser($usuario, $senha, $adm){
    //Atualiza informações sobre o usuário
    $sql_query; 
    $q_senha = ""; 
    $q_adm = "";
    $dot = "";
    if(!empty($senha)){
        $q_senha = "senha=md5('$senha')";
    }
    if($adm != NULL){
        $q_adm = "adm='$adm'";
    }
    if($adm != NULL and !empty($senha)){
        $dot = ",";
    }
    $sql_query = "update tb_users set ".$q_senha.$dot." ".$q_adm." where usuario='$usuario';";
    return $this->execute($sql_query);
}

I know it’s a simple situation and from what I read the Strategy is an efficient way to case with many if’s, and that’s not my case. But I believe I have some way to reduce through a good use of SQL. But I found nothing on the internet about

1 answer

3


Have how you use ternary operator, follow the example:

function updateUser($usuario, $senha, $adm){
    //Atualiza informações sobre o usuário
    $q_senha = (!empty($senha)) ? "senha=md5('$senha')" : "";
    $q_adm = ($adm != NULL) ? "adm='$adm'" : "";
    $dot = ($adm != NULL and !empty($senha)) ? "," : "";

    $sql_query = "update tb_users set ".$q_senha.$dot." ".$q_adm." where usuario='$usuario';";
    return $this->execute($sql_query);
}

You can read more about the ternary operator here.

  • 1

    Its alternative makes it visually much more elegant, but I wonder if there is a different script for not doing this gambiarra. That’s how I see her kkk

  • 1

    It’s not unnecessary $sql_query; at the beginning of the method!?

  • Yes, it is @Rbz.

  • @Matheushenrique this ends up making your question too wide.

  • 1

    @Matheushenrique There is no way to know which is the best form and even if it is "gambiarra" what you did, since, we do not have all your code. The way Junior did has "gone down" as he wanted.

  • 1

    @Rbz, both forms use 3 conditional which makes me think there was no reduction.

  • @Leocaracciolo So, I put quotes on "decreased", because it decreased visually. rs But it is true, did not reduce conditions.

  • @Leocaracciolo I took into consideration the part of the title of the question where is described "reduce if’s". What in fact was done, the if’s were exchanged for ternary operators.

  • Good, really what gives to improve is to exchange the if’s for ternary operators. Thank you Junior and to all.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.