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.

IoT & Smart Cities Stories
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | 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.
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
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...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
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...