What should "idiomatic" Groovy code look like? What are the good practices in terms of syntax style, typing preferences? What are the nice shortcuts to be aware of to be more productive? Guillaume Laforge will answer those questions along the way!
@glaforge Fields and static fields require visibility 19 class HelloLondon { static String message = 'Hello London' String name
HelloLondon(String name) { this.name = name } String greet() { return "$message, $name speaking" } } You created both an instance property and a static property!
@glaforge Get rid of the useless ‘def’ 22 class HelloLondon { private String message = 'Hello London' private String name HelloLondon(String name) { this.name = name } String greet() { String result = "$message, $name speaking" return result } }
@glaforge Get rid of the useless ‘def’ 23 class HelloLondon { private String message = 'Hello London' private String name HelloLondon(String name) { this.name = name } String greet() { def result = "$message, $name speaking" return result } } But it’s fine to use ‘def’ for local variables
@glaforge Switch / case on steroids 56 switch(obj) { case 123: "number 123"; break case "abc": "string abc"; break case String: "is a string"; break case [1, 2, 3]: "in list"; break case ~/.*o+.*/: "regex match"; break case { it < 3 }: "closure criteria"; break default: "unknown" }
@glaforge Of the importance of contracts • Use explicit typing for – method signatures – properties & fields • Nice for – Java interoperability – documenting your APIs – IDE auto-completion and refactoring 72