Here is some hypothetical code sample:
if (e.KeyCode == Keys.Enter)
{
if (this.CurrentElement == null) {
return false;}
if (this.CurrentElement == this.MasterElement) {
return false;}
if (!Validator.Exist (this.CurrentElement)) {
return false;}
if (!Identifier.IsPictureElement (this.CurrentElement)) {
return false;}
this.FlattenObjects(this.CurrentElement);
}
VS
if (e.KeyCode == Keys.Enter)
{
if (this.CurrentElement != null) {
if (this.CurrentElement != this.MasterElement) {
if (Validator.Exist (this.CurrentElement)) {
if (Identifier.IsPictureElement (this.CurrentElement)) {
this.FlattenObjects(this.CurrentElement);}}}}}}
}
Which one do you think is better in terms of readability, maintenance, etc?
Also the 2nd example can be formatted differently via the different use of parenthesis.
A nested if statement is an if statement placed inside another if statement. Nested if statements are often used when you must test a combination of conditions before deciding on the proper action.
An early return, or “return early” is an approach to keep readability in functions and methods. It is always considered a wise choice to return early if simple conditions apply that can be checked at the beginning of a method.
Avoid using nested if-else statements. Keep the code linear and straightforward. Utilize creating functions/methods. Compare it when we try to use an if-else statement that is nested and that does not utilize the power of the return statement, We get this (Code 1.4).
Early return is a situation where the renter returns the rental vehicle before the agreed drop-off time. The supplier may give the renter a refund or charge an Early Return Fee, depending on the supplier's terms and conditions.
Early returns are much more readable.
Whenever you get more than four or five levels of nesting inside a method, it's time to refactor that method.
A single if
with an ||
clause can sometimes be more readable:
if (this.CurrentElement == null
|| this.CurrentElement == this.MasterElement
|| !Validator.Exist(this.CurrentElement)
|| !Identifier.IsPictureElement(this.CurrentElement))
return false;
The first example is better in every way. It's simpler, and easier to read. Some people say that every function should have a single return point; this example shows clearly why those people are wrong.
PS Personally I would remove all those superfluous curly brackets:
if (this.CurrentElement == null) return false;
etc. This makes it even simpler, and even easier to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With