Code bloopers - part 1 (PHP & Laravel)

SHARE:
Facebook logo
Twitter logo
Linkedin logo
Working as a development company in an outsourcing world can be fun, but working on legacy code is often the opposite. That said, those projects have their bright sides. For example, you can find a lot of funky stuff in the code to provide great examples of how not to code. 
Sharing is caring, and we wanted to use this opportunity to provide you with some of those examples, along with a few useful suggestions. 

Hardcoding sensitive data

We’ve found a lot of hardcoded credentials, addresses, and all other kinds of sensitive data in the code we’ve inherited. This is really bad practice, which can make maintaining an application fairly difficult and potentially cause some serious security vulnerabilities.
Example:
1
2
3
4
5
6
7
function debugEnable()
{
    if ((\Request::getClientIp(true) == '219.206.139.228') ||  App::environment('local')) {
        return true;
    }
    return false;
}
There are plenty of reasons why not to hardcode your IP address:
  • This doesn't guarantee exclusive access.
  • Your IP will probably change at some point.
  • Hardcoding is generally a bad idea.
  • And last but not least, your IP can show up on someone’s blog post.
  • One more thing, try to avoid writing if statements that return a boolean value. Instead, you can simply return the condition of the statement. This is a small step for a programmer, but a giant leap for code readability. If using an IP address is the only way to do this, for whatever reason, we suggest you put it in an .env file:
    1
    2
    3
    4
    5
    function isDebugEnabled()
    {
       return Request::getClientIp(true) == env('MAGIC_IP_ADDRESS', '127.0.0.1')
           || App::environment('local');
    }
    Or, if you work with Laravel, then simply use config('app.debug') and avoid involving an IP for this purpose.

    Code redundancy

    One of the principles behind clean code is to avoid repeating yourself. Here’s a simple example of unnecessary code redundancy, and it’s quite common in the code that we’ve worked on:
    1
    2
    3
    4
    5
    if ($result) {
        return response()->json(['result' => $result]);
    } else {
        return response()->json(['result' => []]);
    }
    Simply don't do it. Be concise and, wherever possible, try to keep repetition to a minimum:
    1
    2
    3
    return response()->json([
        'result' => $result ?? []
    ]);
    Or, if you work with older versions of PHP:
    1
    2
    3
    4
    $result = empty($result) ? [] : $result;
    return response()->json([
        'result' => $result
    ]);
    By following this principle, you will have a shorter and cleaner code.

    Zero information response

    Responses that your API returns should have appropriate status codes and provide descriptive error messages so that anyone who uses your API can realise immediately what has gone wrong and why. 
    Take a look at this example:
    1
    2
    3
    if ($tempData == null) {
        return response()->json(['error' => 'error']);
    }
    If something goes wrong we’ll get a response with status code 200 and:
    1
    2
    3
    {
      "error":"error"
    }
    When you see something like this, you can’t help but think “For goodness’ sake, think of a better error message, and please use a more appropriate status code.” 
    Also, it's a good idea to use is_null() instead of comparing variables with null:
    1
    2
    3
    4
    5
    if (is_null($tempData)) {
        return response()->json([
            'error' => 'Temp data not found'
        ], 404);
    }

    Bad variables and method names

    There is a strong probability that the code you’re working on will be read many more times than it will be written or edited. No matter whether it’s destined to be read by you or perhaps by other programmers, it’s important to make it understandable and easy to read. The more time you spend on understanding what the code does, the longer it will take to modify and extend it. One of the most obvious signatures of messy code is the poor naming of variables and methods. 
    For example, we have a controller method for matching an authenticated user with his role and permissions as an array:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public function getMe()
    {
        $me = auth('api')->user();
        $role = $me->role()->get();
        $permissions = $role->permissions();
        $me_data = $me->toArray();
        $me_data['role'] = $role->toArray();
        $me_data['role']['permissions'] = $permissions->toArray();
        return response()->json($me_data);
    }
    The problems here are:
  • The method name getMe doesn’t give us any information about what we should get. Would it be a class parameter $me? Or possibly an instance of that class? We can only speculate until we’ve read the entire method. We could use something like getAuthUser.
  • Inconsistency in naming style. If you use a camelCase then don’t mix it with snake_case. Choose one and stick with it for the entire project.
  • auth('api')->user() can return null if a user is not authenticated, and that can cause an error.
  • We don’t have to convert all these objects to the array individually. Laravel can handle this for us.
  • We can also use eager loading here.
  • We suggest writing it like this:
    1
    2
    3
    4
    5
    6
    7
    8
    public function getAuthUser()
    {
        $user = auth('api')->user();
        if($user){
            $user->load('role.permissions');
        }
        return response()->json($user);
    }

    Overusing elseif statements

    If you end up with more than one elseif statement, there is a good chance that the logic behind your code could be simpler. Here’s a perfect example of this:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public function getNumberBasedTitle($no)
    {
        if($no < 20)
            return 10;
        elseif($no < 30)
            return 20;
        elseif($no < 40)
            return 30;
        elseif($no < 50)
            return 40;
        elseif($no < 100)
            return 50;
        elseif($no < 150)
            return 100;
        elseif($no < 200)
            return 150;
        else
            return 200;
    }
    Okay. This is funny. $no kind of reminds us of
    This method is used to round the size of a list depending on how many elements we can provide for it. Yeah, there are a lot of things wrong here:
  • Method name - roundListSize would be more appropriate because it's more descriptive and makes it easier to guess the type of result.
  • Parameter name - instead of $no, we should use something like $elementsCount.
  • A Bunch of statements - Do we really need to check all of these conditions? Can we calculate the result instead? In this particular case, we obviously can.
  • Hardcoded values - whenever possible, we should use named constants.
  • This is our take on rewriting the method.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    private function roundListSize($elementsCount)
    {
        if ($elementsCount < MIN_LIST_SIZE) {
            return MIN_LIST_SIZE;
        }
        if ($elementsCount > MAX_LIST_SIZE) {
            return MAX_LIST_SIZE;
        }
        $modulus = $elementsCount > 50 ? 50 : 10;
        return $elementsCount - $elementsCount % $modulus;
    }
    How would you refactor it?