Showing posts with label design patterns. Show all posts
Showing posts with label design patterns. Show all posts

Monday, January 18, 2010

The Unit of Work Design Pattern

"Everything that we do in this grid or in these fields, or in this group of tabs cannot be saved to the system until the Save button is actually pressed", says the business analysts.

This made Brian Carr and myself sit way back in our chairs and go "Hmmm... How can we solution this problem given our architecture?". The piece of software we're developing is built around SOA - our front end user interface is strictly ExtJS that communicates over ReSTful web services to our platform. Not a lick of CF on the front end. Shortly after those requirement gathering meetings we buckled down to analyze the problem at hand.

Here were some of our main considerations:

  1. ExtJS grids come with their own dirty/clean mechanism but that only existed for grids. Our client's requirement existed for any form control, not just grids. That option was out of the picture, especially in a SOA.
  2. Even if that functionality existed for all form controls, how would the platform handle saving these data points simplistically with minimal overhead and a clean API? In a traditional application that doesn't use data mappers or ORM, you'd usually have a post page that inserted/saved everything about that entity - for instance a User. You'd have a web form that when posted, would update all 20 fields even though all you needed to update was one email address. In an enterprise level environment this is a HUGE waste both in sending data over the pipe as well as causing unnecessary database overhead.
  3. We already had our own ActiveRecord implementation in place so handling crud operations from our domain model was extremely simple. 
  4. We already implemented the Observer Pattern that I've detail here, to handle saving composites among other things.
  5. At a systems level, we wanted to make small, light and quick web service requests to our platform whenever a form field was updated.
  6. It must be transactional. 
We knew that when it came to persisting an object singularly, it was solid. The api was such that these objects could save itself, load itself etc. We also knew that via our Observer Pattern implementation that when an object saved itself and there were any composite relationships attached to that instance, any of those composites would also save itself. So the only two problems where this:
  1. How do we logically group disparate objects in memory that are part of a unit of work - like a front end data grid or a group of data separated by tabs - to ensure that the underlying objects that encapsulated these data points can be saved, deleted or rollbacked (removed from memory) when needed. All while using our ActiveRecord and Observer patterns? 
  2. ALL of this must be managed across multiple independent http requests to the platform.
As usual Brian and I banged our heads against the wall trying to come up with a solid solution. Then it happened... enter the Unit of Work design pattern by Martin Fowler.

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.


Let's jump right in. I won't go over the exact implementation that we used in our software, but I'll provide a quick overview of this design pattern and how you might get started with it.

As always, here is the class diagram first.



So you'll see here that we've got:
  1. An IPersistent interface that has save and delete that returns a string for example purposes.
  2. A UnitOfWork (UoW) object.
    1. that has 3 fields to store the new, delete and changed stack. Which all should take an array of objects, preferably strongly typed if your language can support it.
    2. methods for adding to each stack.
    3. a method for committing and deleting the UoW.
    4. a get() method that will pull out an object from the UoW registry.
The idea is simple really. The UoW acts as a container/wrapper for disparate objects that will need to take part in a single logical transaction. 

Here is the code for the UnitOfWork object:


Pretty straight forward here. Class members are created to hold objects (stack) and methods are there to throw objects onto a stack. Notice how the entirety of commit() is transactional - it is all or nothing. We iterate over all the stacks and call the appropriate crud method. Also the get() method will pull out the object from the registry based on hashcode. You can do this however based on how you uniquely identify objects in your system.

Here's the scratch code:


Which produces:


In this test we:
  1. created three users
  2. displayed the unique hashcodes for each user
  3. assign user1 and user2 to to the UoW new stack.
  4. assign user3 to the UoW delete stack.
  5. then call commit() on the UoW.
Cool? On uow.commit() we've executed the appropriate database method to handle persistence and printed the save/delete messages to the screen. Of course in a real implementation this would be whatever persistence mechanism you have in place - DAO, ActiveRecord, data mappers, whatever.

Here are a couple key things to consider that this post didn't cover:
  • You will most likely need a singleton object, usually called the UnitOfWorkManager, that is responsible for managing your UnitOfWork objects. This plays into the feature of supporting UoW across multiple HTTP requests.
  • You will need a method on the UoW object that will remove objects from certain stacks altogether. This is for situations that perhaps the user clicks a "new user" object and a new Use robjects get registered. However he/she decides that a new user is no longer needed so they subsequently remove it but there are still other data changes that need to be persisted for that UoW. Don't get this confused for rollback() or registerDeleted().
