uuid: - value: d3fe0eae-7883-4fe6-9a98-747b53d860ca langcode: - value: en type: - target_id: daily_email target_type: node_type target_uuid: 8bde1f2f-eef9-4f2d-ae9c-96921f8193d7 revision_timestamp: - value: '2025-05-11T09:00:14+00:00' revision_uid: - target_type: user target_uuid: b8966985-d4b2-42a7-a319-2e94ccfbb849 revision_log: { } status: - value: true uid: - target_type: user target_uuid: b8966985-d4b2-42a7-a319-2e94ccfbb849 title: - value: "Don't add boolean arguments" created: - value: '2024-05-03T00:00:00+00:00' changed: - value: '2025-05-11T09:00:14+00:00' promote: - value: false sticky: - value: false default_langcode: - value: true revision_translation_affected: - value: true path: - alias: /daily/2024/05/03/dont-add-boolean-arguments langcode: en body: - value: |
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 false
s wherever the method is used.
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 false
s wherever the method is used.