Posts tagged with readability

Making overloaded functions readable

Sometimes you might allow a function to accept multiple data types. I don't know for certain if it's the correct term but for the remainder of this post I'm going to call such a function overloaded. In this post I'd like to show you a little trick to make overloaded functions more readable.

Let's first take a look at a function in Laravel that accepts multiple data types. To store something in a session you can pass a key and value to the session helper:

session($key, $value);

But you can also give it an array:

session(['key' => 'value']);

Now behind the scenes Laravel is calling a put function. It could have been implemented like this:

public function put($key, $value = null)
{
    if (is_array($key)) {
       foreach ($key as $arrayKey => $arrayValue) {
           $this->set($arrayKey, $arrayValue);
       }
    }
    else {
       $this->set($key, $value);
    }
}

In the function above there's a path for doing the work if an array was passed and another path for when (hopefully) a string was passed.

The actual implementation is a bit different (and much better):

public function put($key, $value = null)
{
    if (! is_array($key)) {
        $key = [$key => $value];
    }

    foreach ($key as $arrayKey => $arrayValue) {
        $this->set($arrayKey, $arrayValue);
    }
}

The cool thing to note is that what the function first converts the passed arguments to a certain format (in this case an array) and then perform the work on the format. The actual work, the call to $this->set is only coded up once. When reading the source code of Laravel you'll often come across this pattern.

Let's take a look at another real life example to make the benefit of this pattern more clear. This next snippet is taken from a recent PR to the laravel-permission package. It aims to a add a query scope to a User model to perform the query only on users that have the given role(s). Roles can be passed through as an array, a string or an instance of Role.

/**
 * Scope the user query to certain roles only.
 *
 * @param string|array|Role|\Illuminate\Support\Collection $roles
 *
 * @return bool
 */
public function scopeRole($query, $roles)
{
    if (is_string($roles)) {
        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where('name', $roles);
        });
    }

    if ($roles instanceof Role) {
        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where('id', $roles->id);
        });
    }

    if (is_array($roles)) {
        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where(function ($query) use ($roles) {
                foreach ($roles as $role) {
                    if (is_string($role)) {
                        $query->orWhere('name', $role);
                    }

                    if ($role instanceof Role) {
                        $query->orWhere('id', $role->id);
                    }
                }
            });
        });
    }

    return $query;
}

The query is being build up in a few different ways depending on the type of the argument being passed through. The readability of this code can vastly be improved by:

  • first converting all arguments to a single format to work with
  • performing the work on that format
public function scopeRole($query, $roles)
{
    if ($roles instanceof Collection) {
        $roles = $roles->toArray();
    }

    if (! is_array($roles)) {
        $roles = [$roles];
    }

    $roles = array_map(function ($role) {
        if ($role instanceof Role) {
            return $role;
        }

        return app(Role::class)->findByName($role);
    }, $roles);

    return $query->whereHas('roles', function ($query) use ($roles) {
        $query->where(function ($query) use ($roles) {
            foreach ($roles as $role) {
                $query->orWhere('id', $role->id);
            }
        });
    });
}

In the snippet above all input, no matter what type is being passed through, is first converted to an array with Role objects. U sing that array the query is only being build up once. I should mention that the author of the PR did provide a good set of tests so it was very easy to refactor the code.

Let's do one more example. This one's taken from our laravel-fractal package which aims to make working with Fractal more developer friendly.

To return a response with json data you can to this in a Laravel app.

$books = fractal($books, new BookTransformer())->toArray();

return response()->json($books);

In the last version of our package a respond() method was added. Here's the equivalent code using the respond method.

return fractal($books, new BookTransformer())->respond();

You can pass a response code as the first parameter and optionally some headers as the second

return fractal($books, new BookTransformer())->respond(403, [
    'a-header' => 'a value',
    'another-header' => 'another value',
]);

You can also set the status code and the headers using a callback:

use Illuminate\Http\JsonResponse;

return fractal($books, new BookTransformer())->respond(function(JsonResponse $response) {
    $response
        ->setStatusCode(403)
        ->header('a-header', 'a value')
        ->withHeaders([
            'another-header' => 'another value',
            'yet-another-header' => 'yet another value',
        ]);
});

This is original code for the function that was submitted through a PR (slightly redacted):

public function respond($callbackOrStatusCode = 200, $callbackOrHeaders = [])
{
    $response = new JsonResponse();

    $response->setData($this->createData()->toArray());

    if (is_callable($callbackOrStatusCode)) {
        $callbackOrStatusCode($response);
    } else {
        $response->code($callbackOrStatusCode);

        if (is_callable($callbackOrHeaders)) {
            $callbackOrHeaders($response);
        } else {
            $response->withHeaders($callbackOrHeaders);
        }
    }

    return $response;
}

Sure, that code does the job. Unfortunately the real work (in this case: modifying $response) is done all over the place. Let's refactor! In the code below we're going to convert all input to callables first and then use them to modify $response.

