Wednesday, July 05, 2006

The Transaction Script Pattern

I recently called upon the services of the Transaction Script pattern to organise new business logic for my current software project. I had a bunch of procedural and database-centric logic to implement and needed a way to structure it so that it would be maintainable. I appear to have chosen a reasonable solution, because this pattern has helped me create a simple design that, so far, has proved easy to work with. I also ended up with code that is more readable than I could have hoped for. Go me!

The Transaction Script pattern is as simple as they come. It organizes multi-step business logic into discrete procedures with each procedure implemented either by a single method, or by a group of methods within a dedicated class. The pattern takes its name from the fact that most often a procedure will be executed within the scope of a single database transaction.

Martin Fowler presents the Transaction Script pattern in his book Patterns of Enterprise Application Architecture and it is also catalogued on his site.

In adopting the pattern for my own code, I opted to give each procedure its own class, a la the Command pattern / Object Method refactoring. I think that this decision has been central to my success with the Transaction Script pattern.

I found that partitioning the procedures into their own dedicated classes made for rapid progress, because it facilitated ‘coding by intention’ and refactoring. I was able to decompose each procedure into a set of small and cohesive methods that found a natural home within the class implementing that procedure. These methods could thus share state via instance variables, which removed the need pass data around. Where logic was duplicated across procedures, I found that I was able to extract the duplicated code into a method and pull it up to the base class.

I’m very happy with how it’s playing out so far, but it will be interesting to see the long-term maintainability of this design.




2 comments:

Raheel Khan said...

Interesting approach. I am interested in finding out how you have dealt with Entity objects and Business objects. The classes you mentioned here are essentially wrappers for transactions. What about the de-coupling of entity and business objects.

Tony Byrne said...

Raheel,

The project in question was a Perl web application which had been developed over a number of years and which was in need of refactoring. The use of the Transaction Script pattern was an attempt to wrap the database calls and introduce some layers to the application.