This is one of those design patterns that you can find yourself getting really deep and start customizing like crazy. Be careful for that, make sure to keep it simple...

Hopefully you can use this as your jumping off point... Happy UnitOfWorking!

-Micky

References

Thursday, December 10, 2009

Understanding Strategy Pattern and Polymorphism - Two Birds With One Stone

First off, many thanks to the people that messaged me saying they enjoyed the Observer Pattern tutorial for saving composites. I'm really glad it helped demystify patterns and OO for you! And can I add it was pretty cool that these people were a mix from both CF and C# camps :) I am a big advocate of design patterns so I will not be shutting up about them anytime soon, sorry!


Today I wanted to touch on my favorite behavioral pattern - the Strategy Pattern.



What does this pattern solve? If you have an object that:
  1. Is constantly being subclassed just to override specific implementations (methods).
  2. Has a fugly method(s) that has to run through a mine field of if/case statements just to execute.
Let me start of by first saying when you use this pattern you can truly see polymorphism at its finest. And yes, polymorphism is achievable through ColdFusion. If someone tells you different, they are smoking crack. Say no to drugs.


I won't bore you with the computer science explanation of polymorphism so here's my simple, to-the-point summation. If objects are of different types but share a common derivative(s), they should be interchangable. This should help, lets keep it simple:
If A = B and A = C then B = C.
In the example above, B and C can behave polymorphically because they both share a commonality - they both are a derivation/implementation of A. Understand this critical principle of OO and you are well on your way to your OO awakening.


Moving on. Here's the official definition of the Strategy Pattern:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
What's this mean? I've underlined the key words in this definition. When you hear algorithms, think verbs which mean methods. When you hear encapsulate, think about delegating responsibilities to new objects whose sole purpose is to protect "something" and ensure that these objects are doing only  "something" and doing it well (SRP principle). And lastly, when you hear interchangeable think polymorphism. I'll reword that definition a bit to be in line with what I just described.
Define a family of methods and make sure you've encapsulated each distinct method implementation (algorithm) away into new objects so these objects may be switched out polymorphically at run time.
First, here's an abstract class diagram I put together:




For the purposes of this tuorial just imagine that the inside of the legacy code for subject.doStrategy() you've got the if/case problem going on. It's riddled with them. 
e.g. -if something, set this then return this way, if something else set that and return that way. You get the idea. 

In the class diagram above notice:
  • We have a Subject, think of this as concrete class that has a composite relationship to an implementation of IStrategyBehavior which subject.doStrategy() delegates to. 
  • The idea is that subject.doStrategy() should NOT have any switches or ifs or overridden via subclassing just to provide concrete implementation.
  • Also notice the UML note. We delegate to another object that implements IStrategyBehavior through composition (Subject is composed of IStrategyBehavior), this is where that whole "encapsulate each one, and make them interchangeable" is happening. We're saying listen, Subject, yes you will doStrategy() however you are delegating to a "strategy" property and ask it to call its own doStrategy(). This means at runtime you, Subject, don't care about how your are doStrategy()'ing, you're handing it of to your polymorphic property "strategy" and calling doStrategy() on that. We've just encapsulated that behavior away from Subject into its own set of classes or family of algorithms.
OK now we can move on to concrete designing but first lets understand our requirements We're going to use the standard gaming example well because COD:Modern Warfare 2 just came out and it's glorious. (xbox live : Error401, add me)
  • Build a Soldier that can fight() 
  • fight() cannot have any if's/switches inside of it
  • fight() will execute differently based off what weapon Soldier is holding - Pistol, Rocket Launcher and Machine Gun
Here is the concrete design:


Here notice the following:
  • We've modeled a Soldier (Subject) and are creating a strategy pattern for subject.fight().
  • Interface ISolder has a fight() method with the same contract for for fight() in IFightBehavior. 
  • We've created three concrete implementations (concrete strategies) of IFightBehavior - PistolBehavior, MachinegunBehavior and RocketLauncherBehavior.
  • Side note : This pattern can also be achieved through an abstract class and subclassing but try to stay away from inheritance as much as you can. Favor composition and interface based programming. You have more flexibility that way.
