On Fri, Feb 7, 2025, at 10:21, MrMeshok wrote:
> >
> > Examples of potentially using in PHP:
> > Without this operator we writing this code:
> >
> > $foo = ...
> >
> > if ($foo === null) {
> >     throw new FooIsNullException();
> > }
> >
> > $foo->bar.
> >
> > With this operator:
> >
> > $foo!->bar
> > $foo!->someProperty->method();
> > $foo!->someProperty->anotherProperty!->method();
> 
> I see where you're coming from, in my code I had to deal with a lot of
> APIs with models which have nullable properties, but they shouldn't be
> null if some conditions are met.
> So I work with them in this way
> ```php
> if ($response->code === ResponseCode::Success) {
>     // order and quantity are nullable
>     return $response->data->order->quantity ?? throw new
> UnexpectedResponseException($response);
> 
>     // With method calls you would need to add nullsafe operators
>     // order and date are nullable
>     return $response->data->order?->date?->format('Y-m-d') ?? throw
> new UnexpectedResponseException($response);
> }
> ```
> UnexpectedResponseException is just an exception that keeps faulty
> response, so I can catch it and act on it, or it just gets logged and
> I can show producers of API that they have a problem.
> 
> I see a point in !-> operator if it would work just like that. Throws
> a specific error that has an object that triggered this error.
> 

Hello,

I feel like that is more of an architecture problem than a programming one 
though. Instead of constantly checking if the conditions are right, use php's 
type system instead, so it would read more like:

if ($response instanceof SuccessfulResponse) {
  return $response->data->order->quantity;
}

throw new UnexpectedResponseException($response);

I'd argue that having an "undefined" aka "null" quantity in a model at all is 
rather strange as that doesn't seem to represent any possible reality outside 
of a computer (unless you are dealing with Schrodinger's cat or other quantum 
effects).

— Rob

Reply via email to