0
下面是一些示例代码的问题什么是反映实例方法的惯用Groovy方法?
class Foo {
String a()
String b()
}
初始版本吧
的class Bar {
List<Foo> foos = new ArrayList<Foo>()
String getAs() {
def builder = new StringBuilder()
foos.each {
builder.append it.a()
builder.append System.getProperty("line.separator")
}
builder.toString()
}
String getBs() {
def builder = new StringBuilder()
foos.each {
builder.append it.b()
builder.append System.getProperty("line.separator")
}
builder.toString()
}
}
所以很明显我想重构这个。我目前有这样的:
class Bar {
List<Foo> foos = new ArrayList<Foo>()
String getAs() {
collectSections "a"
}
String getBs() {
collectSections "b"
}
private String collectSections(String method) {
def builder = new StringBuilder()
foos.each {
builder.append it."${method}"()
builder.append System.getProperty("line.separator")
}
builder.toString()
}
}
这是最好的groovy方式做到这一点?
,我们可以摆脱收集完全,只是做的Foo * .A()。加入(System.getProperty(“line.separator”)) – 2011-04-05 19:27:27
,但请记住,加入不包括最后的分隔。如果这对你很好,那么是的,它会更好。 – 2011-04-05 19:28:55