php-try icon indicating copy to clipboard operation
php-try copied to clipboard

Some API suggestions

Open schmittjoh opened this issue 12 years ago • 2 comments

I've some suggestions for the API after trying this a bit. Basically, I'm wondering what you think about something like this:

Attempt::call($someCallable)
    ->forAll($onSuccess)
    ->always($always) // Finally semantics (called regardless of success/failure)
    ->throwIfFailed()
;

This would be equivalent to:

try {
    $rs = $someCallable();
    $onSuccess($rs);
} finally {
    $always();
}

Not sure if this is already supported in another way, but I haven't found anything. What do you think?

schmittjoh avatar Jan 21 '14 17:01 schmittjoh

@schmittjoh I added forAll() (see the other issue), and I like the other suggestions. I was just wondering about the following.

  • throwIfFailed() could be achieved by calling get() which will return the value, or throw if there was an exception. Not sure if it's worth adding an extra method for this?
  • always($callable) This callable cannot be passed a value (I guess that's ok), but what should happen if the always() callable throws? I think the best thing would be to not catch this exception in the library and let the user handle it, but your example code seems to suggest otherwise?

asm89 avatar May 31 '14 14:05 asm89

Thanks for the addition, good job.

I believe get() is what I'm using right now. It's not terribly necessary to have the extra method, it would improve readability for someone else though. Not sure if there is also a use-case for a different return value, i.e. throwIfFailed returning the Attempt. Overall, more a nice-to-have thing, not a must-have :)

Regarding the other method, yeah I think it's a good idea to let the user handle it (or letting him make sure he does not throw one).

schmittjoh avatar May 31 '14 15:05 schmittjoh