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)

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
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
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.
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...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
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...
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...
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...