Using getter and setters in grails or not?

烈酒焚心 提交于 2019-12-08 17:42:02

问题


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?


回答1:


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




回答2:


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"



来源:https://stackoverflow.com/questions/13547563/using-getter-and-setters-in-grails-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!