On 01.04.21 17:07, Benjamin Eberlei wrote:
I don't know, you are arguing that you forgot a return, but you also did
not forget to add a never return type. You
could easily fix this by inlining the exception instead.

```php
if (!isset($user)) {
    throw new NotFoundException();
}
```
Even when you insist on the function, it is a one liner that throws
immediately. Adding the never return type there isn't going to catch a
great many bugs.

Throwing an exception immediately is an alternative, but this only works
if that is the absolute only thing the method does, and even then it
leads to a lot of repetition (if you have many controllers) with very
specific code shared in each controller. Making the identical behavior
between controllers explicit by a shared "notFound" method seems better
coding to me, and it has the advantage of being very readable and
something you can easily recognize between different controllers - you
look it up once and know what it does. If you throw exceptions in each
controller, you might wonder if this is the exact same exception as
another one in another controller. Often you might also want to change
the behavior at some point - for example log the event before throwing
the exception, or handling notFound entirely different. noreturn/never
gives you the flexibility to refactor "throw NotFoundException();" into
a method while keeping the promise that the code flow will not continue.

Abstracting away something like a redirect, an authorization problem or
a 404 also seems an improvement to me (compared to "throw
NotFoundException();") because you write and test that logic once, and
then reuse it in different places. Like with other parts of the type
system in PHP noreturn/never just gives you stronger guarantees and more
information about what a function/method is ought to do and how it behaves.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to