views:

224

answers:

3

When I want to apply the DRY principle, i.e. to unify the code of multiple Struts action for different use-cases (for example the administrator role and the operator role ), one option would be to use an abstract base class "BaseAction" for the action and then use "AdminAction extends BaseAction" and "OperatorAction extends BaseAction". I would apply inheritance for an abstract NewBaseAction, UpdateBaseAction, DeleteBaseAction, ListBaseAction.

But there is a principle that says "favor composition over inheritance" (http://www.artima.com/lejava/articles/designprinciples4.html). Is there a way to implement this in a clean way by using interfaces?

A: 

Statement "favor composition over inheritance" it's a clue for better design in general. Frameworks like Struts introduce own programming model. So you should write Struts action in a way that they adhere to Struts best practices.

In your case writing base class isn't bad. The question is how to design action class hierarchy, e.g. consider using DispatchAction for part of your functionality as your base action class. It will save you from creating a lot unnecessary classes.

Find "Struts way" use cases of DRY principle. More Struts best practises you'll find in free book Struts Survival Guide

cetnar
thank you for the link to the free struts book
poseid
A: 

As a side note:

Consider that "new" and "update" are often very, very similar operations, and can often be the same Action, with a single case statement, instead of two different classes supporting two different JSPs, for example.

Dean J
A: 

The "favor composition over inheritance" solution would be to either:

  1. move the shared code into a separate, non-Action class used by all the Actions in question, or
  2. move the different code into a separate, non-Action class, and have a single Action that can use any of these behaviors.

It's been a few years since I did Struts, but I think for (2) you'll need a little trickery in the struts-config.xml, configuring several <action>s of the same Action class, with different parameters, and having the Action be able to load or select a different behavior implementation depending on the parameters. This seems a bit non-Strutsy, as it takes some of the control logic that would normally be right there in the struts-config.xml and hides it in code.

But depending on your development culture that might actually be considered a good thing.

Whether the composition approach is worth doing probably depends on what code you need to share, and whether it makes sense to try to isolate that code from the Struts boilerplate.

The last Struts application I was on, we used inheritance. Might have been the right thing to do, might have been we just didn't know any better.

David Moles