When to use if or Else If?

Asked

Viewed 653 times

2

It’s a pretty silly thing, but during my writing I came across the following question: When is it really necessary to use if's or else if's in my code? Is there any impact on performance?

I will put down the example from where this doubt came to me.

@if (item.Recursos == "Usuario") //Se o tipo de recurso for "Usuario", ele vai perguntar qual foi o usuário criado antes de finalizar
{
    <p style="font-size: 14px; font-weight:bold;">Usuario Criado:</p>
    @Html.EditorFor(model => model.UsuarioCriado, new { htmlAttributes = new { @class = "form-control" } })
}

@if (item.Recursos == "E-mail") //Se o tipo de recurso for "Emmail", ele vai perguntar qual foi o e-mail criado antes de finalizar
{
    <p style="font-size: 14px; font-weight:bold;">E-mail Criado:</p>
    @Html.EditorFor(model => model.EmailCriado, new { htmlAttributes = new { @class = "form-control" } })
}

@if (item.Recursos == "Desktop" || item.Recursos == "Desktop (Novo") //Se o tipo de recurso for "Desktop" ou "Desktop (Novo)", ele vai perguntar qual o nome/número da maquina antes de finalizar
{
    <p style="font-size: 14px; font-weight:bold;">Nome do Desktop:</p>
    @Html.EditorFor(model => model.NomeDesktop, new { htmlAttributes = new { @class = "form-control" } })
}

@if (item.Recursos == "Notebook") //Se o tipo de recurso for "Notebook", ele vai perguntar qual o nome/número da maquina antes de finalizar
{
    <p style="font-size: 14px; font-weight:bold;">Nome do Notebook:</p>
    @Html.EditorFor(model => model.NomeNotebook, new { htmlAttributes = new { @class = "form-control" } })
}

3 answers

7


TL; DR

When you wear one else is saying that it should only be evaluated if a if previous is false. If a if previous is true all else following will be ignored.

Understand that evaluating is checking the condition, not executing the command block that will only occur if that specific condition is true.

It makes no difference if the else has a if together or not, the else alone is like having a if (true) implicit.

Explaining better

The question is actually about using the else. It should be used whenever you want it to happen after eliminating a possible condition, i.e., you want to test something excluding what has already been tested that you already know is not that condition. It’s like a system of knockout where something leaves the play because it didn’t hit a certain mark. The else is used when there are conditions mutually exclusive.

The else alone means that the condition is anything but that which has determined the previous condition(s)(s). When you have a else after only one if you have a binary situation, either it is a thing or it is the opposite of that condition. When you have several if (obviously with a else together after the first), the else can still be considered a binary situation, i.e., it is it if all the other joints fail.

Usually when you use vários Else` together it is because the conditions are very similar and are testing the same thing with different values, it can be a range of values for example.

Now let’s take your example as a concrete case to demonstrate. The if initial checks whether item.Recursos has as value the text Usuario. If he has this text, that is, the condition is true, he enters the block and executes what has been determined, right? Then we go to the next if. It also checks the content of item.Recursos. If it has that value initially tested, can it have another value? No, right? That is, it is mutually exclusive with the if previous, the fact that the first is true already ensures that the second is false, so there is no reason to evaluate it. And to avoid your assessment we have to make it all one block.

The way it did works, but is inefficient because it will evaluate without need. There is case that does not work (depends on the condition). So let’s make it better?

@if (item.Recursos == "Usuario") {
    <p style="font-size: 14px; font-weight:bold;">Usuario Criado:</p>
    @Html.EditorFor(model => model.UsuarioCriado, new { htmlAttributes = new { @class = "form-control" } })
} else if (item.Recursos == "E-mail") {
    <p style="font-size: 14px; font-weight:bold;">E-mail Criado:</p>
    @Html.EditorFor(model => model.EmailCriado, new { htmlAttributes = new { @class = "form-control" } })
}

So now he will only evaluate the second if the first gives false, or runs a block or executes the other, you can never do both, which is what we want. Improved.

Noted that the elsedoesn’t need the @. Using Razor you can understand even better that this is all one block.

Now we can analyze the next if. He is mutually exclusive in relation to the previous ones, so we can do the same thing with him and the others.

@if (item.Recursos == "Usuario") {
    <p style="font-size: 14px; font-weight:bold;">Usuario Criado:</p>
    @Html.EditorFor(model => model.UsuarioCriado, new { htmlAttributes = new { @class = "form-control" } })
} else if (item.Recursos == "E-mail") {
    <p style="font-size: 14px; font-weight:bold;">E-mail Criado:</p>
    @Html.EditorFor(model => model.EmailCriado, new { htmlAttributes = new { @class = "form-control" } })
} else if (item.Recursos == "Desktop" || item.Recursos == "Desktop (Novo") {
    <p style="font-size: 14px; font-weight:bold;">Nome do Desktop:</p>
    @Html.EditorFor(model => model.NomeDesktop, new { htmlAttributes = new { @class = "form-control" } })
} else if (item.Recursos == "Notebook")
    <p style="font-size: 14px; font-weight:bold;">Nome do Notebook:</p>
    @Html.EditorFor(model => model.NomeNotebook, new { htmlAttributes = new { @class = "form-control" } })
}

I put in the Github for future reference.

Now only enters one of them, all are mutually exclusive, and one of them accepts two variations at the same time (has a ||) . If you think about the use of else is equal to a ||, because they both have something called short-circuit, that is, when one becomes true no longer need to evaluate the rest (in the case of the && is different, but this is another matter and has no equivalent with the else).

This way ensures that only one of these blocks will run because it is treated as a single thing.

If the checks were independent, that is, any one could be executed even if another had already been executed, then it could not put everything as one thing and the else would be inappropriate. It’s all about understanding the problem and doing what is expected of it. There is a case to do more than one would be a problem. This is a case that is only more efficient.

This is a case that could use a switch because it just always compares the same variable just by checking the equality, exactly for what the if was created. The switchtends to be more efficient than the if when it can be applied.

I would worry about aligning the code better and avoiding those comments. If they are useful it is because the code is too complex and should give them more semantics. If they only speak obviousness do not put them. I didn’t read them because the condition is too obvious to me, there’s nothing you can add in a comment that makes it more readable, it’s just polluting the code and creating a potential violation of DRY. Behold Why not comment on the code?.

1

Briefly..

You must use the if when its algorithm has the possibility to enter in all ifs.

When your algorithm should not enter multiples ifs, you use the Else if or switch case.

Else if ends up being more perfomatic than multiples ifs, because when a condition is true, it enters the if, executes the code snippet and already skips all the others ifs, because he understands that he’s done the job.

In your case, it would be interesting to use switch case, because you are checking the same variable item. Resources

0

To illustrate with something compared to your daily life, imagine the situation:

You are in the market, and want to buy only one chocolate, waltz dream or black diamond. But you do not know which one is on sale.

Then you would use if and if else. In this case, you would buy only one chocolate.

Now, you’re in the market, and you want to buy the two chocolates if they’re on sale.

Then you’d use two if in this situation. You can buy both chocolates if they were on sale.

Browser other questions tagged

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