Improving the "return" keyword to do conditional early exists of the method. #7927
-
Background Usually there is two approaches to handle do this. The first one, only one exit:
The problem with this approach is that the logic can became so complex that it will lead to indentation hell. The second one, early exit:
This is so much cleaner and readable way, but now we have a lot of Proposal
or for clarity also can be added a new keyword like
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 30 replies
-
See: #2195 |
Beta Was this translation helpful? Give feedback.
-
This proposal doesn't really save us much and feels like another "terse for the sake of being terse" situation which I'm seldom a fan of. A lot of codebases prefer to put the executed statement on its own line: if (x < 0)
return; Others like adding braces for clarity and consistency, and I see nothing wrong with either option as opposed to something that saves a couple whitspace characters and maybe the word |
Beta Was this translation helpful? Give feedback.
-
When this has been suggested in the past (see #1397 #138 among others) the syntax has been:
Which requires no new keywords and would be (nearly) instantly understood by anyone encountering the construct for the first time. The proposed form
would not only be a brand new and confusing syntax, it's ambiguous with existing code. To illustrate, what does this mean? var result = /* ... elided ... */
return (Parsable) result; Is Or is [Remember that whitespace has (nearly) no meaning in C#, so |
Beta Was this translation helpful? Give feedback.
-
After discussing with @HaloFour , @theunrepentantgeek and @CyrusNajmabadi on how to actually solve the issue that I want to solve, this approach wasn't what I want, but actually I think is better. I use a result class which you can find here with all the needed code https://gist.github.com/proteo5/cf629c7f4575b4ec486cb36425be270a so first I define a custom exception:
Then the rule will throw that exception whereever a rule doesn't pass
So the final code end up like this:
In this way, when a rule is not fulfill it will throw a custom exception and it will be handle on the Once again, thanks a lot for the feedback. |
Beta Was this translation helpful? Give feedback.
After discussing with @HaloFour , @theunrepentantgeek and @CyrusNajmabadi on how to actually solve the issue that I want to solve, this approach wasn't what I want, but actually I think is better.
I use a result class which you can find here with all the needed code https://gist.github.com/proteo5/cf629c7f4575b4ec486cb36425be270a
so first I define a custom exception:
Then the rule will throw that exception whereever a rule doesn't pass