Thursday, December 17, 2009

Quicksilver - REST, MVC, AOP in 26 lines of code, 6 annotations and 0 xml.

You read it right. Let's jump right into how the Quicksilver Framework accomplishes this.





Here is the view - getStuff.cfm





And finally, the results when run:




So, how did we just implement MVC?




STEP 1 - Annotate your component with @viewRoot. This is where all your views are stored.
STEP 2 -  Map the uri and http method to your url. You can optionally use the @returnTypeName annotation so when defined, it's value is mapped to the methods return and will be available in the request scope of your view Look at the getStuff.cfm screen cap above..
STEP 3, non-step - Sit back and relax. Watch the goodness of convention over configuration. QS will look in your @viewRoot for a directory named after the controller, in this case SampleService. Then within that directory look for a file whose name matches the method being mapped.


How did we implement AOP?


STEP 1 - Annotate your cross cutting method with @aspect and give it a name.
STEP 2 - Decorate the target method with @preAspects and/or @postAspects annotations. A comma separated list of the aspect names.


So when getStuff() was run, Quicksilver first ran the aspect addRandomStuff(). All in 2, dos, ni steps. Cool eh?


How did we implement REST?


NO STEPS! - You already did when you annotated for MVC.Proof? Lets hit that URL again but leverage Quicksilver's automatic response serialization (of array, structs, queries)  and get back a JSON representation of "stuff" instead of going through MVC. Simply append ".json" to the end of the url, nothing else needs to change. Hit the url with .json and you'll see this:



That's all folks. All of this in 26 lines of code using 6 annotations and 0 xml.

Hope this helped and please hit us up with any questions.

-Micky

Tuesday, December 15, 2009

Design Before You Develop - Intro to Class Diagrams with Quick Reference

If you already are a design-before-you-develop junkie like I am, daps to you. You can probably stop reading here and move onto the next blog in your queue. For the rest that are curious about it but don't know where to start, read on.  It's my opinion that you should get into the good habit of designing before you develop. Even if the design takes you 10 minutes on a scratch pad, a quick design session on a whiteboard or several days in a full blown modeling tool, you should do it.

Why? Because it's during those sessions that you and your team can express the intended inner workings of your software modules, poke holes in it, rinse then repeat as needed. You can focus on a list business of requirements, design the class diagrams and literally step through the requirements allowing you to articulate the path of execution that'll take place to fulfill each requirement. All of this is done without a lick of code. You discover design flaws early on, not during development. That's risky. You can even take it a step further and generate sequence diagrams against your UML model and requirements, they are invaluable! But sequence diagrams are outside the scope of this article, we'll get to it some other time.

I'll say it again and again that during the design process you need to forget the code. Coding should be the easy part. It's the design that lends your software scalability and flexibility. Without a proper design, you run the risk of causing not only future headaches for yourself and your team but more importantly, the business. Yea yea, without the design phase it's so much faster to release a product. Sure, you can tell your boss/client what you're doing is rapid development. Sure, your bosses will be happy for the time being cause you got it out so quick. You're the hero. You're the man. But who cares if you are spending the next year after your go live fixing code, trying to re-design after the fact and burning through company cash hand over fist. Or worse, bandaiding already production level code with cut rate code because everything is an "emergency" and you don't have the luxury of thinking things through anymore. All the while the boss that was singing your praises is no longer impressed that you put out a piece of software that constantly breaks. It's a vicious cycle and could've been avoided by dedicating a little more time to designing up front. Use the above as a case to your boss when you need a little more leeway to get some design cycles in in the beginning. Just like Ben Franklin put it:
An ounce of prevention is worth a pound of cure.
He was a pretty smart dude, and his quote certainly applies to software engineering. Let's put in that ounce of prevention by designing first eh?

UML to the beginner can seem pretty damn intimidating. In my comp sci class I remember cracking open the UML section and my eyes glazed over at all the fricking symbols. I thought to myself, how in the hell am I going to memorize all this? After I got some real world experience, it's really not that bad. Given, you can get pretty deep into it I find that I'm able to express a software model with only a few symbols. I thought I'd share with you some of the ones that I use all the time with Microsoft Visio however the symbols below are not application specific, they are universal symbols. Here's the quick reference:



