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
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
In this presentation, Striim CTO and founder Steve Wilkes will discuss practical strategies for counteracting fraud and cyberattacks by leveraging real-time streaming analytics. In his session at @ThingsExpo, Steve Wilkes, Founder and Chief Technology Officer at Striim, will provide a detailed look into leveraging streaming data management to correlate events in real time, and identify potential breaches across IoT and non-IoT systems throughout the enterprise. Strategies for processing massive ...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. 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 com...
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational 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 advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
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
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and 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 IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
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 looked 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 deliver...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
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...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
When growing capacity and power in the data center, the architectural trade-offs between server scale-up vs. scale-out continue to be debated. Both approaches are valid: scale-out adds multiple, smaller servers running in a distributed computing model, while scale-up adds fewer, more powerful servers that are capable of running larger workloads. It’s worth noting that there are additional, unique advantages that scale-up architectures offer. One big advantage is large memory and compute capacity...
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...