Code re-use between Grails project - keeping it DRY

Tag: grails Author: zxphistory Date: 2009-08-18

The Grails framework has a lot of constructs/features that allows for adhering to the DRY principle ("don't repeat yourself") within a project. That is: within a specific project you're seldom required to repeat identical blocks of settings or code. So far so good.

However, the more I've worked with Grails the more of I've observed that I repeat code not within the same project but between projects. That is project A has controllers, GSP:s and images that overlaps with project B. This is a maintenance nightmare since bug fixes in project A must also be fixed in project B, etc.

I'd like to take DRY to the next level by not duplicating code between my projects.

My question: How do you tackle this problem (violated "inter-projects DRY") in your own internal Grails projects?

Please be very specific/concrete. If possible try to include specific code examples on how you solve it in practice.

Best Answer

I agree with Lee, Using common/shared plugins is probably the best way to go. At one place that I worked we had quite a few internal plugins for this very reason.

The most common pattern is to put your common domain objects into their own plugin. This works really well for domain classes or services. We didn't end up refactoring the controllers, views, and static resources into a plugin, but the same principle should apply.

Long story short: Reuse of Grails artifacts = use a plugin.

Other Answer1

Writing a custom plugin is the best way. You don't need to release it to the public repository, as you can use a private repository somewhere within your own network.

I haven't had enough duplicated code yet to pull out a plugin (most of the code repeated in my projects seem to be covered by the various public plugins), but a plugin can be as simple as a few common domain classes or services.

Other Answer2

To add to Lee and Colin's points, which are both valid, I think thinking in terms of multiple plugins can yield other benefits.

For example, you can split up your application functinality into multiple pieces, and have different people work on them. Or it can yield results during deployment, if, say, you need to have two layers of access to an app - user-level and admin - if your domain model is in a separate plugin, as Colin suggested, you can easily build two applications and deploy them separately.

For my app, I have several plugins specific to my project - domain classes plugin, one that is a bunch of code for importing data (which I can run easily against my site), some other plugins for graphing and customization of scaffolding. It takes a bit more thinking, but I expect this factoring will yield dividends in the future as we bring on more people to the team.