These symbols should be more than enough to get you going. Below is a what a real class diagram might look like using all above symbols:



In the above class diagram, there are two applications being modeled at the same time that use shared components. A school app and a war game app. I've put together some questions I'd ask myself while making some observations of this class diagram:
  • Person is being extended by Student and Soldier. 
  • Soldier is in the common package. "Is this correct? Shouldn't it be in the wargame package? What happens if its not?" 
  • Soldier can have many pistols. "But is that true? Should it be a one to one? Should there be a collection manager of sorts to keep the api simple? Better ask the business."
  • Student can have many books via its multiplicity. "Same multiplicity questions apply here?"
  • Student is teachable, since it implements ITeachable. "Are the methods defined here really granular? Do they really belong in this interface? Is there anything else I can add to this interface?"
  • A pistol implements IWeapon so it must fire.
  • fire() on the IWeapon interface returns numeric. "Is this the proper return type?", "Should it be another return type?", "Are we going to calculate fire() based on the numeric damage its dealt?,  If so keep it. If not, let's redesign".
  • Soldier doesn't have an interface. "Does Soldier need an interface?", "Is there something that all soldiers must be able to do? Let me dig into the requirements and do some textual analysis."
  • Person has a firstName, lastName and age member. "Are these shared across all Person objects?". "Do they need to be specific to a subclass?"
  • All classes are have their packages before the name so it's clear where each class should exist.
This list could go on and on!

All of these questions should be addressed during design to ensure you and your team have a clear path of development. There are a bunch of open source tools out there especially in C# built into Visual Studio (and I'm sure Java has theirs too) that will parse through class files to generate UML diagrams ad hoc. For ColdFusion developers, at the time of this entry, Mark Mandel has been recently tweeting about a prototype he's working on that will generate UML using ColdDoc and UML2 tools. Initial screen caps looks promising, so it's definitely something look out for. For more info check out Mark's twitter.

I'll also add that it's important to note that these tools should not be misused. Meaning you shouldn't develop first just to produce a class diagram against off-the-cuff code. These tools should be used when you need a way to dynamically create accurate class diagrams from current code for a number of reasons:

  1. You may be working within an enterprise level organization where there are multiple teams with their own special access to certain aspects of the code. Developers often need to know how to leverage an API in which they have no access to the source. In my experience that's where these automated UML tools come in handy. You can print it out and ship it off to whatever team needs it. From the UML, they can discern the contracts in which they need to develop against.
  2. You don't have to deal with the headache of documentation maintenance.
  3. You need to reverse engineer and analyze design at a high level, especially if the code base is pretty huge and there's a lot going on.

So that's class diagrams in a nutshell and hopefully you'll give the design before you develop approach a try if you haven't already. It may seem like a long and drawn out process at first but believe me practice makes perfect. Take it little by little. Maybe try it with that new module that needs developing or that module that is in need of some major refactoring that you've been putting off for months. After awhile, you'll be zipping through design sessions quickly because you've trained yourself to identify patterns and problems during that analysis phase. It'll eventually become second nature and you'll soon feel dirty not doing some form of design up front.

Hope this helps.

-Micky

Resources
Beginning C# Objects: From Concepts to CodeHIGHLY recommend this book for the beginner UML/OO developer. C# is in the title but the content applies to all languages.

Sunday, December 13, 2009

Quicksilver and REST

Let's talk about some REST a la Quicksilver shall we? In my Quicksilver primer post I touched on what it's all about and its automatic dependency injection capabilities. Today we touch on another one of its core features - REST. If you are not familiar with the concept I encourage you to look into first before reading this post.

Let's set the stage. Imagine you built a simple informational design patterns site that explains design patterns. It's been in production for awhile now using OO best practices like service objects to be the intermediary between internal api calls and the data layer. This site has been using Quicksilver because they wanted a powerful flexible framework to one day use AOP and REST in addition to Automatic Dependency Injection just in case they needed to open up their API to other programs. Fast forward to now, they've been getting requests to open up their API via web services. They can use Quicksilver's REST support to do this easily

