2011-04-05 100 views
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方式做到这一点?

回答

1

我会这样做,因为它抽象了收集算法并使用标准的Groovy集合操作方法。

class Bar { 
    List<Foo> foos = new ArrayList<Foo>() 

    String collect(values) { 
    values.inject(new StringBuilder()) { b, val -> 
     b << val + System.getProperty("line.separator") 
    }.toString() 
    } 

    String getAs() { 
    collect foos*.a() 
    } 

    String getBs() { 
    collect foos*.b() 
    } 
} 
+1

,我们可以摆脱收集完全,只是做的Foo * .A()。加入(System.getProperty(“line.separator”)) – 2011-04-05 19:27:27

+0

,但请记住,加入不包括最后的分隔。如果这对你很好,那么是的,它会更好。 – 2011-04-05 19:28:55

相关问题