|By Peter Bell||
|November 9, 2006 01:00 PM EST||
One of the first things that you encounter when moving to object-oriented (OO) programming are beans. Beans are simple representations of a business object (like a user or a product) that hide all of the information stored in the bean behind methods (functions) for getting and setting the information (called, unsurprisingly, getters and setters).
Typically, if you want to display a product view screen, you'll get the product information from the database, load the resulting query recordset into a bean and then, instead of displaying the variables from the query, call the methods from the bean. In the past your product view may have looked like this:
$#Price#<br /><br />
With a bean, the product view will change to the following:
$#Product.get("Price")#<br /><br />
The only difference is that you are calling a "get" method that hides (encapsulates) the way the title and the price are retrieved, but this small difference can have a big impact on the maintainability of your code. (The sharp eyed among you will have noticed that I'm using a generic getter. The sidebar explains why this might be a good idea for you to consider).
Object-oriented programming is all about writing more maintainable code. Many Object Oriented patterns take longer to code initially than a traditional procedural approach, but they are easier to maintain. Given that we tend to spend much more time maintaining than developing applications, this is usually a worthwhile trade-off.
The benefit of encapsulating business object attributes behind getters and setters is that if the logic required to calculate (or save) the attribute changes, you only have to change the code in one place. Let's say that the product price is calculated based on a sale price. In the past you might have put that logic right into the product view:
$<cfif SalePrice>#SalePrice#<cfelse>#Price#</cfif><br /><br />
The problem is, there may also be a product list screen, a product search results screen, and the cart and checkout may also need to know the price of a product, so if you changed the way you calculated the price, you would have to remember to make that change in five places. Even worse, there is the risk that you might forget to update one of the screens, so products displayed on the search screen would display a different price than when added to the basket.
With getters and setters encapsulating the logic, there would be no change at all to the display screens. They would still be:
$#Product.get("Price")#<br /><br />
The only difference is that you would change the getPrice() custom method within the product object to be something like:
<cffunction name="getPrice" returntype="numeric" access="public"
output="no" hint="I return the price to display and charge for the product">
<cfset var Local = structNew()>
<cfset Local.ReturnValue = variables.get("SalePrice")>
<cfset Local.ReturnValue = variables.Price>
So, encapsulation of getters and setters using beans is a key element of Object Oriented programming, and it is a best practice that most OO developers would use most of the time. So, what happens when we have more than one user or product or article?
The Performance Problem
In Java, this would be easy. You would take your recordset, use it to create a collection of objects (one for each record), and you would still have all of the benefits of encapsulated getting and setting of properties. Unfortunately, in ColdFusion, object creation is expensive (in terms of performance). Creating a large number of objects as part of every page load can substantially affect the performance of a ColdFusion script.
Because of this, a lot of ColdFusion developers currently use recordsets for displaying their lists, losing all of the benefits of encapsulation. If they want to change the way the price is calculated for a product list, they either need to push back the price calculation onto the database; write a script in their service object to loop through the query implementing any custom data transformations; or replicate their business logic all over their list screens.
Introducing the Iterating Business Object
The iterating business object (IBO) is a simple solution to the problem of encapsulating access to getters and setters for recordsets without sacrificing performance. It is implemented as a base class that your business objects can extend. As well as providing generic getters and setters, it can also load itself with a query, and it provides a basic set of iterating methods (first(), next(), and isLast()) for looping through the recordset.
The IBO allows you to get all of the benefits of encapsulated getting and setting of attributes - whether you are working with a single object or a collection of them. It also allows you to use exactly the same code for both your single objects and object collections. For example, it really doesn't matter whether you are viewing a single product on a product detail page or a list of products matching a search query. If you want to display the price for the product, you want to use the same business logic to calculate it in both cases. With an IBO, you always load the same object up with the results from your query, and you can maintain all of your getter and setter calculations in that one object. In addition, you are only instantiating a single object per page view, so the performance hit is nominal. You can see the code for a simple IBO in Listing 1.
Using the Iterating Business Object
When you are using the IBO to display a single record, it is exactly the same as using a bean:
$#Product.get("Price")#<br /><br />
If you want to display a list of records, it is almost as easy. You take the same basic display code and just wrap it with a loop based on the iterating methods of the object:
<cfloop condition="NOT #Product.isLast()#">
$#Product.get("Price")#<br /><br />
Improving the Object
Previously I showed an example of a custom getter for calculating the price of a product. If there was a sale price, it displayed that, otherwise it just accessed the variables scope to get the price. Well, that works for a single record, but if there are multiple records (as with the IBO), the actual code to access a particular record would be more like:
<cfset Local.ReturnValue = variables.Data[variables.IteratorCount].Price>
Where the variables.IteratorCount is a pointer to the current record within the recordset being displayed. This isn't "wrong", but over time all of the custom methods would have to include this code, and if I ever decided to change the structure of the data storage within the variables scope, all of those methods would have to be rewritten.
To encapsulate that change, I added one more pair of generic methods to the base IBO: access() and mutate(). Accessors and mutators are alternate terms for getters and setters, but these methods are private and are only to be used by the customer getters and setters to access the underlying data structure, so if I ever wished to change the structure, I would only have to change those two methods. Below is simplified code for the access() method (the full code is available in Listing 1):
<cffunction name="access" returntype="any" access="private" output="no"
hint="I encapsulate access to the attribute values within this object,
accepting an attribute name and returning the appropriate attribute value.">
<cfargument name="AttributeName" type="string" required="yes"
hint="I am the name of the attribute to return the value for">
<cfset var Local = structNew()>
<cfset Local.ReturnValue = variables.Data[variables.IteratorCount][arguments.AttributeName] >
With this in place, we can now simplify the data access in the custom methods to just:
<cfset Local.ReturnValue = variables.access("Price")>
I have used the IBO on a number of production projects over the last couple of months. One project in particular required almost daily changes to the (very complex) object model as we continually added new attributes and changed the rules for calculating existing attributes. I found the application extremely easy to maintain and it is now in production, powering over 20 different sites and performing very well under load.
If you don't have any calculations for getting or setting any of your object attributes and really don't expect any in the future, any kind of encapsulation is overkill, and you would be better just to display using recordsets and cfoutput - for one record or for many. If you do have calculated fields, give the IBO a try and see how it works for your projects.
|Peter Bell 01/02/07 07:19:46 PM EST|
Good catch! That was indeed a little messy and is something I plan to clean up later this month. if you're interested, I'll be reposting code on my Blog. I'm probably going to use isDone(), but will take a little time to look at some other iterators to see what syntax is most popular.
|Michael Long 11/26/06 07:49:10 PM EST|
Could just be me, but I'd expect a function named "isLast" to return true if I'm actually on the last record. Which would in turn lead to an off-by-one error, as the loop would terminate early.
Better, perhaps, would be isEOF, or isDone, either of which would be true if the current record count is greater than the actual record count.
The 3rd International WebRTC Summit, to be held Nov. 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA, announces that its Call for Papers is now open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 15th International Cloud Expo, 6th International Big Data Expo, 3rd International DevOps Summit and 2nd Internet of @ThingsExpo. WebRTC (Web-based Real-Time Communication) is an open source project supported by Google, Mozilla and Opera that aims to enable bro...
Sep. 4, 2015 01:15 AM EDT Reads: 1,612
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies leverage disruptive technologies to optimize revenue-generating systems, has been named “Bronze Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Founded in 1997, Pythian is a global IT services company that helps companies compete by adopting disruptive technologies such as cloud, Big Data, advanced analytics, and DevOps to advance innovation and increase agility. Specializing in designing, imple...
Sep. 4, 2015 12:00 AM EDT Reads: 379
Containers are not new, but renewed commitments to performance, flexibility, and agility have propelled them to the top of the agenda today. By working without the need for virtualization and its overhead, containers are seen as the perfect way to deploy apps and services across multiple clouds. Containers can handle anything from file types to operating systems and services, including microservices. What are microservices? Unlike what the name implies, microservices are not necessarily small, but are focused on specific tasks. The ability for developers to deploy multiple containers – thous...
Sep. 3, 2015 10:00 PM EDT Reads: 191
SYS-CON Events announced today that IceWarp will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. IceWarp, the leader of cloud and on-premise messaging, delivers secured email, chat, documents, conferencing and collaboration to today's mobile workforce, all in one unified interface
Sep. 3, 2015 10:00 PM EDT Reads: 488
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be.
Sep. 3, 2015 08:30 PM EDT Reads: 164
Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome,” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.
Sep. 3, 2015 04:30 PM EDT Reads: 430
As more and more data is generated from a variety of connected devices, the need to get insights from this data and predict future behavior and trends is increasingly essential for businesses. Real-time stream processing is needed in a variety of different industries such as Manufacturing, Oil and Gas, Automobile, Finance, Online Retail, Smart Grids, and Healthcare. Azure Stream Analytics is a fully managed distributed stream computation service that provides low latency, scalable processing of streaming data in the cloud with an enterprise grade SLA. It features built-in integration with Azur...
Sep. 3, 2015 02:45 PM EDT Reads: 388
With the proliferation of connected devices underpinning new Internet of Things systems, Brandon Schulz, Director of Luxoft IoT – Retail, will be looking at the transformation of the retail customer experience in brick and mortar stores in his session at @ThingsExpo. Questions he will address include: Will beacons drop to the wayside like QR codes, or be a proximity-based profit driver? How will the customer experience change in stores of all types when everything can be instrumented and analyzed? As an area of investment, how might a retail company move towards an innovation methodolo...
Sep. 3, 2015 02:30 PM EDT Reads: 516
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
Sep. 3, 2015 02:30 PM EDT Reads: 966
SYS-CON Events announced today the Containers & Microservices Bootcamp, being held November 3-4, 2015, in conjunction with 17th Cloud Expo, @ThingsExpo, and @DevOpsSummit at the Santa Clara Convention Center in Santa Clara, CA. This is your chance to get started with the latest technology in the industry. Combined with real-world scenarios and use cases, the Containers and Microservices Bootcamp, led by Janakiram MSV, a Microsoft Regional Director, will include presentations as well as hands-on demos and comprehensive walkthroughs.
Sep. 3, 2015 02:15 PM EDT Reads: 416
Contrary to mainstream media attention, the multiple possibilities of how consumer IoT will transform our everyday lives aren’t the only angle of this headline-gaining trend. There’s a huge opportunity for “industrial IoT” and “Smart Cities” to impact the world in the same capacity – especially during critical situations. For example, a community water dam that needs to release water can leverage embedded critical communications logic to alert the appropriate individuals, on the right device, as soon as they are needed to take action.
Sep. 3, 2015 01:30 PM EDT
WebRTC services have already permeated corporate communications in the form of videoconferencing solutions. However, WebRTC has the potential of going beyond and catalyzing a new class of services providing more than calls with capabilities such as mass-scale real-time media broadcasting, enriched and augmented video, person-to-machine and machine-to-machine communications. In his session at @ThingsExpo, Luis Lopez, CEO of Kurento, will introduce the technologies required for implementing these ideas and some early experiments performed in the Kurento open source software community in areas ...
Sep. 3, 2015 01:15 PM EDT Reads: 110
Consumer IoT applications provide data about the user that just doesn’t exist in traditional PC or mobile web applications. This rich data, or “context,” enables the highly personalized consumer experiences that characterize many consumer IoT apps. This same data is also providing brands with unprecedented insight into how their connected products are being used, while, at the same time, powering highly targeted engagement and marketing opportunities. In his session at @ThingsExpo, Nathan Treloar, President and COO of Bebaio, will explore examples of brands transforming their businesses by t...
Sep. 3, 2015 12:30 PM EDT Reads: 287
In his session at @ThingsExpo, Lee Williams, a producer of the first smartphones and tablets, will talk about how he is now applying his experience in mobile technology to the design and development of the next generation of Environmental and Sustainability Services at ETwater. He will explain how M2M controllers work through wirelessly connected remote controls; and specifically delve into a retrofit option that reverse-engineers control codes of existing conventional controller systems so they don't have to be replaced and are instantly converted to become smart, connected devices.
Sep. 3, 2015 12:00 PM EDT Reads: 257
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts, GM of Platform at FinancialForce.com, will discuss the value of business applications on wearable ...
Sep. 3, 2015 10:45 AM EDT
SYS-CON Events announced today that Micron Technology, Inc., a global leader in advanced semiconductor systems, will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Micron’s broad portfolio of high-performance memory technologies – including DRAM, NAND and NOR Flash – is the basis for solid state drives, modules, multichip packages and other system solutions. Backed by more than 35 years of technology leadership, Micron's memory solutions enable the world's most innovative computing, consumer,...
Sep. 3, 2015 10:00 AM EDT Reads: 285
17th Cloud Expo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, 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 strategy. Meanwhile, 94% of enterprises are using some form of XaaS – software, platform, and infrastructure as a service.
Sep. 3, 2015 10:00 AM EDT Reads: 1,604
As more intelligent IoT applications shift into gear, they’re merging into the ever-increasing traffic flow of the Internet. It won’t be long before we experience bottlenecks, as IoT traffic peaks during rush hours. Organizations that are unprepared will find themselves by the side of the road unable to cross back into the fast lane. As billions of new devices begin to communicate and exchange data – will your infrastructure be scalable enough to handle this new interconnected world?
Sep. 3, 2015 09:30 AM EDT Reads: 205
While many app developers are comfortable building apps for the smartphone, there is a whole new world out there. In his session at @ThingsExpo, Narayan Sainaney, Co-founder and CTO of Mojio, will discuss how the business case for connected car apps is growing and, with open platform companies having already done the heavy lifting, there really is no barrier to entry.
Sep. 3, 2015 09:30 AM EDT Reads: 214
SYS-CON Events announced today that the "Second Containers & Microservices Expo" will take place November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities.
Sep. 3, 2015 09:30 AM EDT Reads: 652