To understand how QS provides a simple solution to this, let's explore a possible alternative. They could develop soap based web services that consumes their service layer. Not a bad approach, but possibly time consuming and if done incorrectly can also lead to duplicate code since the methods will need to understand how to return json, xml, or a custom format. Also each web service endpoint would be exposed through a cfc - /path/to/webservice/DesignPatterns.cfc?wsdl and call methods off that.  Ugly ugly ugly. Doing it this way is unorganized and resources are all over the place with crud-type methods names - saveThis(), updateThat(), getThis() etc. Get my drift? How does Quicksilver solve this?

Let's dig into the code that we are about to REST'ify.

We've got a design pattern service with one method getCreationalPatterns(), it simply returns an array of strings whose values are pattern names. Here's the code:


Simple enough right?

  • We've got a singleton annotation at the top that tells Quicksilver that this should be handled as a singleton. This is part of automatic dependency injection baby.
  • getCreationalPatterns() simply returns an array. In the real world this could (and should) get as complex as you wanted to, perhaps delegating to a DAO or gateway or even another service but for this example let's KISS.
Good, now take a look at the unit test written for this. Again keeping it simple, let's assert that we are getting five elements back. Using MXUnit, let's write it:



Test passed. Sweet.

Ok so let's now expose this method as a RESTful endpoint that returns a json representation of creational patterns shall we? Let's not create a new component and go through soap based web services, it too much work :) Let's use Quicksilver. How? Use two, count em, two simple annotations in your service object.

  1. @url - this annotation is used to specify your url pattern. 
  2. @httpMethod - possible values are GET, POST, DELETE, PUT. You can use multiple methods separated by commas.
So here's the updated code:



Lines 8-11 baby, that's all you need. Now when I crack open my browser and hit:
http://localhost:8500/learnqs/howtorest/api.cfm/design/patterns/creational.json
We get a json representation like so:


When opened looks like:


See how easy that was? We've just opened up our API via restful web services to our consumers quickly and easily.When this URI is called from an ajax request, consumers are free to use the json representation of the creational patterns however they wish.

Lets take a closer look at that URI:


Notice:

  • We've mapped an HTTP GET call to the url "/design/patterns/creational". Talk this out. Map a HTTP GET to the /design/patterns/creational resource and give it to me in json.
  • @httpMethod GET is the annotation to map an http method a function
  • api.cfm is the required cfm template that must exist for CF to parse the uri. This can be named whatever you want. index.cfm, rest.cfm, I just arbitrarily named it api.cfm. Again, as with any request that must go ColdFusion, you must go through a cfm page. In Quicksilver, however, that cfm page does not need to exist. Just the fact that its in the URL is enough, we'll take care of the rest. In our example, api.cfm is not a real file.
  • After api.cfm comes the path we set in our @url annotation.
  • Automatic Serialization - Quicksilver will automatically serialize arrays, structs and queries to json for you and since our return type is an array, automatic serialization is kicks in.
  • By default the return of this call also returns an HTTP status code of 200. You have full control over the status codes as well.
Easy right? Imagine this uri being called via ajax call from jQuery, ExtJS or whatever ajax feature you use. You'll get a json representation back.

Lastly, you've heard use say again and again that the Quicksilver framework does not get in your way and keeps your codebase HIGHLY testable. We're not just saying this to sound cool, we'll prove it. Lets re-run our unit test even after we  activated REST.



Look at that :) Test still passed. There's your proof. Quicksilver doesn't inject itself into your code rather it hangs out outside of it. It allows you to implement code and test without the framework in your way and we mean it. How? Via annotations baby! Read more about in the Quicksilver primer post if your confused.


