Reputation: 2053
I'm a groovy newbie so bear with me here. I love groovy's power to write less and often cleaner code but I'm trying to figure out if there's a better or more readable way of condensing these multiple if statements. It's a fairly straightforward code snippet but there's got to be a better way of doing this. I'm a newbie so any code snippets are greatly appreciated.
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
}
Thanks in advance for the help!
Upvotes: 0
Views: 8099
Reputation: 187529
This doesn't help with nesting, but there are a few places where you could take advantage of Groovy to make the code a bit more compact. I've added some explanatory comments
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
}
Upvotes: 1