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

Creating Object-Oriented Presentation Layers

All the coolest programmers are doing it

For the past several weeks, I've been immersed in writing a large application - so immersed, in fact, that I missed writing my column for last month! This application has been particularly interesting to me because it makes such extensive use of AJAX - that combination of JavaScript, DOM manipulation, and the XMLHttpRequest object that has caught the attention of the general public. It's also been interesting because it has allowed me to experiment with the idea of creating an object-oriented (OO) presentation layer.

Why incorporate OO? Because all the coolest programmers are doing it! In fact, it seems to me that the accepted wisdom is rapidly becoming this: the only systems worth developing are OO systems and the only programmers worth their salt are OO programmers.

This puts great pressure on procedural programmers to "become" OO programmers. The problem is that designing OO systems is really hard. It's one thing to learn that polymorphism, encapsulation, and inheritance are key features of an OO language; it's quite another to fully grasp the design ramifications of the OO mindset. Perhaps it's time to reflect on Daniel Boorstin's observation that "the greatest obstacle to discovery is not ignorance - it is the illusion of knowledge." What exactly does it mean to be an OO programmer?

One of the key principles of object orientation is that an object is a collection of services. The data an object stores (as instance variables) are meant to be used by that object in carrying out requests for these services. Treating an object as a service provider rather than a data provider is one of the hardest adjustments for procedural programmers to make, so hard, in fact, that many never make the transition.

We might call this data-provider approach to objects pseudo-object orientation. To the pseudo-OO programmer, an object is first and foremost a holder of data. When pseudo-OOers attempt design, they do so by asking what properties a class has. Knowing that many real OO programmers use UML, pseudo-OOers often follow suit, but their pseudo-OO designs can be distinguished from the real thing at a glance: they're heavily weighted on expressing data and the services they expose (as methods) are primarily getters and setters, with some data validation added.

Let me give you an example. Suppose we are writing an e-commerce system that needs to account for taxes. Let's say that in our system, different products are taxed at different rates depending on their country of origin, while some products are entirely tax-free. Set a pseudo-OO programmer to work on this, and he'll likely come up with a UML class diagram for a product that looks something looks like Figure 1.

This analysis of a product fits nicely with what we might call the pseudo-OO motto: All Data, All the Time. The bottom portion of the class box, which should show the services the class can provide, is conveniently empty.

To the pseudo-OO coder, a class is really just a structure in which to hold data. Most often, an instance of a class (an object) is nothing more than an in-memory representation of a row in a database. Given this view, it's no surprise that our pseudo-OOer will immediately concern himself with synchronizing the in-memory representation of the row with the actual row in the database. Enter the data access object or DAO (that works with a single object) and its close cousin, the gateway (that works with collections of objects).

Of course, no pseudo-e-commerce system would be of much use without a pseudo-shopping cart. Stated slightly differently (but with almost no change in meaning), no data-centric e-commerce system would be of much use without a data-centric shopping cart, maybe something like Figure 2.

The products array may be a two-dimensional array in which one index holds the Product object, another holds the quantity in the cart, and perhaps a third holds the SKU of the product (for quick lookups). When it's time to display the shopping cart, the code might look something like this:

<table class="cart">     <tr>
       <th>Quantity</th>
       <th>Product</th>
       <th>Description</th>
       <th>Price</th>
       <th>Extension</th>
    </tr>
    <!--- get array of products in cart --->
    <cfset products = session.user.cart.getProducts()>
    <cfset subtotal = 0>
    <cfset taxes = 0>
    <cfloop from="1" to="#ArrayLen(products)#" index="i">
    <tr>
       <!--- quantity --->
       <td>#products[i][2]#</td>
       <!--- name --->
       <td>#products[i][1].getName()#</td>
       <!--- description --->
       <td>#products[i][1].getDescription()#</td>
       <!--- price --->
       <td>#DollarFormat(products[i][1].getPrice())#</td>
       <!--- extension --->
       <td>#DollarFormat(products[i][2] * products[i][1].getPrice())#</td>
    </tr>
    <cfset subtotal = subtotal + products[i][2] * products[i][1].getPrice()>
    <cfset taxes = taxes + hmmmm>
    </cfloop>

    <tr>
       <td colspan="5" align="right">Sub-total: #DollarFormat(subtotal)#</td>
    </tr>

    <tr>
       <td colspan="5" align="right">Total: #DollarFormat(subtotal + hmmmm)#</td>
    </tr>
