DEV Community

Oliver Davies
Oliver Davies

Posted on • Originally published at oliverdavies.uk on

Coding defensively and considering the unhappy path

Last week, whilst speaking about Sculpin at PHP South West, I showed an example from a client project I'd built with Sculpin.

The project was for a local gym and fitness centre, and I was demonstrating how I'd created the timetable page and kept the data separate from the HTML and Twig markup so the client could easily administer it (they edit the files on GitHub, which triggers a rebuild of the website).

Each class should have a name and start and end times and be on a specified day.

But what if the client didn't include a name or start or end time?

What if they put a number or boolean instead of a string?

What if there are no classes on a particular day?

You don't know how people will use your software, so it's best to be defensive - validate and verify things before rendering them and prevent the page or whole application from breaking if something isn't as you expected or assumed.

We also can't assume the "happy path" will always be correct.

What if there aren't any classes? Do we put an empty message on the timetable or not show that day?

Another scenario

If you were retrieving or posting data to an API endpoint, would you assume it was successful or verify the response code is what you expected?

If you get the data, do you check if it's in the correct format and something you can use?

If not, do you verify other actions in your application haven't run and it's not in an invalid state?

Here's the thing

In PHP, a common approach is to use the assert() function, as we saw in yesterday's email.

Then, write automated tests that don't test just the happy path but also the unhappy paths.

P.S. There's less than a year until Drupal 7's end-of-life date. Plan your upgrade to Drupal 10 now!

Top comments (0)