Architecting Your ColdFusion Objects

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.

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.

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.


Sometimes people without an object-oriented programming background get confused by what ColdSpring does because it solves a problem they don't yet know they have. I'd start by throwing your objects into an application scope to get a sense of the problems that causes. Once that starts to become a problem, head on over to www.coldspringframework.org and it should make perfect sense!

If you know what an Active Record pattern is and find yourself wishing that ColdSpring was optimized for injecting dependencies into transient Business objects as well as singeltons (which it isn't), you might want to check out LightWire at http://lightwire.riaforge.org.

Understanding the Controller
The most misunderstood part of a well-designed object-oriented application is the controller. In the past our "controller" methods often did a lot of work. In a well-architected OO application, they do very little indeed. The job of a controller is to do two things. First it should take values from the URL, form, and (possibly) session scope to make well-parameterized calls to the appropriate method in the model. Second it should take the information returned by the model and pass it to the appropriate view for displaying on-screen. That's pretty much it!

Recently there have been a lot of questions about how to integrate Model-Glue and Mach-II with Flex front-ends or Web Service calls. The answer is that you don't. The Flex front-ends and Web Service calls should speak to the model directly (well, actually via a simple remote façade to handle any differences in data formatting between the model and the remote system). They shouldn't speak to your HTML controller (such as a Mach-II or Model-Glue controller) at all. If you feel you need to make your Flex applications or Web Services speak to your HTML controller because otherwise you'd have to replicate business logic, that's a perfect sign that you've put too much business logic into your controller and that you need to refactor that and put it into your model instead.

Looking at Views
The goal of a view is to display the information that the model provided to the controller along with any templates, formatting, and the like. There should be no business logic in the views (such as calculating prices or deciding what value to display based on business rules). The view should never include a cfquery that runs against a database (a query of queries for sorting or ordering a recordset may sometimes make sense).

Other than the general rules above, there aren't well-accepted patterns in the ColdFusion community for handling view issues like skinning, view composition (so you can reuse parts of your views on multiple pages), and view helpers (to provide a separation of concerns by removing any programming logic from your templates so designers can safely edit the templates without breaking view-specific code like alternating row tables or "records per page" display logic). However, there are many approaches being explored so it's well worth looking at them.

Conclusion
Using cfcs for your application can make complex applications much more maintainable, but there's a substantial learning curve. Wherever possible, start with small test applications and then as you get more confident using the patterns you'll find your development speed increasing. If you have to start with an existing system, solve one problem at a time. Pull your data access logic into DAOs. Then start to add a service layer and remove business logic from your views and controllers one at a time. The trick? Lots of little steps!

© 2008 SYS-CON Media