Don't add boolean arguments

A convention I like from the Laravel framework is to avoid adding boolean arguments to methods.

For example, if I have this function:

public function getPosts() { ... }

If I wanted to only get published posts, one way would be to add a boolean argument:

public function getPosts(boolean $onlyPublished) { ... }

Then, I'd need to use that within the method body to add another condition (this is referred to as control coupling, where one method affects another).

The non-boolean approach would be to create a separate method with its own distinct name.

For example, getPosts() could be named getAllPosts() and there could be a separate getPublishedPosts() method for only getting published posts:

public function getAllPosts() { ... }

public function getPublishedPosts() { ... }

Whilst we have two methods now instead of one, it's much clearer what each does and there aren't any random true or falses wherever the method is used.

- Oliver

P.S. Are you still using Drupal 7 and don’t know what’s involved to upgrade to Drupal 10? Book a Drupal 7 upgrade consultation call or an upgrade roadmap.

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.