When to use if or else If?

Is 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 below the example of where this doubt arose 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" } })
}
Author: Maniero, 2019-08-19

3 answers

TL; DR

When you use a else it is saying that it should only be evaluated if a previous if is false. If a previous if is true all subsequent else are 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 whether else has a if together or not, else alone is as if it has a if (true) implicit.

Explaining better

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

The else alone means that the condition is anything as long as it is not what has already determined the previous condition(s). When you have a else after just a if you have a binary situation, it's either one thing or it's the opposite of that condition. When it has several if (obviously with one else together after the first), the else can still be considered a binary situation, that is, it is it if all the other joints fail.

In general when you uses vários else ' together 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 initial if checks if item.Recursos has the text Usuario as its value. If he has this text, that is, the condition is true, he enters the block and performs what has been determined, right? Here 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 previous if, the fact that the first is true already ensures that the second is false, so you have no reason to evaluate it. And to avoid its evaluation we have to make everything turn into a single block.

The way it did works, but it is inefficient because it will evaluate without need. It has case that it does not work (depends on the condition). So let's go improve it?

@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 it will only evaluate the second one if the first one goes false, or it executes one block or executes the other, it can never do both, which is what we want. Improve.

Noticed that else doesn't need @. Using Razor gives you to understand even better that this is all a single block.

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

@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 on GitHub for future reference .

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

This form ensures that only one of these blocks will be executed because it is treated as a single thing.

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

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

I would worry about aligning the code better and avoiding these comments. If they are useful it is because the code is too complex and should give more semantics to them. If they only talk obviousness do not put them. I I did not read them because the condition is too obvious to me, there is nothing I can add in comment that makes it more readable, it is only polluting the code and creating a potential violation of DRY. See why not comment on the code?.

 7
Author: Maniero, 2020-06-11 14:45:34

Briefly..

You should use if when your algorithm has the ability to enter all ifs.

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

Else if turns out to be more perfomatic than multiples ifs , because when a condition is true, it enters the if , executes the code snippet and already skips all other ifs , because it you understand you've done the job.

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

 1
Author: Lucas, 2019-08-19 18:47:23

To exemplify with something compared in your day to day, imagine the situation:

You are in the market, and want to buy only a chocolate, waltz dream or Black Diamond. But you do not know which one is in the promotion.

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

Now, You are in the market, and you want to buy both chocolates if they are in the promotion.

Then you would use two if in this situation. Being able to buy both chocolates, in case they were on sale.

 0
Author: Leandro Kojima, 2019-08-20 12:25:13