You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Adobe Flex

ColdFusion: Article

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.

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.

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.

More Stories By 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).

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...
The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
Over the course of two days, in addition to insightful conversations and presentations delving into the industry's current pressing challenges, there was considerable buzz about digital transformation and how it is enabling global enterprises to accelerate business growth. Blockchain has been a term that people hear but don't quite understand. The most common myths about blockchain include the assumption that it is private, or that there is only one blockchain, and the idea that blockchain is...
Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Japan DX Pavilion at @CloudEXPO Silicon Valley
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...