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

[question] Usage of return #64

Open
franklinchou opened this issue Aug 7, 2019 · 1 comment
Open

[question] Usage of return #64

franklinchou opened this issue Aug 7, 2019 · 1 comment

Comments

@franklinchou
Copy link

franklinchou commented Aug 7, 2019

One question I had was what if you explicitly want control flow to return to the calling function?

For example, in a web controller function I have the following:

def index(): Action[AnyContent] = Action.async { implicit rq: Request[AnyContent] => 
  rq.getQueryString("permission-field") match {
    case Some(pf) => 
      if (!permissioned.contains(pf)) return Action(Forbidden)
      else // do other stuff
    case None => 
      Future { BadRequest }
  }
}
@Slakah
Copy link
Contributor

Slakah commented Sep 16, 2019

In your example, you would need to return something in the else block. If you wanted to reduce nesting, you could move the permission check into the pattern match, i.e.

def index(): Action[AnyContent] = Action.async { implicit rq: Request[AnyContent] => 
  rq.getQueryString("permission-field") match {
    case Some(pf) if (!permissioned.contains(pf)) => Action(Forbidden)
    case Some(pf) => 
      // do other stuff
    case None => 
      Future { BadRequest }
  }
}

I would also quote from the guide.

Besides, return is anti structural programming, as functions can be described with multiple exit points and if you need return, like in those gigantic methods with lots of if/else branches, the presence of a return is a clear signal that the code stinks, a magnet for future bugs and is thus in urgent need of refactoring.

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