</table>

Notice that I've omitted all the logic for computing the taxes, replacing it with a generic "hmmmm" variable. Of course, that won't really work, so perhaps our programmer will create a computeTax(countryOfOrigin) function that accepts a country of origin (a string) and returns the tax on the item. Add in a few DAOs and Gateway objects and you have yourself an object-oriented e-commerce system.

Except that it isn't. All that's happened is that an e-commerce system, solidly procedural to its core, has been tinkered with and baptized as an OO system. Instead of objects providing services, we have objects providing data that is then used for such tasks as calculating the subtotal, taxes, and total of the shopping cart.

What would a real OO system look like? We would first determine what we need a cart to do - what messages it should respond to, e.g., what services it should provide. How the shopping cart responds to these messages must, of course, be determined, but not now. Our first and most important job is to determine the entities needed by our system and the methods each entity will offer. These methods - or, at least, the publicly accessible ones - form an application programming interface (API) for each entity. The API informs us of the appropriate messages that can be sent to any object. When done correctly, an OO program resembles nothing so much as a conversation between objects.

With this in mind, let's take another look at an OO design for a shopping cart. We start not with data, but with services to be provided. What do we want our cart to do? The answer to this will form the cart's API. Figure 3 shows my take on a ShoppingCart class.

Now, all the focus is on services (methods), not on the data. I've gone so far in slighting the data as to completely ignore it, and this is exactly the right level to design at. OO programs are not about data and functions; they are about determining the way that objects will communicate with each other. Our job as OO designers is to provide an environment in which safe, meaningful communication between objects can take place.

If we were working in the Java world, this emphasis on finding the right API would be reflected in the use of a Java construct called an interface, a fundamental entity in which only methods can be specified. Good design is done at the interface level. Only when the interfaces and their APIs have been determined is the class design (now including data) created.

We don't have interfaces in ColdFusion (nor am I anxious that they should be included in the language), but the essence of interfaces - the focus on services rather than data - should be just as central to our designs in ColdFusion as it would be if we were designing in Java.

Once we have a class design done, of course, we must make the objects created from these classes persistent. DAOs and gateways are one way to do this, but we must make sure that they are subservient to an OO design that allows for communication between objects.

Next month, I'll share some experiments I've been working on that try to bring the ideas of object orientation to the presentation layer. I think the experiments may hold some promise, not in order to be fashionable, but to create programs that at every level (including the presentation level) are easy to maintain and adapt easily to change. Those are goals that will resonate with programmers of all types.

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 (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
SYS-CON Australia News Desk 06/28/06 04:41:21 PM EDT

For the past several weeks, I've been immersed in writing a large application - so immersed, in fact, that I missed writing my column for last month! This application has been particularly interesting to me because it makes such extensive use of AJAX - that combination of JavaScript, DOM manipulation, and the XMLHttpRequest object that has caught the attention of the general public. It's also been interesting because it has allowed me to experiment with the idea of creating an object-oriented (OO) presentation layer.

@ThingsExpo Stories
Announcing Poland #DigitalTransformation Pavilion
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
CloudEXPO | DXWorldEXPO 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.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO 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 CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
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.
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.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
"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.
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
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...
In past @ThingsExpo presentations, Joseph di Paolantonio has explored how various Internet of Things (IoT) and data management and analytics (DMA) solution spaces will come together as sensor analytics ecosystems. This year, in his session at @ThingsExpo, Joseph di Paolantonio from DataArchon, added the numerous Transportation areas, from autonomous vehicles to “Uber for containers.” While IoT data in any one area of Transportation will have a huge impact in that area, combining sensor analytic...
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...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
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 ...
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.