|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.
In his general session at 18th Cloud Expo, Lee Atchison, Principal Cloud Architect and Advocate at New Relic, discussed cloud as a ‘better data center’ and how it adds new capacity (faster) and improves application availability (redundancy). The cloud is a ‘Dynamic Tool for Dynamic Apps’ and resource allocation is an integral part of your application architecture, so use only the resources you need and allocate /de-allocate resources on the fly.
Sep. 27, 2016 09:30 AM EDT Reads: 2,627
Vidyo, Inc., has joined the Alliance for Open Media. The Alliance for Open Media is a non-profit organization working to define and develop media technologies that address the need for an open standard for video compression and delivery over the web. As a member of the Alliance, Vidyo will collaborate with industry leaders in pursuit of an open and royalty-free AOMedia Video codec, AV1. Vidyo’s contributions to the organization will bring to bear its long history of expertise in codec technolo...
Sep. 27, 2016 08:30 AM EDT Reads: 2,636
There is little doubt that Big Data solutions will have an increasing role in the Enterprise IT mainstream over time. Big Data at Cloud Expo - to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA - has announced its Call for Papers is open. Cloud computing is being adopted in one form or another by 94% of enterprises today. Tens of billions of new devices are being connected to The Internet of Things. And Big Data is driving this bus. An exponential increase is...
Sep. 27, 2016 08:15 AM EDT Reads: 2,621
An IoT product’s log files speak volumes about what’s happening with your products in the field, pinpointing current and potential issues, and enabling you to predict failures and save millions of dollars in inventory. But until recently, no one knew how to listen. In his session at @ThingsExpo, Dan Gettens, Chief Research Officer at OnProcess, will discuss recent research by Massachusetts Institute of Technology and OnProcess Technology, where MIT created a new, breakthrough analytics model f...
Sep. 27, 2016 08:00 AM EDT Reads: 1,989
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, wh...
Sep. 27, 2016 08:00 AM EDT Reads: 3,677
Ask someone to architect an Internet of Things (IoT) solution and you are guaranteed to see a reference to the cloud. This would lead you to believe that IoT requires the cloud to exist. However, there are many IoT use cases where the cloud is not feasible or desirable. In his session at @ThingsExpo, Dave McCarthy, Director of Products at Bsquare Corporation, will discuss the strategies that exist to extend intelligence directly to IoT devices and sensors, freeing them from the constraints of ...
Sep. 27, 2016 07:45 AM EDT Reads: 2,496
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform and how we integrate our thinking to solve complicated problems. In his session at 19th Cloud Expo, Craig Sproule, CEO of Metavine, will demonstrate how to move beyond today's coding paradigm ...
Sep. 27, 2016 07:45 AM EDT Reads: 3,277
From wearable activity trackers to fantasy e-sports, data and technology are transforming the way athletes train for the game and fans engage with their teams. In his session at @ThingsExpo, will present key data findings from leading sports organizations San Francisco 49ers, Orlando Magic NBA team. By utilizing data analytics these sports orgs have recognized new revenue streams, doubled its fan base and streamlined costs at its stadiums. John Paul is the CEO and Founder of VenueNext. Prior ...
Sep. 27, 2016 07:30 AM EDT Reads: 2,970
Technology vendors and analysts are eager to paint a rosy picture of how wonderful IoT is and why your deployment will be great with the use of their products and services. While it is easy to showcase successful IoT solutions, identifying IoT systems that missed the mark or failed can often provide more in the way of key lessons learned. In his session at @ThingsExpo, Peter Vanderminden, Principal Industry Analyst for IoT & Digital Supply Chain to Flatiron Strategies, will focus on how IoT de...
Sep. 27, 2016 07:15 AM EDT Reads: 1,117
IoT offers a value of almost $4 trillion to the manufacturing industry through platforms that can improve margins, optimize operations & drive high performance work teams. By using IoT technologies as a foundation, manufacturing customers are integrating worker safety with manufacturing systems, driving deep collaboration and utilizing analytics to exponentially increased per-unit margins. However, as Benoit Lheureux, the VP for Research at Gartner points out, “IoT project implementers often ...
Sep. 27, 2016 06:45 AM EDT Reads: 3,329
So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, provided tips on how to be successful in large scale machine learning...
Sep. 27, 2016 06:30 AM EDT Reads: 1,882
Information technology is an industry that has always experienced change, and the dramatic change sweeping across the industry today could not be truthfully described as the first time we've seen such widespread change impacting customer investments. However, the rate of the change, and the potential outcomes from today's digital transformation has the distinct potential to separate the industry into two camps: Organizations that see the change coming, embrace it, and successful leverage it; and...
Sep. 27, 2016 05:30 AM EDT Reads: 1,158
SYS-CON Events announced today that Roundee / LinearHub will exhibit at the WebRTC Summit at @ThingsExpo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. LinearHub provides Roundee Service, a smart platform for enterprise video conferencing with enhanced features such as automatic recording and transcription service. Slack users can integrate Roundee to their team via Slack’s App Directory, and '/roundee' command lets your video conference ...
Sep. 27, 2016 05:15 AM EDT Reads: 1,446
Digital transformation is too big and important for our future success to not understand the rules that apply to it. The first three rules for winning in this age of hyper-digital transformation are: Advantages in speed, analytics and operational tempos must be captured by implementing an optimized information logistics system (OILS) Real-time operational tempos (IT, people and business processes) must be achieved Businesses that can "analyze data and act and with speed" will dominate those t...
Sep. 27, 2016 04:45 AM EDT Reads: 1,159
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, will compare the Jevons Paradox to modern-day enterprise IT, e...
Sep. 27, 2016 04:30 AM EDT Reads: 2,043
There are several IoTs: the Industrial Internet, Consumer Wearables, Wearables and Healthcare, Supply Chains, and the movement toward Smart Grids, Cities, Regions, and Nations. There are competing communications standards every step of the way, a bewildering array of sensors and devices, and an entire world of competing data analytics platforms. To some this appears to be chaos. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, Bradley Holt, Developer Advocate a...
Sep. 27, 2016 04:15 AM EDT Reads: 2,115
SYS-CON Events announced today that Bsquare has been named “Silver Sponsor” of SYS-CON's @ThingsExpo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. For more than two decades, Bsquare has helped its customers extract business value from a broad array of physical assets by making them intelligent, connecting them, and using the data they generate to optimize business processes.
Sep. 27, 2016 03:00 AM EDT Reads: 2,781
There is growing need for data-driven applications and the need for digital platforms to build these apps. In his session at 19th Cloud Expo, Muddu Sudhakar, VP and GM of Security & IoT at Splunk, will cover different PaaS solutions and Big Data platforms that are available to build applications. In addition, AI and machine learning are creating new requirements that developers need in the building of next-gen apps. The next-generation digital platforms have some of the past platform needs a...
Sep. 27, 2016 03:00 AM EDT Reads: 1,809
SYS-CON Events announced today that ReadyTalk, a leading provider of online conferencing and webinar services, has been named Vendor Presentation Sponsor at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. ReadyTalk delivers audio and web conferencing services that inspire collaboration and enable the Future of Work for today’s increasingly digital and mobile workforce. By combining intuitive, innovative tec...
Sep. 27, 2016 03:00 AM EDT Reads: 2,945
Fact is, enterprises have significant legacy voice infrastructure that’s costly to replace with pure IP solutions. How can we bring this analog infrastructure into our shiny new cloud applications? There are proven methods to bind both legacy voice applications and traditional PSTN audio into cloud-based applications and services at a carrier scale. Some of the most successful implementations leverage WebRTC, WebSockets, SIP and other open source technologies. In his session at @ThingsExpo, Da...
Sep. 27, 2016 02:15 AM EDT Reads: 1,608