Readable code tips: Extract complex conditions

Previous tip: Introduction and naming with units
Next tip: Don’t inline everything

One idea that I learned very early on in my computing education was that you work “top down” by writing a high-level, abstract version of a more complex process, stating what you want to do, and then working on each of the sub-steps of the process.

I’ve heard this called “pseudo-code” and “programming by wishful thinking” (as in “I wish there was a function called getPostsFromApi()“)

I often come across complex conditions in code that are hard to read because they have multiple sub-conditions.

Things like:

if (
    pathinfo($filename, PATHINFO_EXTENSION) === 'txt' &&
    file_exists($filename) &&
    filetype($filename) === 'file'
) {
    ...
}

I’m sure that these kinds of conditions normally evolve over time and so don’t exist as pseudo-code to start with. But the pseudo-code idea can now be used to make this easier to read:

function isExistingTextFile($filename) {
	return
        pathinfo($filename, PATHINFO_EXTENSION) === 'txt' &&
        file_exists($filename) &&
        filetype($filename) === 'file';
}

if (isExistingTextFile($filename)) {
    ...
}

This has the additional benefit that the isExistingTextFile function here is also reusable.

And if you can build trust in your code base, this is easier to read and faster to work with too.