Assertions aren't just for tests

If you've written or seen automated tests in PHP, you'll have seen lines like this:

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:

$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.

- Oliver

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.