In general, I believe it is easier to read a single if
instead of one or more of them.
Here are some scenarios to compare the two options.
Many conditions
Thinking of cases with more if
You’ll see that this:
if ( A > X AND A > Y AND A > Z)
instrucao aqui....
ENDIF
It ends up being simpler to understand that:
if ( A > X )
if ( A > Y)
if ( A > Z)
instrucao aqui....
ENDIF
ENDIF
ENDIF
Extract method
Using a single if
, you can simplify the meaning of the conditions by creating a single method, which is not possible with a if
within another if
.
As an example:
if ( A > X AND A > Y)
instrucao aqui....
ENDIF
You could have a method isAMaiorQueYeX(A, X, Y)
, giving an explanatory name to the condition:
if ( isAMaiorQueYeX(A, X, Y))
instrucao aqui....
ENDIF
For more complex condition cases, this type of artifice becomes increasingly useful.
Code debugging and errors
A small advantage that exists using a single if
is in troubleshooting. If there is a "Nullpointer" error or something like that, the line shown in the error will straightforward in the problematic condition. Now, using multiple conditions on the same line, you will not be sure which condition caused the problem and will have to debug the application to understand.
And speaking of debugging, it’s also facilitated with several if
s. As debugging is done line by line, it is a little easier to observe what is happening in the code.
thanks. in that case even the conditions/checks were small but I came across very large conditions/checks hence the doubt.
– Luís Almeida