Question

So we have unique 'codes' for some of our grails objects (ref data), and when we want to retrieve them, we do so by calling them with their static code:

Currency.findByCode(Currency.DOLLAR)

Perhaps I'm completely wrong, but this seems like a very verbose and non-groovy way of retrieving objects (especially when you have to do it multiple times, for multiple objects).

Is there a more accepted approach (maybe having a reference to the object itself somewhere)? If this is the best way to do it, that is an acceptable answer. Thanks.

Was it helpful?

Solution

It depends. This seems like reference data. If the reference data is never gonna change, I wouldn't use the persistence layer at all -- I would code up a bunch of static variables that are the static reference data.

If you want to be able to change your reference data without redeploying, the most practical way would be to load them from the db. You would have some type of admin screen where you could manipulate the data. You would use 2nd level cache like ehcache to limit how much the persistence layer actually hit the db -- you can get really good performance this way. See section 5.5.2.2 of the user guide.

However, with your current approach you would have to redeploy on a change in your reference data, because the Currency.DOLLAR need to be coded in. It would probably be nice to not have to do that.

OTHER TIPS

One other thing that you could do to shorten up the code if you use static variables is to use static imports (this is actually part of Java, but I didn't find it till I moved to groovy):

If you do a static import of CurrencyType (potentially an enum holding the various types of Currency that you've defined) at the top of your class:

static import com.example.CurrencyType.*

Down in your code, you no longer need to prefix all of the references with CurrencyType, you can just do:

Currency.findByCode(DOLLAR)

If they don't need to change, you could also add a helper method to your Currency class to retrieve it:

Currency.groovy:
static import com.example.CurrencyType.*
...
static transients = ['dollar']
...
static Currency getDollar() {
    Currency.findByCode(DOLLAR)
}

That would let you use Currency.dollar in your other code. In those classes, you could also use a static import there to just refer to dollar:

static import com.example.Currency.*
....
println dollar // gets the dollar from the db and prints it out
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top