combined return and if statement like ruby #2195
Replies: 3 comments 13 replies
-
|
I think #1785 is very close to what you're proposing (but there are quite a few proposals for similar features, so I'm not surprised it's not the one you found). I think the main issues with this proposal are:
|
Beta Was this translation helpful? Give feedback.
-
|
Instead of var value = somefunction();
if (value == null) {
return <error>;
}Just do var value = somefunction();
if (value == null) return <error>;Tada. |
Beta Was this translation helpful? Give feedback.
-
|
All the examples I'm seeing in favour of this are the form if (something is null) return <error>which already has a succinct short form. The one scenario where I've previously found myself wishing for a short-hand is the reverse, where I have a string of "validate" checks at the start of a method and if any of them return an error, return that. That does now have a shortening thanks to pattern matching, but it's still needing extra variable declarations that aren't otherwise needed. For example: if (checkOne() is Error errorOne) return errorOne;
if (checkTwo() is Error errorTwo) return errorTwo;
if (checkThree() is Error errorThree) return errorThree;
if (checkFour() is Error errorFour) return errorFour;vs. return checkOne() if not null; // not suggested syntax, just for intention
return checkTwo() if not null;
return checkThree() if not null;
return checkFour() if not null; |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I was coming here to suggest a return if type statement and Github suggested a previous proposal from last summer.
I don't think the original poster on that proposal articulated the right solution, but one of the responses pointed out that Ruby has this construct already..
I guess I should do some research into how well this construct performs in Ruby, but I can say that my code is littered with things like this:
I believe that the code would be more readable if that code could look like this:
Thanks
Beta Was this translation helpful? Give feedback.
All reactions