If you've a domain class in a grails project you can also use getter and setter to write or read them.
For example domain class Book has attribute:
String author
In controller you've a book and you want to set the author for this book: This works with direct access to the attribute or with getter and setter methods although they aren't in the class.
book.author = "Mike Miller"
book.setAuthor("Mike Miller")
What's the preferred way of getting and setting attributes in groovy & grails?
They're the same. When you have an unscoped field like String author
, the Groovy compiler makes the field private and creates a getter and setter for it. It won't overwrite existing methods though, so you can define your own set and/or get if it's more than just setting and getting the value.
book.author = "Mike Miller"
is Groovy syntactic sugar for calling the setter, just like String authorName = book.author
is syntactic sugar for calling the getter. To see this, edit the class and add in a setter or getter and add a println, e.g.
void setAuthor(String a) {
println "Setting author to '$a', was '$author'"
author = a
}
You can use a decompiler to see the generated code - I recommend JD-GUI, http://java.decompiler.free.fr/?q=jdgui
There is no actual difference between the two since they both compile down to the same code. One of the benefits of using grails is not having to worry about the getters and setters boilerplate code, so I would strongly suggest the code below as it improves readability and productivity:
book.author = "Mike Miller"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With