Le 10/01/2021 à 22:27, Larry Garfield a écrit :
This is a little tangent from the Enums RFC, but I want to flag it because it
it's the sort of in-passing decision that could have far-reaching implications,
so shouldn't be done implicitly.
At the moment, the Enum RFC for scalar enums includes two methods:
public function has(string $name): bool
public function from(string $name): self throws ValueError
Nikita raised the point that has() seems kinda pointless as it would only ever
be used to wrap a possibly-unsafe from() call. (In most other cases, calling
cases() would be more useful or at least equally useful.) One of the proposed
alternatives was the following:
public function from(string $name): self throws ValueError
public function tryFrom(string $name): ?self
The "a method that begins with try is nullable, so watch out" idiom is present
in C# and Rust, but to my knowledge has never existed in PHP. That doesn't make it bad;
it actually combines quite well with the null coalesce operator to allow for default
values, making a valueOrDefault() method unnecessary.
$order = SortOrder::tryFrom($input) ?? SortOrder::Asc;
I'm not opposed to following that pattern here; it would allow both a "hard fail" and
"soft fail" variant of the operation. However, as noted that idiom has never appeared in
PHP before that I'm aware. If we adopt it here, that means it will either start to spread and
become a more common PHP idiom over time, OR it won't spread and Enums will have this weird one-off
naming convention for a nullable method. The former would, of course, be considerably preferable
to the latter.
So, explicit decision time: Are we OK with introducing that idiom, and then
following it consistently in the future in similar situations? (viz, tryX()
means nullable, and no-try means not nullable.) I'm good with it if the
consensus is good with it, but I want to see what the consensus is first.
I'm OK with the tryBar(): ?Foo pattern, but my preference goes over just
bar(): ?Foo, as long as API are explicitly typed and correctly documented.
I will not fight against or for any or another solution, as long as the
convention remains the same for everything.
Larry, I think your proposal is missing something: if a convention
emerge, it should be documented as such, and be considered as a law for
subsequent language / API addition, the real question, IMHO, is : Are
people OK with writing naming and design conventions by law in PHP core ?
For that matters, I'm OK, this would avoid many bikesheds in the future:
this is the law, and the law says, name it tryX(), no more useless
votes, no more flavor-oriented flame wars on naming :)
--
Pierre
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php