On Tue, Apr 2, 2024, at 20:51, Bruce Weirdan wrote:
> On Tue, Apr 2, 2024 at 8:05 PM Ilija Tovilo <tovilo.il...@gmail.com> wrote:
> 
> > Equality for data objects is based on data, rather than the object
> > handle.
> 
> I believe equality should always consider the type of the object.
> 
> ```php
> new Problem(size:'big') === new Universe(size:'big')
> && new Problem(size:'big') === new Shoe(size:'big');
> ```
> 
> If the above can ever be true then I'm not sure how big is the problem
> (but probably very big).
> Also see the examples of non-comparable ids - `new CompanyId(1)`
> should not be equal to `new PersonId(1)`
> 
> And I'd find it very confusing if the following crashed
> 
> ```php
> function f(Universe $_u): void {}
> $universe = new Universe(size:'big');
> $shoe = new Shoe(size:'big);
> 
> if ($shoe === $universe) {
>    f($shoe); // shoe is *identical* to the universe, so it should be
> accepted wherever the universe is
> }
> ```
> 
> -- 
>   Best regards,
>       Bruce Weirdan                                     
> mailto:weir...@gmail.com
> 

I'd love to see it so that equality was more like == for regular objects. If 
the type matches and the data matches, it's true. It'd be really helpful to be 
able to downcast types though. Such as in my user id example I gave earlier. 
Once it reaches a certain point in the code, it doesn't matter that it was once 
a UserId, it just matters that it is currently an Id.

Now that I think about it, decoration might be better than inheritance here and 
inheritance might make more sense to be banned. In other words, this might be 
just as simple and easy to use:

data class Id {
  public function __construct(public string $id) {}
}

data class UserId {
  public function __construct(public Id $id) {}
}

Though it would be really interesting to use them as "traits" for each other to 
say "this data class can be converted to another type, but information will be 
lost" where they are 100% separate types but can be "cast" to specified types.

// "use" has all the same rules as extends, but,
// UserId is not an Id; it can be converted to an Id
data class UserId use Id {
  public function __construct(public string $id, public string $name) {}
}

$user = new UserId('123', 'rob');

$id = (Id) $user;

$user !== $id === true;

$id is 100% Id and lost all its "userness." Hmm. Interesting indeed. Probably 
not practical, but interesting.

— Rob

Reply via email to