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
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
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...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear these words all day every day... lofty goals but how do we make it real? Add to that, that simply put, people don't like change. But what if we could implement and utilize these enterprise tools in a fast and "Non-Disruptive" way, enabling us to glean insights about our business, identify and reduce exposure, risk and liability, and secure business continuity?
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, 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.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
In this Women in Technology Power Panel at 15th Cloud Expo, moderated by Anne Plese, Senior Consultant, Cloud Product Marketing at Verizon Enterprise, Esmeralda Swartz, CMO at MetraTech; Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems; Seema Jethani, Director of Product Management at Basho Technologies; Victoria Livschitz, CEO of Qubell Inc.; Anne Hungate, Senior Director of Software Quality at DIRECTV, discussed what path they took to find their spot within the tec...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.