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
SYS-CON Events announced today that Fusion, a leading provider of cloud services, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Fusion, a leading provider of integrated cloud solutions to small, medium and large businesses, is the industry’s single source for the cloud. Fusion’s advanced, proprietary cloud service platform enables the integration of leading edge solutions in the cloud, including cloud...
Five years ago development was seen as a dead-end career, now it’s anything but – with an explosion in mobile and IoT initiatives increasing the demand for skilled engineers. But apart from having a ready supply of great coders, what constitutes true ‘DevOps Royalty’? It’ll be the ability to craft resilient architectures, supportability, security everywhere across the software lifecycle. In his keynote at @DevOpsSummit at 20th Cloud Expo, Jeffrey Scheaffer, GM and SVP, Continuous Delivery Busine...
SYS-CON Events announced today that Cloud Academy will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud computing technologies. Ge...
SYS-CON Events announced today that Interoute has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Interoute is the owner operator of Europe's largest network and a global cloud services platform, which encompasses over 70,000 km of lit fiber, 15 data centers, 17 virtual data centers and 33 colocation centers, with connections to 195 additional partner data centers. Our full-service Unifie...
SYS-CON Events announced today that Ocean9will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Ocean9 provides cloud services for Backup, Disaster Recovery (DRaaS) and instant Innovation, and redefines enterprise infrastructure with its cloud native subscription offerings for mission critical SAP workloads.
SYS-CON Events announced today that Systena America will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Systena Group has been in business for various software development and verification in Japan, US, ASEAN, and China by utilizing the knowledge we gained from all types of device development for various industries including smartphones (Android/iOS), wireless communication, security technology and IoT serv...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. @ThingsExpo Silicon Valley Call for Papers is now open.
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive ad...
Everywhere we turn in our industry we can find strong opinions about the direction, type and nature of cloud’s impact on computing and business. Another word that is used in every context in our industry is “hybrid.” In his session at 20th Cloud Expo, Alvaro Gonzalez, Director of Technical, Partner and Field Marketing at Peak 10, will use a combination of a few conceptual props and some research recently commissioned by Peak 10 to offer a real-world consideration of how the various categories of...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that CollabNet, a global leader in enterprise software development, release automation and DevOps solutions, will be a Bronze Sponsor of SYS-CON's 20th International Cloud Expo®, taking place from June 6-8, 2017, at the Javits Center in New York City, NY. CollabNet offers a broad range of solutions with the mission of helping modern organizations deliver quality software at speed. The company’s latest innovation, the DevOps Lifecycle Manager (DLM), supports Value S...
SYS-CON Events announced today that Peak 10, Inc., a national IT infrastructure and cloud services provider, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Peak 10 provides reliable, tailored data center and network services, cloud and managed services. Its solutions are designed to scale and adapt to customers’ changing business needs, enabling them to lower costs, improve performance and focus intern...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
SYS-CON Events announced today that Linux Academy, the foremost online Linux and cloud training platform and community, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Linux Academy was founded on the belief that providing high-quality, in-depth training should be available at an affordable price. Industry leaders in quality training, provided services, and student certification passes, its goal is to c...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
SYS-CON Events announced today that EARP Integration will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. EARP Integration is a passionate software house. Since its inception in 2009 the company successfully delivers smart solutions for cities and factories that start their digital transformation. EARP provides bespoke solutions like, for example, advanced enterprise portals, business intelligence systems an...
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
SYS-CON Events announced today that Hitachi Data Systems, a wholly owned subsidiary of Hitachi LTD., will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City. Hitachi Data Systems (HDS) will be featuring the Hitachi Content Platform (HCP) portfolio. This is the industry’s only offering that allows organizations to bring together object storage, file sync and share, cloud storage gateways, and sophisticated search and...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs ofte...