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>
    <!--- 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">
       <!--- quantity --->
       <!--- name --->
       <!--- description --->
       <!--- price --->
       <!--- extension --->
       <td>#DollarFormat(products[i][2] * products[i][1].getPrice())#</td>
    <cfset subtotal = subtotal + products[i][2] * products[i][1].getPrice()>
    <cfset taxes = taxes + hmmmm>

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

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

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)

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
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...
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.
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...
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...
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...