From 8e2060dea66c280eb46f9c1e9d28e3bd5cf3e976 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Thu, 29 Aug 2024 23:59:05 +0100 Subject: [PATCH] Add daily email for 2024-08-30 Revisiting the Null Object pattern in Drupal --- source/_daily_emails/2024-08-30.md | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 source/_daily_emails/2024-08-30.md diff --git a/source/_daily_emails/2024-08-30.md b/source/_daily_emails/2024-08-30.md new file mode 100644 index 00000000..34d311b1 --- /dev/null +++ b/source/_daily_emails/2024-08-30.md @@ -0,0 +1,38 @@ +--- +title: Revisiting the Null Object pattern in Drupal +date: 2024-08-30 +permalink: daily/2024/08/30/revisiting-the-null-object-pattern-in-drupal +tags: + - software-development + - drupal + - drupal-module + - open-source + - php + - design-patterns +cta: ~ +snippet: | + Whilst working on my secret side project, today I decided to revisit the Null User Drupal module. +--- + +The Null Object pattern is one of my favourite ways to DRY up code and reduce duplication. + +I wrote the [System User module][0] for a client project a number of years ago, which also included the [Null User module][1]. + +If no system user is found, it returns a null (empty) user instead that returns null or empty values by default. + +Today, [I posted][2] [and tooted][3] a screenshot of some code from a side project I'm working on, which I realised would be another good time to use the Null User module. + +In the code, I search for a user with a given licence key. + +If a user is found, it is returned. + +If not, instead of returning FALSE or NULL, I return a null user object that I can treat the same as a real user. + +Now, when I create the node and assign an owner, I can just use `$account->id()` and it will always work if a user was found or not. + +This makes the code cleaner, simpler and easier to test and maintain. + +[0]: https://www.drupal.org/project/system_user +[1]: https://www.drupal.org/project/null_user +[2]: https://x.com/opdavies/status/1829183673725284772 +[3]: https://mastodon.social/@opdavies/113046773292848198