2013-06-30 115 views
0

我是一个时髦的新手,所以在这里忍受着我。我喜欢groovy编写更少且通常更简洁的代码的能力,但我试图弄清楚是否有更好或更可读的凝聚这些多个if语句的方法。这是一个相当简单的代码片段,但这样做有一个更好的方法。我是一个新手,所以任何代码片断都不胜感激。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 
} 

在此先感谢您的帮助!

+1

我看不出它是如何更紧凑,仍然可读的。该代码有什么问题?除了它似乎有很多责任(许多变量似乎不相关),我没有看到任何代码重复。 –

+1

你应该考虑使用'URI'而不是手动构建URL ......它将采用所有讨厌的东西,如编码等。它的构造函数是“无效的” – fge

+0

我总是在印象中,我可能是错误地认为有多个嵌套的if语句是不好的做法。感谢提示@fge –

回答

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 
} 
+0

谢谢@Don非常感谢您的帮助 –