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.

@ThingsExpo Stories
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
CloudEXPO | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.