"TryX" idom for Enumerations
| From: | Larry Garfield | Date: | Sun, 10 Jan 2021 21:27:12 +0000 |
| Subject: | "TryX" idom for Enumerations | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-112838@lists.php.net to get a copy of this message | ||
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.
--
Larry Garfield
larry@garfieldtech.com