Welcome!

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.

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.


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
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, 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.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
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 ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"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.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, 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.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.