Crell / enum-comparison

A comparison of enumerations and similar features in different languages
80 stars 7 forks source link

has() vs tryFrom() #67

Closed iluuu1994 closed 3 years ago

iluuu1994 commented 3 years ago

Suggested by Nikita, has() itself is rarely useful. It will always be used in combination with from() so we might as well offer tryFrom() to make these cases shorter.

iluuu1994 commented 3 years ago

Additional plus: Static analyzers will understand that tryFrom() doesn't throw an exception while has() ? from() : null would require additional logic to understand.

Crell commented 3 years ago

As discussed in slack, my primary concern with from()/tryFrom() is that we'd be stealth-introducing a naming convention of "tryX() means it may return null". I am highly wary of that without further consideration because the implications could be large.

(Not necessarily bad, but large.)

TysonAndre commented 3 years ago

There's also the option of getOrDefault(string $name, $default = null), but both would definitely be different naming conventions. I don't have a strong preference.

Additional plus: Static analyzers will understand that tryFrom() doesn't throw an exception while has() ? from() : null would require additional logic to understand.

I agree it's definitely easier.

They'd have to get it from an external repo such as https://github.com/JetBrains/phpstorm-stubs/blob/master/Reflection/ReflectionClass.php (or extract it) because getDocComment() is almost always null for internal classes, methods, etc.

Phan and Psalm check for user-defined methods but not for internal methods (at least not that I remember for psalm)

Crell commented 3 years ago

I'd feel more comfortable with from(): self / tryFrom(): ?self if voters were clear of the implications. Unless someone objects I'm going to start a thread on Internals tomorrow to highlight it and see if anyone has an issue with setting this precedent. If there's no serious pushback, then we can go with that.

iluuu1994 commented 3 years ago

The downside of fromOrDefault is that with missing generics the return type would have to be mixed. My preference is tryFrom. I'm also cool with fromOrNull.

Crell commented 3 years ago

RFC updated to use from/tryFrom.

Crell commented 3 years ago

Leaving open until @iluuu1994 updates the implementation. Ilija, please close when you've done so.