chip
chip

Reputation: 3279

how come some statements require the return statement at the end of some groovy closures?

def handleLogin = {
   def hashPassd = DU.md5Hex(params.password)
   // Find the username
   def user = User.findByUserNameAndPassword(params.userName, hashPassd)
   if (!user) {
      flash.message = "User not found for userName: ${params.userName}"
      redirect(action:'index')
      return
   } else {
      session.user = user
      redirect(controller:'todo')
   }
}

how come the if condition requires the return statement? and the else block don't require it?

Upvotes: 2

Views: 563

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122394

The return is not strictly necessary but it's a good habit to get into. Calls like render and redirect in a controller action are usually intended to be the conceptual "end" of the action, and its easy to forget sometimes and treat the redirect as if it were a return

def someAction() {
  if(!params.id) {
    flash.message = "no ID provided"
    redirect action:'error'
  }

  def myObj = MyObj.get(params.id)
  //...
}

This will fail at runtime, probably with a rather obscure error message, and to avoid this possibility it's a good idea to remember to put an explicit return after any calls to redirect or render. It's the kind of thing that has bitten me when coming back to make changes to a controller action I originally wrote 6 months previously...

Upvotes: 1

Steve Kuo
Steve Kuo

Reputation: 63104

In this case the return is not necessary. If the return isn't there it will continue to after the if, which is the end of the method, and thus returns.

Upvotes: 3

Related Questions