On Sat, 20 Mar 2021 at 11:35, Larry Garfield <la...@garfieldtech.com> wrote:

> My main concern is around the covariance of inheritance.  The example
> given:
>
> abstract class Person
> {
>     abstract public function hasAgreedToTerms(): bool;
> }
>
> class Kid extends Person
> {
>     public function hasAgreedToTerms(): noreturn
>     {
>         throw new \Exception('Kids cannot legally agree to terms');
>     }
> }
>
> While that may be technically correct from a type theory perspective (my
> type theory isn't strong enough to say either way), I don't feel like that
> obeys Liskov.


It absolutely obeys Liskov, because noreturn is the subtype of all
subtypes, aka the bottom type.


> If I have an array of Person objects, and I iterate them to check if
> they've all agreed to terms, I expect the return value to be a *usable*
> type in the Person interface or a subtype of it *that I can still use*.  I
> cannot use Kid::hasAgreedToTerms's return type, because it's by definition
> non-existent.


Luckily your program will never have the chance to use its return type,
because calling the method throws an exception.


> That feels like a bad time bomb.
>

You might, in this scenario, add a `@throws` docblock and hope some sort of
static analysis rule might catch the time bomb

Another way that you can think of this is with throw expressions. The
ternary in the function below is supposed to return `string`, or a subtype
of `string` (the literal string "hello" is a subtype of `string`). The
types are valid here if the type of `throw new Exception...` is treated as
`noreturn`, and if `noreturn` is a subtype of `string`.

```
<?php
function getString(): string {
  return rand(0, 1) ? "hello" : throw new \Exception('bad');
}
```


> Other than that concern, I'm fine with the spec.  I would marginally
> prefer "never" over "noreturn", but not enough to vote against it just for
> that.
>

There will be a separate vote for noreturn vs never!


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

Reply via email to