side note: Just FYI - Quicksilver also supports custom representations prepended with whatever extension you want - .extjs? .pdf? .myCoolExtension?. Also allows you to have FULL control on HTTP status codes that are returned as well as the ability to send variables via the URL, http raw post, form post etc.  No problem. We'll get to that in future blog posts, promise. Or check out Brian's Quicksilver blog. Link at the end of the article.


So to wrap up, I hope you now see how Quicksilver is as unobtrusive as possible. We REST'd our application with no added components, no messy soap web services, no duplicate code all while remaining organized and  highly testable. No framework artifacts riddling your awesome code. How about that? A framework that actually cares about risk management.

-Micky

Resources
Quicksilver Blog - entries by the one and only Brian Carr. Check it out!

Friday, December 11, 2009

Quick Tip - See nested conditionals? Consider Guard Clauses

Just a quick tip when you are refactoring code with crazy nested if/else logic. As a rule of thumb if you see a method that has conditional statements check to see if these exists:

  1. Is there a private variable, let's call it x that is private to the function that is being set within each (or at least a majority) of the if/case legs whose value is a method call?
  2. Is x is being returned at the end of the method?
  3. You got nested conditionals?
Here is what it would would like:

Notice the:
  • result  private variable at the beginning of the function
  • result is being returned at the end of the function
  • Nasty nasty nasty nested conditional that sets result to the value of a method
If the above is true or the code you are refactoring looks similar to this, you might want to look into using guard clauses. Sounds more complicated than it really is. Basically see if you can refactor it like so:
  1. Remove the private variable thats being set during each if/else leg.
  2. Return the method or the condition that is setting it.
Simple as that. Here is the code above refactored:


Notice now:
  • No more nested if's
  • After each if/else leg, we are returning the method.
Given that some legacy methods you are trying to refactor are not as trivial as this and each have their own unique level of suck - this is always a good start. This keeps your method simple, less complex and highly testable because each execution path is linear. Guard clauses baby, a good alternative to the strategy pattern.

HTH

-Mick

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?

Wednesday, December 9, 2009

ColdFusion Comes of Age - Community to Follow?

About a month ago my fellow CF'er Mike Chandler showed me this article. The initial once over was quick with only a handful of comments that made me chuckle then I moved on. As I was sifting through old email I found the link and decided to see where the conversation went, if anywhere. That, my friends, is what inspired this blog post.

Basically a CEO announced a launch of their new site which was rebuilt in Java and somewhere in the post called ColdFusion outmoded. I’m writing this entry not because I’m miffed that he called ColdFusion outmoded, I’m writing this because of some, not all, of the responses that ensued. People are entitled to their opinion both the CEO of MFG and the responders alike but I really couldn’t believe the level of back and forth going on between commenters. Some responses reminded me of elementary school where kids are cracking “your momma” jokes back and forth, getting heated over well, nothing. Sarcastic banter and throwing out stats is not going to make your point, especially in a forum. And seriously, all the CEO said was that it was "outmoded". Give me a break, that is not a big deal people.

So this got me thinking, “What do we as a community need to do to be taken seriously?”. Here's my $.02.

First, let’s stop bashing other languages. There's something to learn in every language regardless of what side of the fence you are on and whether you care to admit it or not, its true. There is always something to learn. AlwaysSecondly, let's stop responding immaturely when someone says “ColdFusion {insert derogatory verb here}”. Let it go. Breathe. Do a 10 count. I get it, we are all passionate about ColdFusion. But we should be even more passionate about what ColdFusion is used for - software engineering. More passionate about solving complex problems that completely kick our ass. The kind of problems that you find yourself solving when you're dozing in and out of consciousness in the middle of the night cause you can't sleep, just to wake up still trying to solve it and can't get that computer on fast enough. And hey, in my experience ColdFusion allows you to solution those types of problems and solution them pretty damn well - thats why I love it just as do you.

Adobe and the ColdFusion team hit the nail on the head with CF9. They’ve armed us with the capabilities to enter the arena and stand and bang like the big boys. It gives us the ability to execute the core tenets of object oriented programming - encapsulation, inheritance and polymorphism. It makes OO feel natural just like C++, Java and C# with its new and improved script syntax and quick object creation. It feels grown up. It feels like it has come of age. It demands to be taken seriously. But there’s one critical piece missing. We as a development community need to come of age with it. We need to mature. We need to start designing before we write code. We need to really understand object orientation and design patterns. Strive to be software engineers, not just complacent code monkeys. We need to advocate designing before we develop because identifying problems with our architecture while it’s in design is much better than discovering them hundreds of hours into development and hundreds of $'s in the hole. We need to design, poke holes, re-design, poke more holes, then lastly start coding (this should be the easy part). But hey even if you need to rework design during development, your design should be such that its easy to maintain and modify. We need to architect applications that scale. That are flexible. We need to understand why to use Framework A, B, and C and more importantly how they work under the hood. We need to fully understand the problems these frameworks were created to solve.

Lastly and most important, we need to solve problems just like the big boys and be sure to share the solutions amongst each other. Problems whose solutions cannot be summed up with “check out how I used this really cool CF feature to create a pdf or make an ajax request”. Other languages and developers don’t care about that. They’ve got their own cool features that they'll argue it puts yours to shame and vice versa. We need to solve problems that transcend languages. Problems that only sound design, architecture, design patterns and well written, efficient algorithms can solve. Once you solved it, share your solution. Get involved. Publish it. It’s only then that we can be taken more seriously. It's only then we can share complex solutions that programmers from other languages can stumble upon and implement. Solutions that came from the mind of a ColdFusion software engineer. A solution that programmers from another language can respect and apply with their language of choice.

CF9 has come of age and has equipped us to do all of the above. It’s been our responsibility as a community to come of age with it. Next time that startup comes knocking, do it right from the beginning. The next time that corporate piece of software needs a new module, do it right from the beginning. Do it object oriented. Use frameworks for the right reasons. Even dive into design patterns. There is a reason for object orientation and blackboxing, that's why its taught in computer science. Don't fight it and know that advice and direction is only a tweet or email away - our community is great about that. Apply those concepts and over time that piece of software you wrote will grow and scale easily and it's then that your piece of software will be a testament to ColdFusion and its capabilities. It's then we'll no longer have to squabble over statistics because we've got proof of high profile adoption.

We're on the path to get there. We have a fricking ton of brilliant minds in this community doing some very cool things every single day, you included.

So let's walk the walk and stop talking the talk. Let's build better software as a community. It'll end up speaking for itself.

-Micky

Tuesday, December 8, 2009

MXUnit - DataProvider Goodness

Just when I thought my unit tests were pretty dang light its become even lighter after I came across Marc Esher's blog post about DataProviders that shipped with the new MXUnit 1.0.8 release


In my unit tests, especially tests that are very data driven like DAO's and validators I found myself doing this alot:









As the screencap shows, there are many time where you need to setup data sets that will be used during assertions or mocks and usually start out inline. You'll find yourself duplicating tests that really assert the same thing just with a different data set. I admit that in unit tests I've become lazy and often times do not even create a private method that returns a pseudo dataset for reuse, yea yea I'm sorry. I just duplicate this code above in each method that needs it because it feels innocuous in a test, I mean after all its simply a query with one record for goodness sake. Well with the new MXUnit data providers its time for me to stop whining because they've made it extremely easy to declare a dataset (DataProvider) and have it injected into the test by doing just three things so:

  1. Create your dataprovider in the setup() as a class level member (variables scope)
  2. Annotating your function using the @mxunit:dataprovider annotation with the value being the dataprovider you want to inject.
  3. Referencing that dataset as an argument in your test method
Here's how it looks like now (with the provider flow):



Booya - that DataProvider is now available to any test method in that TestCase. No need to write duplicate code or private methods. MXUnit simply passes it off politely to your test method. If you have multiple rows in the query it iterates each and fires your unit test, no more separate tests essentially doing the same thing. Damn you MXUnit for making me write better, more efficient code.

MXUnit all the way.

-Mick

Resources

Quicksilver Framework - A Primer

Let's chat about some Quicksilver! Quicksilver was created by a good friend of mine, Brian Carr, who has brought us the first RESTful framework for CF called Powernap. For reasons unknown to me he has given me the honor of working side by side with him on  Quicksilver - a framework that  allows programmers to quickly create MVC applications with some powerful and flexible features.


When we say powerful features, we mean it. We all know that  MVC is powerful and flexible because its given.... No need to stress that. The fact that "MVC" is in the Quicksilver USP is enough. When we use the words powerful and flexible we are truly talking about the features as well. QS offers so much more than just MVC. So... much... more.


At a high level, here are the 4(+1) core tenets that we stuck to when developing QS:

  1. Provide MVC 
  2. Native Aspect Oriented Programming(AOP) capabilities
  3. Provide Automatic Dependency Injection
  4. Provide fully functioning REST support
  5. Provide 1-4 easily and transparently as possible meaning there should be no framework artifacts in your actual implementation code getting in your way resulting in an app that becomes extremely dependent on its framework. If we achieved this we can guarantee that your application remains HIGHLY testable which means better and more focused tests, which leads to non-fragile software, which leads to happy customers and ultimately you not having to be a nervous wreck every time a code migration is ordered.
So how did we achieve this? By using Annotations. We took a page from Java/C++ and refer to them as annotations but other popular programming languages have the same feature but named differently e.g. C# calls them Attributes. Although there are many different flavors of annotations from language to language, at the end of the day annotations will provide metadata for your class files, its members and source code. With the release of CF9, you can append this metadata by way of using the cf comments with two asterisks like so:
Notice how the property is annotated via a code comment that this factory property should have a type of "path.to.some.factory". What's so cool about this? It's because an annotation is not part of implementation code - code that goes inside an actual method to be run or as a class member. Anything inside this annotation is available to the developer to introspect at runtime but actual implementation code knows nothing about it. This gives developers the ability at "compile" time to introspect source and perhaps churn out automated documentation, run debug level tests when "compilation" is running in debug mode, or in our case build a framework that gives you some really powerful features like the ones I explained above.


My intent on this entry was not to touch on every single one of those points but lets start with one - Automatic Dependency Injection. If you look at the example above we are simply telling the object that it should have a property called "factory" that has a type of "some.path.to.factory". No dependency injection going on here son, zero. That is unless you've installed Quicksilver and have either Lightwire or Coldspring installed in root. QS will by default look to see if you have Lightwire installed if not it looks for Coldspring. We decided to go with Lightwire first since it manages transient objects better than Coldspring. Ok back to the code - you've installed QS and Lightwire and now when you create your object, QS will automatically inject those dependencies for you. No XML, no bean configuration, nothing. Just the simple fact that you've annotated your property with the type is enough, QS takes care of the rest. So when you ask for an object that has property annotations attached with either the @type annotation or even inline property declaration like - property name="factory" type="some.type", you will have a proper object and its correct dependencies.


But what about for our interface based programmers that love properties that are of an interface type? Properties that doesn't have an actual concrete implementation defined as a type? Good fricking question! Here's how QS supports that with an addition annotation.










Simple type your property to the interface then use the @implementation annotation to give the actual concrete type. Your property still stays polymorphic and the world is good to you again.


So now you see the power of QS by way of annotations. QS exposes all of its features through annotations. We grew tired of having framework artifacts littered throughout code. Controllers that needed to instantiate this and extend that. XML configs spanning hundreds and hundreds of lines. With QS you get MVC without that nonsense and so much more on top of that. And we've tried our best to make sure that the "so much more" is NOT a pain for you to implement when time comes to use them like AOP or REST. 


Brian and I are putting QS to the test. You've heard me talk about the new platform that we're writing from scratch. This project uses Quicksilver so know that its being actively developed. I spoke with Brian and we've got an updated QS release coming up soon so please friends do check it out, find some bugs and put it through the ringer. Brian and I are always open to questions and feedback so definitely reach out.


With that primer out of the way, we'll dive head first into the AOP or REST capabilities of Quicksilver. What you think?


Later friends.
-Mick

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