public function respond($statusCode = 200, $headers = [])
{
    $response = new JsonResponse();

    $response->setData($this->createData()->toArray());

    if (is_int($statusCode)) {
        $statusCode = function (JsonResponse $response) use ($statusCode) {
            return $response->setStatusCode($statusCode);
        };
    }

    if (is_array($headers)) {
        $headers = function (JsonResponse $response) use ($headers) {
            return $response->withHeaders($headers);
        };
    }

    if (is_callable($statusCode)) {
        $statusCode($response);
    }

    if (is_callable($headers)) {
        $headers($response);
    }

    return $response;
}

Hopefully you can use this neat little trick to improve the readability of your code as well.

Read more

Human Readable AJAX Requests

Zach Silveira made a new JavaScript library that aims to make ajax requests much more readable. Under the hood template literals are used.

Anyone familiar with HTTP requests knows what each line in chrome's network tab means. It's too bad we can't copy and paste this into our code and do that exact request..... But we can (almost), if my idea pans out! Take a look at what I'm proposing:
request`  
  url: http://test.app/settings/user/19
  method: PATCH
  headers: ${{ 
    Authorization: 'Bearer: token' 
  }}
  body: ${{ name: 'Bob' }}
`

https://zach.codes/human-readable-ajax-requests/

Read more

Join thousands of developers

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages.

No spam. Unsubscribe anytime. You can also follow me on X.

When are single-character variable names acceptable?

Generally I don't like to abbreviate variable names. This answer on Quora lists a few situations where an abbreviation is probably ok.

There is a simple (but unsatisfying) answer to all questions of this form: they are acceptable when they would make the code clearer.

This can happen in a few ways. The most common, as you noted, is convention: i, j, k for loop variables, x and y for coordinates, e for exceptions, f and g for functions and so on.

Another is structure. Often, the broad structure of an expression is more important than its contents. Using shorter variable names makes it easier to read at a glance. I think this is often more important than being easy to read in detail!

If a variable has a very small scope—say one or two lines at most—and it's easy to see where it comes from, having a long name is just noise.

https://www.quora.com/When-are-single-character-variable-names-acceptable/answer/Tikhon-Jelvis

Read more

How to design words

John Saito, a designer at Dropbox, wrote down some very useful tips to improve the text in your UI.

Technically speaking, I’m a writer. I get paid to write words. But here’s something most people don’t know about me: I hate to read. ... You see, I mostly write interface text for apps and websites. It’s a style of writing where brevity beats brilliance, and every character counts. Writing interface text is actually a lot like design—designing words for people who hate to read.

https://medium.com/@jsaito/how-to-design-words-63d6965051e9

Read more

Improving readability using array_filter

In this post I'd like to share a quick tip on how you can improve the readability of your code with array_filter.

Today I was working on some code that looked something like this:

class Address
{
    ...

    public function toArray()
    {
        $address = [
            'name' => $this->name,
            'street' => $this->street,
            'location' => $this->location,
        ];

        if ($this->line2 != '') {
            $address['line2'] = $this->line2;
        }

        if ($this->busNumber != '') {
            $address['busNumber'] = $this->busNumber;
        }

        if ($this->country != '') {
            $address['country'] = $this->country;
        }


        return $address;
    }
}

Did you know that you can use array_filter to clean this up? I didn't, until today.

When that function is called without a second argument it will remove any element that contains a falsy value (so null, or an empty string) Here's the refactored, equivalent code:

class Address
{
    ...

    public function toArray()
    {
        return array_filter([
            'name' => $this->name,
            'street' => $this->street,
            'line2' => $this->line2,
            'busNumber' => $this->busNumber,
            'location' => $this->location,
            'country' => $this->country,
        ]);
    }
}

That's much better!

Just be careful when using this with numeric data that you want to keep in the array. 0 is considered as a falsy value too, so it'll be removed as well.

Read more

How to save a kitten by writing clean code

Some great coding tips written down by Joeri Timmermans on the Intracto blog.

As a developer it's your duty to take good care of your code. It's not enough for your code to work, you also have to make sure it's well written and readable. If we spend 10 times more time reading code versus actually writing it, this means the readability of your code is directly related to your output and the output of your co-workers. So providing cheaper reads will not only create happier co-workers, but also increase the productivity of your whole team.

http://blog.intracto.com/how-to-save-a-kitten-by-writing-clean-code

Read more

How to make syntax highlighting more useful

We think syntax highlighting makes the structure of code easier to understand. But as it stands, we highlight the obvious (like the word function) and leave most of the content in black. Rather than highlighting the differences between currentIndex and the keyword function, we could highlight the difference between currentIndex and randomIndex. Here’s what that might look like:1-TVSPOYO1z8GOVs3tuxNRqA
https://medium.com/@evnbr/coding-in-color-3a6db2743a1e

Read more

Making string concatenation readable in PHP

by Freek Van der Herten – 2 minute read

Probably all PHP developers know how to concatenate strings. The most popular method is using the .-operator. For small concatenations using this operator works fine. When lots of strings or variables need to be combined it can become cumbersome. Here's an example: $logMessage = 'A…

Read more