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

Understanding the Model-View-Controller Design Pattern

Understanding the Model-View-Controller Design Pattern

With the advent of ColdFusion MX, CF programmers have the ability to bundle data and functions into a single unit for the first time.

Macromedia calls these constructs ColdFusion Components, or CFCs; other languages call them objects. This isn't to say that ColdFusion MX is now an object-oriented language. OO purists will rightly point out that CFCs don't have all the required features of first-class objects (including, perhaps most notably, polymorphism). Ben Forta's article on CFCs at www.macromedia.com makes this point under the heading "CFCs Are Objects, Kind Of."

Granting this point, though, doesn't diminish the great capability CFCs provide ColdFusion programmers and the new opportunities they open to us. CFCs can give our code greater power, flexibility, and reusability - all the benefits that object technologists have recognized for many years. If they aren't full card-carrying members of the Object Club, they're still very useful, and far less complex to use than their big brothers. Borrowing from a famous ad campaign, we might say that "CFCs are objects for the rest of us."

To gain advantage from this new capability requires new thinking. A shift in perception is required, in which the programmer moves from thinking of the application as composed of low-level details such as datatypes, recordsets, and functions to a more abstract view in which objects, in an almost lifelike way, handle their own data and know how to perform appropriate actions. Instead of viewing an application as data that's manipulated, the programmer begins to think of an application as composed of various objects that respond to different requests.

Object theorists refer to this as encapsulation. Any required action for an application is assigned to an appropriate object.

Here the two methods are contrasted:

Method A: Traditional data manipulation

<cfquery datasource="#request.dsn#" name="UserInfo">
SELECT
firstName,
lastName,
userID,
userPermissions
FROM
USER
WHERE
userID = '#URL.drilldown#'
</cfquery>
<cfoutput>
Hello there, #UserInfo.firstName# #UserInfo.lastName#
</cfoutput>
Method B: Using encapsulated CFCs

<cfset CurrentUser = CreateObject( "component", "User" ) />
<cfset CurrentUser.getInfo( url.drilldown ) >
<cfoutput>
Hello, #CurrentUser.getFirstName()# #CurrentUser.getLastName()#
</cfoutput>
In last month's column I said that CFCs combine structures with user-defined functions. Note, though, that here I'm not simply outputting two keys in the CurrentUser structure, CurrentUser.firstName and Current User.lastName. That code would look like this - and would work:

#CurrentUser.firstName# #CurrentUser.lastName#

But encapsulation asks us not to think of an object - or a CFC - as its constituent data elements, but as a self-contained entity. To get information from an object, I make a request of the object itself and therefore call the methods getFirstName() and getLastName(). It's up to the object to determine how this information is stored and in what way it will respond to these requests.

Although such a strict encapsulation may seem foreign to programmers at first, the benefits of such a plan soon win over most developers. When that change of perception does occur, programmers often succumb to "object fever" and the entire activity of programming seems radically new and exciting. In that fervor there's a tendency to ask objects to do too much, or rather, to ask a single object to do too much.

For example, a developer may realize that common user management functions (create, read, update, delete) can be wrapped into a single user object. Concentrating on what this object will be responsible for, our newly minted object programmer decides to include methods for displaying a form to gather new user information: User.newUserForm(). Submitting this form will call User.new(). Editing a user is as simple as calling User.editUserForm(), followed by User.update().

All goes well with our new CFC developer - let's call him "Bob" - until more than one view of a new user form is required. Perhaps one user form will be displayed to a user registering him- or herself, while a different one, with added fields, is made available to a supervisor.

Bob thinks about making changes to the form, altering the display based on who called it, but he's well aware that excessive conditional code makes for fragile code, and elects instead to have separate methods: User.new UserAsUser() and User.newUserAsSupervisor().

It doesn't stop there, of course, and soon a request comes in to allow a new user to be created by sending a formatted e-mail, which the program should read. Bob adds User.newUserFromEmail() and is wondering, "Can something this ugly really be right?" The final blow comes when another developer working on a different application wants to use Bob's user CFC. Naturally all the forms for creating a new user are quite different, and Bob finds himself looking at a method like this:

User.newUserAsSupervisorForHRapplication()

One very good solution to Bob's problem is the use of a design pattern known as Model-View-Controller, or MVC. Design patterns are time-tested architectural solutions to common problems, and Bob's problem is a common one. MVC was developed some 20 years ago at Xerox's famed Palo Alto Research Center (PARC).

In the MVC design pattern the modeling of the external world and the visual feedback to the user are explicitly separated and handled by three types of objects, each specialized for its task.

Objects/CFCs belonging to the model are responsible for handling the business logic and "back-end" work. Typically, complex algorithms and databases belong to the model. View objects are responsible for displaying information to and retrieving information from the user. In the Web world this is normally done using HTML and graphics, with Flash and Java used when greater capabilities are desired. Controller objects interpret mouse and keyboard inputs from the user, making requests of the model and/or the view as appropriate.

Applying this to Bob's situation, we see that there are several different views - different users and different applications - while the model remains stable. After reading an article entitled (ahem) "Understanding the Model-View-Controller Design Pattern" in his favorite magazine, Bob decides to create a user CFC that will handle only the essentials of user management. The user CFC must be responsible for creating a new user, for example, but the interface into that CFC is something wholly separate, something belonging to the view. It will then be the job of a controller to manage interaction between model and view.

Bob decides that he will create a user CFC that acts as a model. To the user CFC, creating a new user means saving user information to a database, assigning a CSR to the user, and sending an e-mail to that CSR. Everything else - what the entry form looks like, the permissions needed to see that form, etc. - is not the user's concern. With this new perspective, Bob creates a user model CFC that looks like this:

CFC: USER
Methods
new( firstName, lastName, address, city,
state, zip, email, [csrID], [userPermissions] )
edit( userID, firstName, lastName, address, city,
state, zip, email, [csrID], [userPermissions] )
getInfo( userID )
delete( userID )
Bob realizes this is just a start toward a full MVC implementation, but it's a good start. At some point in the future, if the company decides to change the method of storing user information - from SQL Server to Oracle, say - Bob will only need to change the implementation of his user CFC. All the applications that use that model will work without change.

MVC is a sophisticated architecture that not all applications will need. Still, an understanding of it can help you enormously in tackling large, complex - and profitable - jobs. Fusebox 3 makes a very good platform on which to implement MVC. You can find out more on this at www.techspedition.com.

More Stories By Hal Helms

Hal Helms is a well-known speaker/writer/strategist on software development issues. He holds training sessions on Java, ColdFusion, and software development processes. He authors a popular monthly newsletter series. For more information, contact him at hal (at) halhelms.com or see his website, www.halhelms.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.


IoT & Smart Cities Stories
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
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, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
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...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...