Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Confusing singleWhereOrNull extension method #294

Open
jaripekkala opened this issue Jun 20, 2023 · 1 comment
Open

Confusing singleWhereOrNull extension method #294

jaripekkala opened this issue Jun 20, 2023 · 1 comment

Comments

@jaripekkala
Copy link

https://github.com/dart-lang/collection/blob/v1.17.2/lib/src/iterable_extensions.dart#L296-L304

My proposal: Deprecate and delete singleWhereOrNull, and introduce more clear methods

Reasoning:
Many use the singleWhere method as replacement to firstWhere when the list should not contain more than one matching value, in cases when the logic would not work if code somewhere later changes in way that there are multiple matching values, so throwing error would make sense (developer need to go and handle the case).

But when also no matching value is acceptable, developer can mistakenly use singleWhereOrNull and have different behaviour than intended. These cases are not so commonly unit tested, as these cases are preventing mistakes in the future.

@lrhn
Copy link
Member

lrhn commented Feb 29, 2024

I can see how the singleWhereOrNull behavior might not be what someone wants, if they're really asking for a zeroOrOneWhere: If there is none, give me null, if there is one, give me it, if there are more, something is seriously wrong, so throw.

I do think that elements.singleWhereOrNull(test) should behave like elements.where(test).singleOrNull, so maybe we just need to add another method to cover the zeroOrOneWhere/optionalSingleWhere case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants