YOUR FEEDBACK
sahil wrote: help
AJAXWorld RIA Conference
October 20-22 San Jose, CA
Register Today and SAVE !..


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP COLDFUSION LINKS


Architecting Your ColdFusion Objects
How to write more maintainable applications

Once you've learned the syntax of cfcs, one of the hardest things to do is to figure out exactly how and where to use them. The goal of this article is to run you through the most common (and useful) ways to use cfcs to make your applications easier to maintain.

The main benefit of cfcs is that they can make your applications more maintainable. If you're just creating a page with a form that saves user input to a database, you probably don't need cfcs. However, as your applications become more complex, cfcs can make them easier to maintain by breaking your code down into smaller chunks that are easier to find, edit, test, and debug as your user's requirements change.

Design Patterns
Design patterns are simply "proven solutions to recurring problems." In the programming world the term was coined by the "Gang of Four" who wrote a book full of common patterns back in 1995. Design patterns provide two main benefits. First, they show a proven way to solve a particular problem. Second, they give you a shared vocabulary to talk with other programmers about solving those problems.

Think of design patterns like recipes for "baking" successful code. It's important to realize that the only reason to use a particular design pattern is to solve an associated problem. You don't get extra points for using patterns you don't need. In fact, one of the biggest risks when you start writing code with cfcs is that you will put in patterns you don't really need - resist the temptation!

Nothing is Free
Most object-oriented design patterns were created to solve the problems of managing complexity and improving the maintainability of your code. They do this at the cost of increasing the complexity of the structure of your application and decreasing its performance.

They increase the complexity of the structure of your application so that you can break your code into smaller chunks, making it easier to find, modify, and test each piece. They decrease its performance because the overhead of getting all those little chunks to talk to each other is not zero (it's often small enough to be unimportant, but it's never zero).

However, once you get used to the more complex structure, it's actually easier to find the code you want, and on the whole programmers are more expensive than computers, so even though most of the design patterns will affect the performance of your applications, it will be well worth it to make them more maintainable.

OO-101
Just before we get started with design patterns, let's revisit why we use cfcs and object-oriented programming. Over the years it's been found that putting information (variables) and actions (functions) together into self-contained objects (in ColdFusion we use cfcs) can make for more maintainable code. Why? Because it lets you decrease the dependencies (coupling) between different parts of your application.

If you have a "user" object, as long as you don't change the methods (functions) it provides, you can change how the user works internally without breaking the rest of your application. So, when a client comes along and asks you to change how one part of his application works, it's now less likely to break the rest of the application.

What Makes an Application Maintainable?
There are a number of common "best practices" that have been proven over the years to make code more maintainable. Many design patterns can be explained by the fact that they help you to implement these best practices.

  • High Cohesion: The code you put in a cfc wants to be as logically cohesive as possible - it should "hang together." That's why we create business objects like users or invoices to put all of their properties (variables) and methods (functions) together and why classes with functions that have little in common (say, general utility classes) should be avoided where possible.
  • Loose Coupling: Even more importantly, you want to minimize the coupling between different classes (classes is another term you might hear for cfc's - a cfc can be called a class). This is important because when you have to change a class you don't want it to break too many other parts of your application.
  • Program to Interfaces - Not Implementations: One way to decrease the coupling between classes is to make sure that you treat each cfc as a black box. Pretend you don't know how it works - only what methods (functions) it provides. That way, if you have to change the implementation later (how the methods work), it won't break the rest of your code.
  • Tell - Don't Ask: Another key to decreasing coupling is to "tell" a class to do something instead of "asking" it for information. A general rule is that if you ask a cfc for two or more pieces of information that you're operating on, you should try to replace that with a single request for the cfc to do whatever you were doing. Don't ask a TaxRate.cfc for the tax rate and whether to tax shipping. Pass it the order and ask it to calculate the tax. That way, if the rules for calculating taxes ever change, you'll know that all you have to do is change the code in the TaxRate.calculateTax() method.
Business Objects
The first step in architecting an object-oriented application is to come up with a list of business objects. Business objects are the real-world "things" that your application models. In a shopping cart you might have products, categories, orders, and order items. A content management system might have users, pages. and articles. An accounting system might have vendors, customers, invoices, and bills. Coming up with a good domain model (a well-thought out list of business objects) is one of the hardest parts of object-oriented programming and is outside the scope of this article. You might want to start by creating one business object per database table (excluding joining or extension tables), but please be aware that a well-designed object model is often very different from the list of tables in your applications database.

MVC
The first pattern you'll want to consider is MVC - Model-View-Controller. The Model is the meat of your application - the business objects and their associated business logic. The View handles displaying the state of the application and the Controller lets the user select a view and interact with the model.

The goal of MVC is to clearly separate your business logic and views to make them easier to reuse in the application. It also lets you reuse the same model code across multiple display technologies (perhaps an HTML Web site, a Flex front-end and a Web Service). Most non-trivial applications should use MVC to get the business logic out of the page views and improve the readability and maintainability of the code. Popular community frameworks like Mach-II and Model-Glue implement MVC and provide a great example of the pattern.

Introducing the Model
Once you have your domain model, you still have a bunch of architectural choices to make. Most real-world systems don't have one cfc per business object in the model. You'll often see DAOs, Service cfcs, Gateways, and maybe even Transfer Object cfc's as well as the business objects for each object in the domain model.

  • Service Objects: Service objects (sometimes called Managers) are used to provide an API to the Business objects. Usually named ProductService.cfc or ProductManager.cfc (for a Product object), they are singletons, which just means that there's only one of each at any given time in your application - you don't need three ProductService's running - just one. If you want to get a list of users, ask UserService.cfc. Want to delete all of your old orders? Ask OrderService.cfc. The Service objects (sometimes also called the "service layer") along with the Business objects are the only parts of your model that the controller should speak to.
  • Data Access Objects (DAOs: Data Access Objects are used to encapsulate (hide) your SQL code so that all of your SQL queries for each object are in one reusable place. DAOs are often used just to encapsulate single record access (insert, update, delete, and select for a single record), with the Gateway handling operations on multiple records.
  • (Table Data) Gateways: The Table Data Gateway (usually just called a "Gateway") is a pattern for putting all of your operations on multiple records in one place. This will always include select statements and could sometimes include delete or even insert or update methods if they're operating on collections of records.
  • Transfer Objects: Mainly used for passing objects to remote systems (e.g., for a Flex front-end), Transfer Objects are really just structs of data without any business logic stored in a very simple cfc. They really aren't very "object-oriented" (they don't combine properties with methods) but they can be useful in solving specific problems when building a project.
Architecting the Model
Most object-oriented ColdFusion developers create a Service class, a Business object, a DAO and a Gateway for each domain object (product, user, invoice, company, etc.). The DAO and the Gateway are only ever called by the Service method and the Business object is mainly used for passing round information with getters and setters to encapsulate (hide changes in) getting and setting of individual values.

In a simple application, a product might have a ProductService.cfc with methods like getProductbyCategory(CategoryID), getProductbyID(ProductID), getProductbySKU(ProductSKU), deleteProduct(Product), and saveProduct(Product). The Product Business Object (Product.cfc) would have methods for getting and setting its properties so there would be getPrice() to get the price of a product and setPrice() if you wanted to set the price of the product - perhaps as part of processing a product administration form for the site manager to update the product prices. The controller would only ever speak to the ProductService and Product objects.

The Service class would then call the ProductDAO's getProductbyID(), getProductbySKU(), deleteProduct(), and saveProduct() methods to get, delete, and save a single product respectively and would call the ProductGateway's getProductbyCategory() method (because there could be more than one product in a category) to get all of the products in a category. The getProductbyID() and getProductbySKU() typically return a loaded object ready for passing back to the controller. The deleteProduct() and saveProduct() either return just the status of the request or an object containing the status of the request. The ProductGateway.getProductbyCategory() returns a recordset ready for displaying using a simple cfoutput.

Improving the Modelb First, you should consider putting all of your "Product" objects in one directory, all of your "User" objects in another and so on. That way you can make all of the DAO and Gateway methods "package" types (rather than public or private) so that they are only available from other objects in the same directory - in this case the Service class and the Business object. Second, you need to ask whether you'll ever have to calculate the values of your objects properties (perhaps a product's price or a user's age) when you are dealing with lists (like getProductbyCategory(), which returns multiple records). If you do, the above approach doesn't work very well since you need to put all of your business calculations in the database, loop through your recordset in the Service object to do any calculations, or put your calculations in your views (not a good idea). See CFDJ October 2006 (p. 16) for more information on why you might want to encapsulate your recordsets.

If you choose to take this approach, the Gateway disappears, the ProductService always calls the ProductDAO for any database-related tasks, and instead of getting an object from getProductbySKU() and a recordset from getProductsinCategory(), both now return an Iterating Business Object that gives you the benefits of encapsulating your getting and setting (making your code more maintainable) while still providing good performance. I'd personally recommend starting with Gateways and recordsets and then moving to this approach only if you find that you have values in your recordsets whose calculation you'd like to be able to vary.

Handling Dependenciesb We now have a bunch of objects that need to talk to each other (the Product service needs to talk to the Product DAO, and so on). But how does that work? We could just throw them all into the application scope. Then when ProductService wants to get a product by ID, it would just call application.ProductDAO.getProductbyID(ProductID). This works for a while, but as your application grows it can become a little unwieldy. It also makes it harder to test components using Unit Testing (see www.cfcunit.org for more information on Unit Testing in ColdFusion). You could create a Factory (another design pattern) to create and/or return your objects, but then you'd need to access the Factory (either by calling it in the application scope or by passing it into every object).

A better solution is to use a framework to automatically provide all of your objects with any other objects they need. The most popular framework for doing this in ColdFusion is ColdSpring. With ColdSpring, you just add a cfargument to your init() method for every dependent object (so ProductService, which needs ProductDAO, would have a ProductDAO cfargument in its init() method) and create a simple XML file describing your objects and ColdSpring will take care of providing the right objects when you need them.


About Peter Bell
Peter Bell is CEO/CTO of SystemsForge (http://ww.systemsforge.com) and helps Web designers to increase their profits and build a residual income by generating custom web applications - in minutes, not months. An experienced entrepreneur and software architect with fifteen years of business experience, he lectures and blogs extensively on application generation and ColdFusion design patterns (http://www.pbell.com).

CFDJ LATEST STORIES . . .
Kevin Lynch, who will be keynoting on October 21, 2008, helped originally coin the term "Rich Internet Application" in 2002. He has been at the center of innovation in Flash and Adobe AIR since their inception, and currently drives Adobe’s technology platform for designers and develo...
Rich Internet Applications offer the potential to fundamentally change the user experience and in doing so, yield significant business benefits. The theme of this October's AJAX World Conference & Expo 2008 West is 'Beyond AJAX to the RIA Era' and the Call for Papers, which is still op...
Join Scott Guthrie as he discusses Microsoft’s commitment to web standards development, Rich Internet Applications and how Microsoft is contributing to help move the web forward. Join Adobe’s Kevin Lynch as he demonstrates how Flash and HTML come together to make the most engaging,...
Virtualization has become a critical part of Enterprise IT strategy. Why and how has it become one of the most important change agents in our industry? To answer these questions I had the good fortune recently to be able to speak to a select group of top IT industry executives who join...
SQL Injection attacks are one of the easiest ways to hack into a website. One recent hack, using a script from verynx.cn, involves injecting sql into a web form that then appends some JavaScript code into fields in a database that then gets executed on the client side when a user views...
Recursion Software released a private beta version of their Voyager mobile platform, with powerful interoperability for Android, Microsoft .NET and Compact Framework (CF), all Java editions (JME CDC, JSE and JEE), and more than 15 embedded operating systems. The Voyager platform is a p...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

MOST READ THIS WEEK
ADS BY GOOGLE