-
Notifications
You must be signed in to change notification settings - Fork 4
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
Add analyzer warning about throw expressions passed to GetOrElse
#466
Comments
I agree, that's something that I've seen done wrong quite a few times. Of course, this may also be a hint that the API isn't as obvious as it could be. |
An alternative would be to remove the value overload and only accept a Func. In almost all cases except the primitive types, this would improve the runtime performance, because the Func will only be evaluated when really necessary. |
While that is a possibility, I think it would be noise in cases where variables or primitives are already present. You could argue it's still better however, as you can't accidentially calculate the fallback value (if you call a method) instead of passing it as lazy. There is no good way to write an analyzer for that. I would not strongly oppose removing the value overload. |
@Mafii Are you sure that your first example compiles? I get a compiler error. |
You're right, it does not compile - I sadly don't have the original anymore, and wrote this out of my head. Here's one that does compile: Funcky.Monads.Option.FromNullable(someStringThatCanBeNullable)
.Where(value => value != "Hello")
.GetOrElse(() => throw new Exception("Unexpected....")()); |
I found a more reasonable case where this behaviour can happen unexpectedly: string? someStringThatCanBeNullable = null;
string? nullableFallbackValue = null;
Funcky.Monads.Option.FromNullable(someStringThatCanBeNullable)
.Where(value => value != "Hello")
.GetOrElse(nullableFallbackValue ?? throw new Exception("Unexpected....")); The same can happen with ternary expressions, and all other cases where throw expressions can be part of an expression that directly returns a value (none on the top of my head but there might be some) |
Here's some possible rules I have in mind for the analyzer to show a warning (or not):
|
See #521 and coordinate |
When calling
GetOrElse(<alternative>)
at the end of a option chain, sometimes developers forget to pass a method and pass thethrow
expression directly. This happens because thethrow
expression will statisfy any type for the compiler.Example of code that compiles, seems fine, but will throw an exception in both
None
andSome
cases:what the person probably wanted to do:
This is also what I propose as refactoring that should be presented to the user (quick fix): Just add a
() =>
in front of thethrow
expression.The text was updated successfully, but these errors were encountered: