0

I'm using Groovy. What's a more elegant way to do the following?

if (!token) {
    token = this.getToken(key, callback)

    if(!token) {
      return params = null
    }

}

So if a token is already present when a user comes into this flow, that token should be used. However, if the token isn't present, we should try to generate one. The service we're using to get the token doesn't throw an exception if none is created, it just returns null. If the token isn't successfully created (is still null) we want to set the params to null.

Is there a cleaner way to do what I'm doing? The null check within a null check seems ugly to me.

Paul Erdos
  • 1,355
  • 2
  • 23
  • 47
  • If the new generated token is not null, what are you supposed to do with params? – jalopaba Mar 30 '15 at 16:41
  • If params is null, then the button associated with the token will be hidden in the view. So if you can't get the token basically that functionality will be disabled for the user. – Paul Erdos Mar 30 '15 at 16:44

1 Answers1

2

The first part can be rewritten using the elvis operator to eliminate the first null check:

token = token ?: this.getToken(key, callback)
if (!token) {
   ...
}
ataylor
  • 64,891
  • 24
  • 161
  • 189