Stop using Else in your programs

When I was just starting to program, I would like to find someone who could talk about the main pitfalls that I will encounter when creating my first site.







Then one of the problems was the excessive use of else when writing conditional expressions. Today, I myself constantly see how other people fall into the same trap, so I decided to write this post.







Disclaimer: The following is solely my subjective opinion.







The trick I'm going to talk about doesn't always work and sometimes you still have to use else . In other cases, dropping else will help make the code cleaner.

















Security Expressions



According to Wikipedia , “guard clause” is a preliminary check of certain conditions in order to avoid errors later.







Let's look at the above on the fingers. So, we check some conditions (somewhere at the beginning of the code) in order not to deal with errors during the movement of the program execution flow.







Ideally, we would like the main logic of the program to be located after all data checks.







Let's look at an example: a site where one of the sections is available only to premium customers and only after 12 hours.







<?php

if ($user != null) {
    if (time() >= strtotime('12 pm')) {
        if ($user->hasAccess(UserType.PREMIUM)) {
            if ($store->hasItemsInStock()) {
                //  .
            } else {
                return 'We are completely sold out.';
            }
        } else {
            return 'You do not have premium access to our website.';
        }
    } else {
        return 'This section is not opened before 12PM';
    }
} else {
    return 'You are not signed in.';
}

      
      





, .







, else, .







, . , .







:







<?php

if (condition1()) {
    return ...;
}

if (condition2()) {
    return ...;
}

//    .
doSomething();
      
      





:







<?php

if ($user == null) {
    return 'You are not signed in.';
}

if (time() < strtotime('12 pm')) { 
    return 'This section is not opened before 12PM';
}

if (!$user->hasAccess(UserType.PREMIUM)) {
    return 'You do not have premium access to our website';
}

if (!$store->hasItemsInStock()) {
    return 'We are completely sold out.';
}

//  .
      
      





, , . .. , , , .







, .









, : « 6 ?»







. , , .







, .








All Articles