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

What's an Object? An Introduction to OOP

An introduction to object-oriented programming for ColdFusion developers

At this point all we've done is create an object, but we haven't called a constructor. Or have we? Although CFCs don't have formal constructors, they do have what's usually referred to as a "pseudo-constructor." When you create a CFC, any code that's placed after the opening cfcomponent tag but outside any cffunction tags will get executed. We'll look at the code for our Person CFC in a moment, but here's a short example:


<cfcomponent>
<!--- this is the pseudo-constructor --->
<cfset variables.firstName = "Matt" />
<cfset variables.lastName = "Woodward" />
<!--- end of pseudo-constructor --->

<!--- object methods begin here --->
<cffunction name="doSomething">
etc. ...
</cffunction>
</cfcomponent>
Now obviously you aren't going to want to set all of your Person objects' names to "Matt Woodward" as they're created, but I hope you understand the concept. The CFML code in the area after the opening component tag but before the first cffunction tag will get executed when you create an instance of this CFC by using cfobject or CreateObject().

What has become considered a bit of a best practice in OO development with CFCs is not to rely on this pseudo-constructor, but rather to provide a method in the object called init() that is used as a constructor for the CFC. This allows for an explicit call to a constructor that is more along the lines of what happens in other OO languages. So while you could still create the object without calling the init method, in many cases you would do something like this:

matt = CreateObject("component", "Person").init("Matt", "Woodward");

This would create the object and immediately call the object's init method. By passing the init method a first and last name, in this case the object subsequently calls the setters for the firstName and lastName attributes in the object (we'll see specifically how this works in a moment). Bear in mind you could also call the init method and pass it no arguments and the object would be created; it just won't know its name or anything else about itself until we set those values. This will all be coming together shortly!

The Person CFC
If you're with me so far, you're well on your way to understanding objects and being able to start using them in your ColdFusion applications. Armed with all your newfound OO knowledge, let's take a look at the specific implementation of the Person CFC. What I won't cover in this article is how to use this CFC in the context of a larger application; I don't want to muddy the waters with how you will throw objects around in your applications just yet.

Let's briefly review the important object concepts before taking a look at the specific CFC code:

  • Objects have attributes (e.g., first name and last name)
  • Objects have methods (e.g., getFirstName(), setFirstName())
  • Objects are self-contained, meaning the object's data and the methods that work with the data are all contained within the object itself
  • Objects use encapsulation, meaning you will only interact with the object via the methods that it exposes to you
  • Objects contain a constructor method that is called to construct the object (set default attribute values, etc.)
  • Objects are your friend and you will use them whenever possible in your ColdFusion applications (sorry, had to throw that in here!)
And now, without further delay, let's take a look at the Person.cfc code (see Listing 1)! We're going to limit our CFC's attributes to just first name and last name, and there's going to be some "stuff" in here that we won't concern ourselves with at this stage, but we'll look over the CFC's anatomy after you peruse the code for yourself. See if you can pick out all of the concepts we've discussed and how they're implemented in this CFC.

If we want to create an instance of this object with the first name "Matt" and the last name "Woodward," we'd just use the code we outlined earlier, but now that you've see the CFC code you'll have a better understanding of what's happening:

matt = CreateObject("component", "Person").init("Matt", "Woodward");

This creates the object, and since we're calling the init method and passing it a first and last name, the init method in turn calls the setters for these attributes within the object.

Finally, since the init method returns the object itself, the "matt" variable becomes an instance of the Person object with the first and last name attributes set. How many items from our object concept list did you pick out? Let's walk through a few of them.

1.  Our object has attributes, specifically firstName and lastName. While a real-world object would typically have a lot more attributes than this, these suffice to illustrate the concept.

2.  Our object has methods, five to be exact. We have an init method that serves as a constructor, and a pair of get and set methods for each of our two attributes. The get methods simply return a string for their respective attribute, and the set methods take a string as an argument and set the attribute's value to the value of the argument passed to the method.

3.  Our object is self-contained. The object's attributes (data) and the methods that interact with this data are all contained within the object itself.

4.  Because we have getters and setters and no publicly accessible data (we'll discuss public, private, and surrounding issues in a future article), we're using encapsulation. You can only get and set the attribute values via the methods that the object provides to you for this purpose.

5.  Our object contains a constructor, which in this case is our init method. The two arguments firstName and lastName are marked as optional so we can either call init() and not pass it any arguments, in which case we'd get an object back with no value for firstName and lastName, or we can pass it arguments and the firstName and lastName attributes are set accordingly. Last, objects clearly are your best friend and you will be using them whenever possible in your ColdFusion applications! Even if you're not convinced quite yet, I hope you can at least see the tremendous potential for the use of objects in your applications. Once you really understand objects and get the hang of how to use them, it will make your development work much easier, your applications far easier to maintain, and you'll be writing your ColdFusion applications using the same methodologies as the rest of the software development world.

Looking Ahead...
I hope this relatively high-level overview of what an object is and how you apply object concepts in the ColdFusion world has piqued your interest in the wonderful world of object-oriented programming. While I can't promise that it will bring you vast wealth and make you more attractive to others, I can promise that it's a better way to develop ColdFusion applications. Even if it might seem a bit complex at first, after you've been working with objects for a bit you'll start to see the complexity fall away and you won't be able to imagine how you ever developed without them.

Please feel free to e-mail me if there are specific things you'd like to see addressed in future articles, but I think a logical next step will be to address some of the specific gotchas you'll need to be aware of as you start using CFCs as objects, and to show you how to use this Person CFC in a real-world application. Stay tuned for another installment in the near future!

Resources

  • Sierra, Kathy and Bert Bates. Head First Java. O'Reilly, 2004.
  • Taylor, David A. Object Technology: A Manager's Guide. 2nd ed. Addison-Wesley, 1998.
  • Weisfeld, Matt. The Object-Oriented Thought Process. 2nd ed. Sam's Publishing, 2004.

More Stories By Matthew Woodward

Matt Woodward is Principal Information Technology Specialist with the Office of the Sergeant at Arms at the United States Senate. He was until recently a Web application developer for i2 Technologies in Dallas, Texas. A Macromedia Certified ColdFusion Developer and a member of Team Macromedia, he has been using ColdFusion since 1996. In addition to his ColdFusion work, Matt also develops in Java and PHP.

Comments (0)

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.


@ThingsExpo Stories
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. 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 ov...
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, whic...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...