IF condition - Good use practice

Asked

Viewed 212 times

0

During an encoding I had to carry out the development in the following way:

IF (Condicao1 = True)
  IF (Condicao2 = True)
    IF (Condicao3 = True)
       Imprime(Mensagem);

The way I’ve accomplished is considered best practice?

There would be a better way to accomplish this?

  • 1
  • 1
  • 3

    Know the logical operator and? If (condicao1 and condicao2 and condicao3) Imprime(Mensagem)

  • 2

    I do not know if using and is the most recommended. There may be cases where you do not want to validate an equality of all conditions in a unique way. I believe the switch can be the solution when you want to validate condition by condition, or the OR, depending on the case.

  • 2

    It is interesting that you specify which language you use. Some languages treat relational operators AND/OR in mode of short-circuit and thus a AND can function as several IF chained, but other languages do not use this mode.

1 answer

2

Apparently the way you structured is not the best. I say this because you do not use keys us ifs, which suggests they are only for what is being displayed in the code, i.e., validate whether the three conditions are true; being, prints. Thus, the best alternative is to use the and , as already said in a comment:

IF (Condicao1 && Condicao2 && Condicao3)
    Imprime(Mensagem);

However, if there are commands to be executed in case some of them are false, you structured in the correct way.

IF (Condicao1 = True) {
  IF (Condicao2 = True){
    IF (Condicao3 = True){
       Imprime(Mensagem);
    } else {
      // codigo
    }
  } else {
    //codigo
  }
} else {
  //código
}

In case you don’t need any "sinews", use the first form.

Browser other questions tagged

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