oliverdavies.uk/source/_daily_emails/2023-08-19.md

44 lines
1.3 KiB
Markdown
Raw Normal View History

2024-01-03 20:00:00 +00:00
---
title: >
2024-02-07 20:01:19 +00:00
Asserting all the things
2024-01-03 20:00:00 +00:00
pubDate: 2023-08-19
permalink: >-
2024-02-07 20:01:19 +00:00
archive/2023/08/19/asserting-all-the-things
2024-01-03 20:00:00 +00:00
tags:
2024-02-07 20:01:19 +00:00
- php
2024-01-03 20:00:00 +00:00
---
As well as assertions within tests, you can also check within implementation code that things are in an expected state or contain a certain value.
In PHP, this is done by throwing an Exception if a condition is met.
For example:
```language-php
2024-01-03 20:00:00 +00:00
if (!is_array(false)) {
throw new \Exception('Not an array');
}
```
There's also the `assert` construct which, since PHP 8.0, throws an Exception by default:
```language-php
2024-01-03 20:00:00 +00:00
assert(is_array(false));
```
You can also use an assertion library, such as `webmozart/assert` or `beberlei/assert` which provide assertions and guard methods:
```language-php
2024-01-03 20:00:00 +00:00
use Webmozart\Assert\Assert;
Assert::isArray(false);
```
Similarly, if the condition fails, it throws an Exception that can be caught elsewhere.
As well as basic assertions such as the item is the expected type or don't match the condition, there are more complex assertions, such as all items within an array are a certain type or that an integer is positive.
## Here's the thing
I use guard conditions a lot within my code. If something is not as I'd expect, I like for an error to be thrown. This makes is easy to test and to debug any failures compared to failing silently.