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

ColdFusion: Article

Data Access Objects

The mystery design pattern

It seems that there's a lot of talk in the ColdFusion community about data access objects and data gateway design patterns. Everyone talks about how great they are and why everyone should be using these patterns.

Unfortunately, there seems to be little talk about what exactly they are and how you would implement them in a ColdFusion application. At one point I did a lot of searching for resources on these two patterns and came up with nothing. These patterns aren't discussed in the famous "Gang of Four" book, nor are they covered in Head First Design Patterns. A Web search also came up empty. So where does one go to learn? Hopefully I can shed some light on these patterns. It was only after talking to different people about them that I started to understand their purpose and how you could implement them. In this article I'll explore the Data Access Object (DAO) in detail. Next month I'll examine the gateway pattern.

What Is a Design Pattern?
A design pattern is just another name for a best practice. There are usually certain tradeoffs you make for choosing one approach over another. I recommend you try to learn as many patterns as you can, and then you'll be in a better position to decide what will work best for your current situation.

When talking about design patterns, most ColdFusion developers are usually talking about ways to structure the code that makes their business model. Design patterns in the model are a way to structure code in such a way that allows the most flexibility long-term. Software applications spend most of their life in a maintenance change as I'm sure you've already experienced.

Design patterns aren't limited to your business model, though. Model-View-Controller is a design pattern many CF developers are familiar with that's not related to how to structure your model; it's designed to help separate your model from your view code. Yahoo released a series of design patterns that are related to the user interface. You can read about them at http://developer.yahoo.com/ypatterns/index.php. When you implement DAOs or gateway objects you'll be doing so in your model.

What Is a Data Access Object?
Data Access Objects are a design pattern that lets you separate your data access from any business logic. This lets you easily change your data storage mechanism with minimal code changes. Perhaps you want to move from a MySQL database to a SQL Server database. Or perhaps you're ditching local data storage in favor of using a Web Service mechanism? Maybe you want to move some data out of the database and into XML files? Or perhaps you'll want to move them out of XML files into a database. If your application is implemented using DAOs then you'll just have to write a new DAO objects for the new data mechanism and then tell your application to use the new one instead of the old one.

In most cases, a DAO will have four methods in it, one for inserting data, one for updating data, one for selecting data, and one for deleting data. Your business model components will access the DAO objects as needed to maintain the data properly. This probably sounds harder than it is, so let me demonstrate with an example.

MyFriends RSSCategory Component
To illustrate a DAO object, I want to take a look at the RSSCategory.cfc from the MyFriends RSS aggregator. You can download the aggregator code from the software pod on my Web site at www.jeffryhouser.com. RSS feeds that are entered into the system can be categorized. This component is used for creating or updating one of those categories. It was originally built in the interest of speed without much thought to database portability.

The RSSCategory component has two properties, a CategoryID and a Category. It has two methods, an init method and a commit method. The init method contains a select statement. The commit method contains an update statement and an insert statement. If we change our data storage mechanism, all the SQL statements would have to be changed inside the component. This could, potentially, mean changing every component in our Model. This is about as close to a full rewrite as you can get. The intent in creating a DAO is to move the SQL statements outside of the main component and into a separate component. That way, you only have to change the DAO, leaving the rest of your app untouched.

Writing the Data Access Object
The Data Access Object won't have any properties, just the methods for selecting, inserting, updating, and deleting. (For the sake of brevity, I won't provide the delete method.). A CFC without any local properties is like a function library, and that is exactly what we're using it for. Listing 1 shows the select method. The method name is select and it returns a query. It accepts two arguments, the CategoryID and the datasource name. The CategoryID is the primary key for the category you want to retrieve. The query name is defined as a local variable then the select query is run. I chose RSSCategory.cfc because of the simplicity of the queries. The resultant query, even if no data is returned, is passed out of the function. Easy as pie.

