From c8d276611b02c49fa3b8fd08c296b65e55d110c8 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Thu, 18 Jan 2024 23:50:54 +0000 Subject: [PATCH] Add daily email for 2024-01-18 Is zero unlimited? --- source/_daily_emails/2024-01-18.md | 64 ++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 source/_daily_emails/2024-01-18.md diff --git a/source/_daily_emails/2024-01-18.md b/source/_daily_emails/2024-01-18.md new file mode 100644 index 000000000..41911c983 --- /dev/null +++ b/source/_daily_emails/2024-01-18.md @@ -0,0 +1,64 @@ +--- +title: Is zero unlimited? +date: 2024-01-18 +permalink: archive/2024/01/18/is-zero-unlimited +snippet: | + If you set a limit to be zero, would you expect it to return all the results or none? +tags: + - software-development + - clean-code +--- + +Something I've seen in code is the unclear use of zero when adding limits, such as loading items from a database. + +In some instances, setting zero will return all items - essentially, an 'unlimited' value in disguise - rather than returning no results, which is what I'd expect. + +I imagine the code looks something like this: + +```php +if ($limit > 0) { + $query->range(0, $limit); +} +``` + +If `$limit` is greater than one, add it to the query. + +For me, using `0` as the unlimited value doesn't seem like the best option. + +I'd prefer to use a `null` value as the default and only add the limit if it's set - i.e. an integer or not null. + +It means the value could be either an integer or null, but I think the intent of the code is more explicit. + +This would make the code look like this: + +```php +if (is_int($limit)) { + $query->range(0, $limit); +} +``` + +Whilst this is clearer, it doesn't cover all use cases. + +Presumably, the limit should only be a positive integer. + +It wouldn't make sense to set a negative number as the limit or, as the unlimited value is `null`, setting it to zero. + +This is the end code I'd likely write: + +```php +if (is_int($limit)) { + if ($limit < 1) { + throw new InvalidArgumentException('A limit must be a positive integer.'); + } + + $query->range(0, $limit); +} +``` + +If the limit is not an integer, nothing happens. + +It throws an Exception if the value is invalid - i.e. less than one. + +The limit is applied if the limit is greater than or equal to one. + +While it's more complex as there are more checks to perform and different types in use, I think this is clearer and easier for someone reading or implementing the code to understand what it does and use it correctly.