Code time - Soldier.cfc (I've omitted showing the interfaces. It should be straight forward how to create them from the class diagram above):

  • Critical piece of code on line 2 - fightBehavior is polymorphic. Interface based programming baby. In most of my examples I will program to an interface, not an implementation (concrete type). At run time this property can be switched out by  any object that implements IFightBehavior. That's polymorphism peeps. Simple as that. Don't over complicate it.
  • fight() delegates to the fightBehavior property. In the abstract portion of this entry, when I said that a Subject, in this case Soldier, doesn't care how it does doStrategy(), in this case fight() - this is exactly what I mean. You're simply calling getFightBehavior().fight(). Soldier doesn't care how its actually doing it because it could be doing it n number of ways through polymorphism. All Soldier cares about is that fight() returns a string. And we the developer have ensured that it will since fightBehavior implements the IFightBehavior interface which also has a matching fight() method that expects a return of string.
Here is what your concrete behaviors might look like. I've consolidated it into one image in order - PistolBehavior (goes Bang!), MachineGunBehavior(lots of bangs!) and RocketLauncherBehavior(goes Boom!):


  • The classes simply implement IFightBehavior and provide a concrete implementation for fight() in their own unique way. This is their only responsibility.
  • These three classes are now interchangeable with any return type, property or method argument with the type of IFightBehavior. Like where? Like in Soldier's fightBehavior property!
And finally the implementation and the results when run:


  • While I'm hard coding the actual setFightBehavior() above, let's imagine that the setting of the weapon came from a weapon select box from a form. When the form is posted you process the selections and dynamically set the behavior and subsequently call soldier.fight().
  • If you added 50 more weapons to the select box as long as there were 50 more behavioral classes that implemented IFightBehavior, your consuming code DOES NOT CHANGE and you don't have to needlessly subclass and override methods anymore. That's the beauty and power of this pattern - polymorphism at runtime which keeps your API clean. In our example above, calls to solder.fight() need not change.

To drive it home for the last time. A solution without this pattern would most likely force you to add additional subclasses or add if/case's in solder.fight() that checks for weapon a soldier is holding, do some process logic then execute fight() in a specific fashion. Unnecessary complexity.

So there you have it - the strategy pattern in a nutshell. I've managed to work out some pretty slick solutions with this pattern in CF and C# from organizing complex search algorithms to encapsulating gnarly business logic and I'm sure you could find umpteen more uses for it. This pattern keeps complexity low, forces objects to be highly focused with singular responsibility all while being easily scalable and maintainable.


Hopefully I helped you get another step closer to object oriented design pattern nirvana. And remember, as John Whish said to me and I couldn't agree more, "Death to inheritance - long live the strategy pattern!"

-Mick


p.s. - which pattern is next?

Monday, December 7, 2009

Using Observer Pattern to Save Composite Objects

I've recently been asked by a few people how I  go about saving composite objects so I figured it may be worth a blog entry.  I have a handful of applications I work on, both in CF and .NET, that share similar patterns for solving the problem of saving an object and its composites transactionally and in order. For example, if Object A has an Object B through composition and B cannot save until A is finished saving itself. Additionally if B has a problem saving itself, A should rollback as well. So how the frick does that all work?


As with really anything in programming it can be done a million ways. Some ways are better than others but there is no golden ticket. In my experience, an acceptable solution could be by way of a service object, business object, DAO, ORM (no brainer here) or a combination of all of the above depending on how abstract you want to get. In this example I'll walk you through how I solved this problem using the tried and true Observer Design Pattern.


The Observer Pattern was created by the Gang of Four (GoF) - Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Long story short back in 95' these very smart guys identified 23 recurring software problems, designed solutions for each called a "design pattern" (which borrowed from proper architect Chris Alexander) and released a book to school us on it. If you don't own this book you definitely should, shame on you. Familiarize yourself with the problems and patterns the GoF describe and lock it away in your brain cache. When time comes, you'll be well equipped to tackle some tough design problem thrown at you. Cool? Good. Here is the definition of the observer pattern:
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
So given the composite save problem at hand, I looked to design patterns to see if I could use one as a viable solution. I think I was on a long flight to Boston so I spent the entire flight sifting through design patterns and with the help of the book and a beer or two, I was pretty sure the observer pattern would be a good match. Thinking of the problem at a high level we have a possible one-to-many relationship between an object and its composites that needed behavior between the two such that when an object is saved, it needs to notify the composite objects who are waiting intently to save themselves but cannot before that initial object is saved successfully. For the purposes on this blog entry I've created a couple class diagrams that explain the design, then we'll jump into some code. Here's the high level/abstract:




[click to view full image]

You'll see that there are two interfaces involved in this implementation:






  • IObservable - Any class that needs to be observable must implement this interface. It contains methods to attach() as a observer, detach() an observer and to notify() its observers of an event. Simply put, if you think of a pub/sub technique, an object implementing IObservable will be the publisher.
  • IObserver - Any class that can attach itself as an observer to an an object that implements IObservable must implement this interface. It has the API that IObservable will call when it notifies its observers.

Now here is the UML with concrete implementations:




[click image for full view]

Looking at this diagram you should be able to discern the following:






  • We have a Person that has an Address - here's our composite relationship.
  • It's a one to many relationship. A Person can have multiple Addresses.
  • Private member - observers - is of type IObservable[]. Whats the brackets for?
  • There is a save() method is each object. To keep things simple just imagine that save() is delegating to a DAO or using some snazzy ActiveRecord pattern to actual persist the record. Bottom line is don't worry about it for this example.
  • Person is observable by way of implementing IObservable. That little symbol with the interface name above each class is called a "lollipop", no joke. It means this class means  "implements" whatever name is shown.
  • Address is an observer by implementing IObserver.
  • addEmail() has an optional second parameter "attachAsObserver" that is default = true. Remember this, you'll see how this plays into a clean API when using this pattern.

A concrete implementation of Person might look like this:


[click image for full view]
You'll notice that:









  • attach() will push an observer into the private subscribers array. This method is responsible for allowing observers subscribe to it (Person).
  • notify() loops over all observers and invokes update("some_event") on the observer that tells the observer, "hey dude, just fired "some_event". In the same breathe it is also inspecting the result of notify() that sniffs for a return of false which means something went wrong so return false and stop notify execution. I know that there are possible scenarios where you would not want to stop processing and move along but exploring that is out of the scope of this example. Although if you go ahead and re-factor this example to do this I'd love to see it!
  • We've overridden addAddress() which manages our address collection. This is essentially the setter for Address but called it add instead of set because of the one-to-many relationship. Notice that the we've added a second parameter to this method called attachAsSubscriber that has a default = true so its optional. In the logic, we're saying if attasAsObserver is true then automatically attach the Address as an observer to Person.
  • save() calls super.save(). Make believe Person extends some base persistence object.
K - on to some Address code:


[click image for full view]
Here you'll notice that:
  • update() will receive the event message and process accordingly. Please do not confuse this with a CRUD operation. As a best practice in you database layer there really shouldn't even be a method called update(), rather call it save(). Anyway, what update() will do is inspect the event that was just fired by IObservable and if it is a "save" event, then return save(). This is a very important piece right here! The return of save() gets bubbled up to the observer. This will ultimately determine the rollback which we'll get to in a second. You can optionally override Address.save() also do the same algorithm as Person.save() if Address also needed to be observable and notify its own observers.But thats up to your requirements. Just want to drive the point home that pattern can be implemented n-levels deep. D observes C who observes B who observes A. A = mack daddy.
  • update() by default will return true.
  • update() uses the eventInfo structs observable key to get the Person that was just persisted. This allows Address to save() correctly. I chose to go with a struct for eventInfo because an event might be fired in the future that needed to pass a handful of additional info to its observers. This allows for future flexibility.
And finally here is how you might possibly consume this API in its entirety. For the purposes of this example its in a cfm page but you'd probably want it somewhere in a persistence layer - perhaps a controller/service type object.


[click image for full view]


Here we have:
  • Created a new Person and Address.
  • Associated the Address to the Person. Under the hood this will also attach Address as an observer to Person but the API remains simple. Looks just like a simple setter - addAddress(in Address). It has no idea the observer pattern is going on in the background.
  • We are simply making the entire save process transactional and when an observer fails to save or an exception is thrown, we handle it accordingly by rolling everything back. You could have 100 objects in the queue to be save()'d, fail on save() #99 and it'll nicely rollback everything for you.
  • And now since we've kept the Observer pattern extremely generic, you can feel free to leverage this implementation for any other event, not just saving.
There you have it. Observer pattern goodness that could hopefully make the GoF a little proud. I've implemented this technique both in .NET and CF and it works great for me. For my C# peeps, Microsoft is releasing an set of Observer Pattern interfaces that will support this type of usage out of the box. Check it out here.


So in closing, this is just one technique of many so I encourage you to explore some other ways and please point me to ways you've done it in the past. I'm interested in seeing it!


Apologies in advance for any bugs in this code. Everything was typed on the fly but hopefully you get the idea.


Till next time my friends.

-Mick



Resources:
Design Patterns with C#
Christopher Alexander, founder of the design pattern in architecture.
GoFyou owe it to them so buy their book