Readable code tips: Use “is” or “has” for Boolean variables/functions

Previous Tip: Don’t inline everything!

This is a little naming convention that I find really helpful.

If a variable is Boolean type, or if a function returns a Boolean type, then consider if you can name it with an “is” or “has” prefix (or somewhere in the name). Because in many cases, not doing this can be confusing.

Let’s see some examples.

Here’s a variable that tells us if a file has a .txt extension.

$txtExtension = pathinfo($filename, PATHINFO_EXTENSION) === 'txt'

But… with that name, it could mean “here is the string that is used for a text file extension”.

This variable tells us if a file has a txt extension. So let’s name it appropriately:

$fileHasTxtExtension = pathinfo($filename, PATHINFO_EXTENSION) === 'txt'

I see this a lot! And it’s a really simple improvement.

Here’s a Boolean function/method:

function textFile(string $filename) : bool {
    ...
}

I mean, the name is just really confusing. It could do anything. But if the intention is to test if the filename is that of a text file, then say so!

function isTextFile($filename) {
    ...
}

Bonus related weird programming fact

One of the first languages I learned properly was the functional language “Scheme”, which was like Lisp with training wheels.

There was a convention in Lisp that a “predicate” (a function that returned t or nil, which are equivalent to true and false) would be named with a p or -p suffix.

And I still think of this sometimes. Can I ask my wife if she wants a cup of tea by asking “Tea-P?” (No, I don’t. Never. Ever.)

I think function textFileP( $filename )isn’t quite as clear, but know that naming conventions like this are proper old!