From e3b6a8feeceeb5b5a3893a41d736fada6eb18334 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Sat, 4 May 2024 23:54:06 +0100 Subject: [PATCH] Add daily email for 2024-05-03 Don't add boolean arguments --- source/_daily_emails/2024-05-03.md | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 source/_daily_emails/2024-05-03.md diff --git a/source/_daily_emails/2024-05-03.md b/source/_daily_emails/2024-05-03.md new file mode 100644 index 000000000..9a7fe6fcb --- /dev/null +++ b/source/_daily_emails/2024-05-03.md @@ -0,0 +1,38 @@ +--- +title: Don't add boolean arguments +date: 2024-05-03 +permalink: archive/2024/05/03/dont-add-boolean-arguments +tags: + - software-development + - drupal + - php +cta: ~ +snippet: | + Don't add boolean arguments to your methods. +--- + +A convention I like from the Laravel framework is to avoid adding boolean arguments to methods. + +For example, if I have this function: + +```php +public function getPosts() { ... } +``` +If I wanted to only get published posts, one way would be to add a boolean argument: + +```php +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: + +```php +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.