Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getter and setters in grails or not?

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?

like image 372
whitenexx Avatar asked Nov 25 '12 01:11

whitenexx


2 Answers

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

like image 76
Burt Beckwith Avatar answered Nov 12 '22 06:11

Burt Beckwith


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"

like image 32
Simon Piel Avatar answered Nov 12 '22 06:11

Simon Piel