2011-04-05 65 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

相關問題