From 5910e4eb0e9d8a94a505bfd22ff587db1a04cef1 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Sat, 11 May 2024 01:08:18 +0200 Subject: [PATCH] Add daily email for 2024-05-08 Assertions aren't just for tests --- source/_daily_emails/2024-05-08.md | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 source/_daily_emails/2024-05-08.md diff --git a/source/_daily_emails/2024-05-08.md b/source/_daily_emails/2024-05-08.md new file mode 100644 index 000000000..56570e86c --- /dev/null +++ b/source/_daily_emails/2024-05-08.md @@ -0,0 +1,42 @@ +--- +title: Assertions aren't just for tests +date: 2024-05-08 +permalink: archive/2024/05/08/assertions-arent-just-for-tests +tags: + - software-development + - drupal + - php + - automated-testing +cta: ~ +snippet: | + `assert()` isn't just for automated tests. +--- + +If you've written or seen automated tests in PHP, you'll have seen lines like this: + +```php +self::assertTrue(FALSE); +``` + +But, did you know assertions can be used outside of tests. + +PHP has an `assert()` function that can be used anywhere. + +For example, if I had this code: + +```php +$node = Node::load(1); + +assert($node instanceof NodeInterface); +assert($node->bundle() === 'page'); +``` + +I know `$node` is a node with the correct bundle type and I can continue. + +I've made my assumptions explicit. + +If `$node` is not the correct type or returns an unexpected bundle, the assertion will fail and an Exception will be thrown. + +I think this is better than assuming or hoping the values are as you expect, and it also makes the intent of the code much easier to see and understand. + +If you haven't tried `assert()` before, give it a try.