0

我是一个 groovy 新手,所以请耐心等待。我喜欢 groovy 编写更少且通常更清晰的代码的能力,但我试图弄清楚是否有更好或更易读的方式来压缩这些多个 if 语句。这是一个相当简单的代码片段,但必须有更好的方法来做到这一点。我是新手,因此非常感谢任何代码片段。

if (!textOverlay) {
  textType = "" 
  if(url != null){
    Page getPage = resource.getResourceResolver().getResource(url).adaptTo(Page.class)
    if (getPage != null) {
      showLink = showLink + ".html"
        if (fragment.length() > 0) {
          url += "#"+fragment;
        }
    }
  }             
}  else { 
    //do something else
}

在此先感谢您的帮助!

4

1 回答 1

1

这对嵌套没有帮助,但是在一些地方您可以利用 Groovy 来使代码更加紧凑。我添加了一些解释性评论

if (!textOverlay) {
  textType = "" 

  // null is considered false, so no need to explicitly check for null
  if (url) {

    // getResourceResolver() replaced by resourceResolver
    // Page and Page.class are the same thing
    Page getPage = resource.resourceResolver.getResource(url).adaptTo(Page)

    // Groovy truth
    if (getPage) {

      // use String concatenation operator (also works in Java)
      showLink += ".html"

      // non-empty strings evaluate to true
      if (fragment) {
          // GString instead of string concatenation
          url += "#$fragment"
      }
    }
  }             
}  else { 
    //do something else
}
于 2013-07-01T12:34:12.493 回答