Reputation: 5552
I am working on a Grails project and I am trying to refactor it, extract code out of classes and put it in Helper Classes. The problem that I have now is that I have ended up with a bunch load of helpers (which is not really a problem) but the main issue is the number of static methods that i have. This is an example:
public static format(myFoo){
def nullOr = { it == JSONObject.NULL ? null : it }
.....
....
...
parse(blah,blah,blah)
}
private static parse(parseFunc, value, errors){
try {
parseFunc(value)
} catch (ApplicationException x) {
errors << x
value
}
}
Is this a correct approach? It is Groovy so should I use static closures instead? I am calling my helpers as this:
MyHelper.format()
Should I remove the static and create instances instead? What is the best approach ?
Upvotes: 2
Views: 62
Reputation: 35951
There are many ways to move code from Controller to an external class. But static method probably the worst way, you cannot extend this method, really hard to make unit tests for classes based on static methods, etc.
Grails have provides a special type of class, exactly for this situation: Services
So, you could create MyService
like:
def format(myFoo){
def nullOr = { it == JSONObject.NULL ? null : it }
...
parse(blah,blah,blah)
}
private parse(parseFunc, value, errors){
try {
parseFunc(value)
} catch (ApplicationException x) {
errors << x
value
}
}
and use from controller as:
def myService
def myAction() {
myService.format()
}
Read more about Grails services: http://grails.org/doc/latest/guide/services.html
Also you can register any Class as a Spring bean, and use similar to Service. See http://grails.org/doc/latest/guide/spring.html
Upvotes: 3