Listing 2 shows the insert method. This method is named insert, but returns void. It accepts three arguments, the CategoryID, the Category, and the datasource. This is different than the select method, which only needs the primary key. Since we're creating a new category from scratch, we need all the associated data for the query. The query variable is defined as a local variable on the next line. Then comes the query. In the case of the MyFriends project, UUIDs are used as primary keys so they'll be created outside of the component and passed in. If you were using other methods for primary key creation, such as an auto-incrementing integer, then you may not want to pass that value into the method. You may want to get it from the database after the insert and return it out of the method. These decisions are application-specific decisions, though, not data storage-specific. The update method, shown in Listing 3 is identical in form to the insert method and I don't have anything else to add about the code.

Modifying the RSSCategory Component
With the Data Access Object created, the next step is to modify the RSSCategory component to use the methods in the DAO instead of directly executing SQL. First, we want to create an instance variable to contain the DAO object. We can add this line as part of the pseudo constructor code:

variables.instance.DAO = "";

The modified init method is shown in Listing 4. It adds a third argument, which is the type of DAO you want to use. Most likely this will be a global setting somewhere in your app. So I don't have to change any already-written code, I made this argument optional and added a default value, which refers to the Data Access Object I just created. First I define a local query variable. Then the code creates an instance of the DAO object. In the old version of the component, the query was located next. Here we call the select method and assign the results to the query variable. The remainder of the method sets the instance variables based on the query data.

The modified commit method is shown in Listing 5. The commit method remains largely unchanged. The method signature is the same. There is one argument for the data source. A local query variable is defined. If the primary key is an empty string then the new primary key is created and the insert method executed. Otherwise, the update method is run.

Why Use a Data Access Object?
With the example behind you, you might ask yourself why would you care about DAOs? I can honestly say that I rarely use them. Most of my applications are custom built for clients. How often do companies change their database? Yes, it happens, but it's rare. In my early days I converted a lot of Microsoft Access databases to SQL Server, but it's rare to find an Access-built app. It'd be even rarer to see an Access-built Web app that uses DAOs or any advanced design concepts.

DAOs really start being a benefit if you're going to build an application that will be deployed in multiple environments and those environments are unknown. Perhaps you're building a killer CMS? Or free blogging software? If so then you're going to want to use DAOs in your development. You don't know if the next deployment will be on SQL Server, Oracle, or even XML files.

Final Thoughts
You should now have an understanding of what DAOs are and how to use them in your ColdFusion applications. I wish I could give you a list of resources to learn about gateways, but my research has always come up empty. I can think of many alternate implementations of this pattern that could achieve the same affect. I'd love to hear how you implement DAOs. Let me know!

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

Comments (1) View Comments

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.


Most Recent Comments
Michael Long 03/28/07 07:57:25 PM EDT

First, if you're writing your own CRUD statements to do DAO's you're missing out on the more powerful aspects of systems like Reactor and Transfer, which do all of that scut work for you.

Second, let's take as an example a membership record. A membership DAO would consolidate all of the code for managing members in a single place. How many places in a site are you going to be working with member records? How about registration, forgotten emails, signin/signout, user profile pages, or changing email addresses or passwords? Comments? Submissions? Orders?

How many places have you spread out inserts and updates? Specified datasources? And in how many places did you remember to handle nulls correctly? Retest for duplicate emails or usernames? Remember to validate the password? DAOs let you write that code once, and use it everywhere.

You say most places don't change databases, and that's true... but what happens when the DB admin says we need to change servers or split the database and datasources need to change? What if, for performance reasons, all of those inserts and updates need to become stored procedures? What if your company makes the decision to move member information to an LDAP server?

How much code are you going to have to track down and change? And how long is it going to take?

In short, if you're not using them in your code, you should be.

And BTW, while the technical name for the pattern is ActiveRecord, if you're Gang-of-Fouring the best choice there is a façade, an object that provides a simplified interface (load, save) to a larger body of code (INSERT INTO...).

@ThingsExpo Stories
"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.
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 ...
"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...
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...
"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.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
"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.
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
"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...
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...
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.
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...
"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.
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
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 ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...
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.