|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 Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, will explore the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.
Oct. 9, 2015 05:30 PM EDT
Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi's VP Business Development and Engineering, will explore the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context w...
Oct. 9, 2015 05:15 PM EDT Reads: 110
The buzz continues for cloud, data analytics and the Internet of Things (IoT) and their collective impact across all industries. But a new conversation is emerging - how do companies use industry disruption and technology enablers to lead in markets undergoing change, uncertainty and ambiguity? Organizations of all sizes need to evolve and transform, often under massive pressure, as industry lines blur and merge and traditional business models are assaulted and turned upside down. In this new data-driven world, marketplaces reign supreme while interoperability, APIs and applications deliver un...
Oct. 9, 2015 04:00 PM EDT Reads: 303
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
Oct. 9, 2015 04:00 PM EDT Reads: 238
Electric power utilities face relentless pressure on their financial performance, and reducing distribution grid losses is one of the last untapped opportunities to meet their business goals. Combining IoT-enabled sensors and cloud-based data analytics, utilities now are able to find, quantify and reduce losses faster – and with a smaller IT footprint. Solutions exist using Internet-enabled sensors deployed temporarily at strategic locations within the distribution grid to measure actual line loads.
Oct. 9, 2015 03:49 PM EDT
You have your devices and your data, but what about the rest of your Internet of Things story? Two popular classes of technologies that nicely handle the Big Data analytics for Internet of Things are Apache Hadoop and NoSQL. Hadoop is designed for parallelizing analytical work across many servers and is ideal for the massive data volumes you create with IoT devices. NoSQL databases such as Apache HBase are ideal for storing and retrieving IoT data as “time series data.”
Oct. 9, 2015 03:45 PM EDT Reads: 506
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.
Oct. 9, 2015 03:45 PM EDT Reads: 141
The IoT market is on track to hit $7.1 trillion in 2020. The reality is that only a handful of companies are ready for this massive demand. There are a lot of barriers, paint points, traps, and hidden roadblocks. How can we deal with these issues and challenges? The paradigm has changed. Old-style ad-hoc trial-and-error ways will certainly lead you to the dead end. What is mandatory is an overarching and adaptive approach to effectively handle the rapid changes and exponential growth.
Oct. 9, 2015 03:00 PM EDT Reads: 207
Today’s connected world is moving from devices towards things, what this means is that by using increasingly low cost sensors embedded in devices we can create many new use cases. These span across use cases in cities, vehicles, home, offices, factories, retail environments, worksites, health, logistics, and health. These use cases rely on ubiquitous connectivity and generate massive amounts of data at scale. These technologies enable new business opportunities, ways to optimize and automate, along with new ways to engage with users.
Oct. 9, 2015 02:00 PM EDT Reads: 187
The IoT is upon us, but today’s databases, built on 30-year-old math, require multiple platforms to create a single solution. Data demands of the IoT require Big Data systems that can handle ingest, transactions and analytics concurrently adapting to varied situations as they occur, with speed at scale. In his session at @ThingsExpo, Chad Jones, chief strategy officer at Deep Information Sciences, will look differently at IoT data so enterprises can fully leverage their IoT potential. He’ll share tips on how to speed up business initiatives, harness Big Data and remain one step ahead by apply...
Oct. 9, 2015 01:45 PM EDT Reads: 562
There will be 20 billion IoT devices connected to the Internet soon. What if we could control these devices with our voice, mind, or gestures? What if we could teach these devices how to talk to each other? What if these devices could learn how to interact with us (and each other) to make our lives better? What if Jarvis was real? How can I gain these super powers? In his session at 17th Cloud Expo, Chris Matthieu, co-founder and CTO of Octoblu, will show you!
Oct. 9, 2015 01:15 PM EDT
SYS-CON Events announced today that ProfitBricks, the provider of painless cloud infrastructure, will exhibit at SYS-CON's 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. ProfitBricks is the IaaS provider that offers a painless cloud experience for all IT users, with no learning curve. ProfitBricks boasts flexible cloud servers and networking, an integrated Data Center Designer tool for visual control over the cloud and the best price/performance value available. ProfitBricks was named one of the coolest Clo...
Oct. 9, 2015 01:00 PM EDT Reads: 798
As a company adopts a DevOps approach to software development, what are key things that both the Dev and Ops side of the business must keep in mind to ensure effective continuous delivery? In his session at DevOps Summit, Mark Hydar, Head of DevOps, Ericsson TV Platforms, will share best practices and provide helpful tips for Ops teams to adopt an open line of communication with the development side of the house to ensure success between the two sides.
Oct. 9, 2015 01:00 PM EDT Reads: 607
SYS-CON Events announced today that IBM Cloud Data Services 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. IBM Cloud Data Services offers a portfolio of integrated, best-of-breed cloud data services for developers focused on mobile computing and analytics use cases.
Oct. 9, 2015 12:00 PM EDT Reads: 738
SYS-CON Events announced today that Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, will keynote 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.
Oct. 9, 2015 11:15 AM EDT
Developing software for the Internet of Things (IoT) comes with its own set of challenges. Security, privacy, and unified standards are a few key issues. In addition, each IoT product is comprised of at least three separate application components: the software embedded in the device, the backend big-data service, and the mobile application for the end user's controls. Each component is developed by a different team, using different technologies and practices, and deployed to a different stack/target - this makes the integration of these separate pipelines and the coordination of software upd...
Oct. 9, 2015 09:00 AM EDT Reads: 296
Mobile messaging has been a popular communication channel for more than 20 years. Finnish engineer Matti Makkonen invented the idea for SMS (Short Message Service) in 1984, making his vision a reality on December 3, 1992 by sending the first message ("Happy Christmas") from a PC to a cell phone. Since then, the technology has evolved immensely, from both a technology standpoint, and in our everyday uses for it. Originally used for person-to-person (P2P) communication, i.e., Sally sends a text message to Betty – mobile messaging now offers tremendous value to businesses for customer and empl...
Oct. 9, 2015 08:30 AM EDT Reads: 311
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Oct. 9, 2015 07:00 AM EDT Reads: 5,887
WebRTC converts the entire network into a ubiquitous communications cloud thereby connecting anytime, anywhere through any point. In his session at WebRTC Summit,, Mark Castleman, EIR at Bell Labs and Head of Future X Labs, will discuss how the transformational nature of communications is achieved through the democratizing force of WebRTC. WebRTC is doing for voice what HTML did for web content.
Oct. 9, 2015 06:00 AM EDT Reads: 1,416
Nowadays, a large number of sensors and devices are connected to the network. Leading-edge IoT technologies integrate various types of sensor data to create a new value for several business decision scenarios. The transparent cloud is a model of a new IoT emergence service platform. Many service providers store and access various types of sensor data in order to create and find out new business values by integrating such data.
Oct. 9, 2015 04:00 AM EDT Reads: 572