On New Year's Eve, 2004 I declared 2005 to be the "year of object-oriented programming for ColdFusion developers," and since the year is approaching its final quarter it's a good time to focus our attention on OOP in ColdFusion and see how we're doing.
Based on talking with developers both in person and virtually, reading blogs, and looking at some of the newer ColdFusion code that people have been sending my way over the last few months, I'm really excited about the increase in interest and use of OOP in ColdFusion. The ability to even do object-oriented programming in ColdFusion is a relatively new addition to the technology, so it's not surprising that it's taken a bit of time to catch on. From what I'm seeing these days the tide is definitely turning, so this is great to see.
What I also see occurring, however, is an increasing gap between the ColdFusion developers who are embracing OOP wholeheartedly and those who want to dive into OOP but don't quite know how to go about doing so, or have gotten started but get frustrated or discouraged and go back to their old ways of doing things. This is lamentable but understandable. Coming from the procedural mindset that many ColdFusion developers have, making the move to OOP is not something that will happen instantly, and in many cases developers are under deadlines and just can't afford to ditch their tried-and-true methods for OOP if they don't yet have a comfort level with it.
With that in mind, this article is designed to give ColdFusion developers an extremely gentle introduction to some OOP fundamentals. In working with other developers I've found that these concepts have helped many of them make the transition from ColdFusion 5-style procedural coding into OOP in CFMX 6.1 and 7. This is a transition that in my opinion ColdFusion developers can't afford not to make. Object-oriented programming has been around since the 1960s, all modern languages support OOP to varying degrees, and the ubiquity of OOP is not accidental; it really is a better way to build applications. I hope by the end of this article you'll agree with me and start to see the OO light.
ColdFusion's OO Conundrum
If you're reading this chances are I don't need to convince you of the tremendous strengths of ColdFusion: ease of use, huge feature set, rapid development, integration with Java.... These are all great things, and ColdFusion 7 made things even better with the addition of the cfdocument tag, Flash forms and XForms, event gateways, and a great deal of other new features that help us build better applications more quickly and easily.
With all that having been said, and I don't want to scare anyone, I truly believe that if ColdFusion - and by extension ColdFusion developers - is going to survive over the long haul, we absolutely must get with the times and start down the path of truly understanding OOP and using it as the default way we do ColdFusion development. Every other major Web application development platform is fully OO or rapidly getting there, so the days for excuses are over. OOP has become king of the software development world for a reason, and I promise that once you truly understand it you'll wonder how you ever got along without it. It's quite simply a better way to solve real-world problems through programming.
First and perhaps foremost, I think it's quite unfortunate that most of the ColdFusion literature dives right into CFML syntax and spends a great deal of time illustrating how to build entirely page-based, procedural applications, only discussing ColdFusion Components (CFCs) and OOP as an afterthought. Since OOP wasn't really even possible prior to the introduction of CFCs in CFMX, and even then a lot of the huge quirks weren't worked out until CFMX 6.1, I suppose this situation shouldn't be surprising.
However let's consider where we are today. CFMX 6.1 is now the "old" version and we have a fantastic new release with ColdFusion 7, so it's high time that we start using the tools available to us to their full potential. I only hope that the ColdFusion literature begins to reflect this mode of thinking as well, and I think that will happen given the huge upswing in interest in OOP I've seen over the last few months.
As a bit of an aside, I'm going to forgo the "Is ColdFusion/Are CFCs fully OO?" argument because I think it's largely irrelevant to the discussion at hand. While it is true that CFCs lack certain characteristics of objects in fully-OO languages such as Java, that's certainly not a reason to not use them to do OOP in ColdFusion. First we all need to understand what OO is and start using CFCs to do OO programming in ColdFusion, then we can talk about how CFCs differ from something like a Java object and address any limitations, tricks, and traps related to these issues.
If you pick up any good Java book (I'll have a few good recommendations at the end of this article) it will start with a discussion of objects and basic OOP concepts before you even see much Java code. Better still, there are a couple of good language-agnostic OO books that can provide a solid grounding in OO concepts before you even start writing any code. With OOP it's extremely important that you have a firm foundation in the fundamental concepts before you jump right into development, especially if you have a completely procedural programming background.
At the outset, thinking in objects is in my estimation far more important than understanding how to implement these concepts in code. In the first Java class I took at Sun Microsystems we didn't write a single line of code, we just spent an entire week talking about objects and approaching problem solving in an object-oriented fashion. This was all rather abstract and didn't involve a single line of Java code, but it's still the best Java class I ever took.
While ColdFusion's audience is admittedly a bit bifurcated when compared to Java's, I still believe it's of the utmost importance both for us as developers and for the reputation of ColdFusion as a technology that we make OOP the de facto way we develop applications in ColdFusion. One of ColdFusion's biggest strengths is that it's easy to learn and allows even non-programmers to get results very quickly. This is also one of its biggest weaknesses. The challenge, then, is to somehow keep the ease of use/rapid development reputation while strengthening the notion that CF is an extremely capable development platform that can be used to build enterprise-level applications using the same methodologies as the two giants of the Web application development world, namely Java and .NET. I don't have a solution for this conundrum yet, but I do believe that making OOP an inextricable part of CF development is a big step in the right direction.
As I climb off my soapbox, try to put your mind in a place that might be new to some of you. Imagine if you will a world where there is no procedural programming. In this world all software is built with objects, and a software application is nothing more than objects communicating with one another. (I'll focus more on the distinctions between procedural programming and OOP in a future article.) At the heart of this style of development of course is the concept of what an object is, so let's address that question before we go any deeper.
What's an Object?
I'm glad you asked that question! I've talked with a lot of ColdFusion developers who are intrigued by the idea of objects and OOP, but they just don't even know where to begin. To quote Maria von Trapp, "Let's start at the very beginning, a very good place to start." The beginning of object-oriented programming is of course the concept of the object. To be completely truthful there is a bit of a chicken-and-egg situation between the concept of a class and the concept of an object. For the moment let's simply focus on explaining what an object is, not only because they don't call it "Class-Oriented Programming," but because I think you'll find it easier to understand the concept of a class if you first understand what an object is.
To put it extremely simply, you already know what an object is. Objects are all around you. If you look at the computer you spend countless hours a day using, that will serve as a good example of what an object is in the real world. One of the amazingly powerful things about software objects is that they're designed to model real-world objects, and do quite a good job of it!
Your computer is an object, and as an object it has certain characteristics such as brand, processor type and speed, amount of RAM, hard drive size, etc. In object lingo, these characteristics are called attributes. Your computer can also do things (sometimes it doesn't do what you want it to do, but it's still doing something!). It can power up, launch applications, automatically run tasks such as a virus scan, and power down. In object parlance these things that your computer can do would be referred to as methods (or sometimes they're referred to slightly less accurately, at least from an OOP standpoint, as functions).
In addition to attributes and methods, perhaps the most important characteristic of an object is that it's self-contained. As I said earlier I'm not going to dive into the differences between procedural programming and OOP at this point because I think that's a bit difficult to understand without really understanding what an object is, but the notion of a self-contained object is important to address. In procedural programming there basically exists data and functions that work with this data, but the data and functions are typically separate and distinct from one another. With an object, the data (attributes) and functions (methods) are all contained within a single, tidy little software component known as the object. This offers numerous advantages that we'll delve into in a future article.
I'm a Person, Not an Object!
Let's consider another, very commonly used example to shed more light on the concept of objects, and this one you'll probably use more regularly in your applications: a person. A Person object, like the Computer object, also has attributes (for example, first and last name) and things they can do, or methods (for example, "walk"). So while you might not prefer to be thought of as an object, as far as the software world is concerned a person is a rather ideal example of an object. If you don't take too much offense let's proceed with this example for now.
Recalling that the three most important aspects of an object are attributes, methods, and that the object is self-contained, we're now going to look more specifically at how we'd go about modeling a person as an object in our applications. First, let's make a basic list of some of the more important attributes that a person has:
A Touch of Class
Earlier I mentioned the term class, and before we go much further we need to touch briefly on what a class is. Now that you understand at least in a basic sense what an object is you'll grasp the concept of class pretty easily. A class can be thought of as a generic version of an object. Continuing with our Person object discussion, think of the Person class as a generic person. You don't know if this person is male or female, young or old, short or tall, it's just a nameless, faceless, abstract person.
In OOP you use this generic Person class as the blueprint for creating specific Person objects. The Person class knows that a person has the attributes and methods listed above but knows nothing specific about a particular person. In other words, the Person class knows that a person has a first name, but it doesn't know any particular person's first name. The Person object will know specific details about a particular person, such as "This particular Person's first name is Matt."
You create a specific Person object, which is also known as an instance of the Person class, by instantiating the class. This is a fancy OO way of saying, "Let's take this generic Person class and make it into a specific Person object." For argument's sake let's assume we want to create a Person object called "matt." (I could always use another one of myself to help me get things done.)
In terms specific to ColdFusion, objects are defined using ColdFusion Components (CFCs). The Person class would be a CFC called Person.cfc. To instantiate this class in ColdFusion, you would either use the cfobject tag or the CreateObject function as follows:
Using the cfobject tag:
<cfobject component="Person" name="matt" />
Using CreateObject (this could be within a cfscript block or you could do this within a
cfset tag as well):
matt = CreateObject("component", "Person");
There are some details you'll need to know regarding where ColdFusion looks to locate your CFCs, but don't concern yourself with the specifics of implementation at the moment. Just repeat this phrase over and over again: "I'm thinking in objects. I'm thinking in objects." We'll get to a specific implementation at the end of this article.
So at this point we have a specific Person object called matt with which we can start working. When the matt object is first created, however, it doesn't necessarily know anything about itself. There are a couple of standard ways to get data into our object. You might think we can just start setting our object's attributes using dot notation as follows:
matt.firstName = "Matt";
matt.lastName = "Woodward";
Not so fast! You may recall from the discussion above that one of the hallmarks of an object is that it's self-contained. What does this mean? In addition to meaning that the object's data and the methods for working with the data are both contained within the object, it also means that you should never (and in most cases, well-designed objects won't let you) set an object's data directly as illustrated above. A good object will contain methods that will allow other objects to access its data as needed, and the polite OO behavior is to use these methods - and only these methods - to interact with the object. You don't want to be seen as rude on your first visit to ObjectLand, do you?
Don't Touch My Data... At Least Not Without Asking
Only using an object's methods to access its data brings up another OO concept called encapsulation. In brief, encapsulation refers to the situation I described above whereby you only interact with an object through the methods it exposes to you. For something simple such as retrieving a Person object's first name this may seem like overkill (why not just grab the data directly?), but let's consider another example. If you were to have an object that contained a method that had to perform relatively complex operations to return the requested data to you, you shouldn't have to know (and probably don't even want to know!) what the object is doing to return that data.
In this sense an object and its use of encapsulation are like a telephone. You just plug the phone into the wall, pick up the receiver, and you get a dial tone. You don't know or care about what's going on in the wiring, switching, etc., you just want to get a dial tone. This is exactly what encapsulation does. It provides an interface for you to use to get what you need without requiring you to know what's going on behind the scenes. This is important for simplicity and ease of use, to protect the object's data, and to keep things from breaking in the future. Imagine if you had to reconfigure your telephone every time the phone company got a new piece of hardware on their network!
Encapsulation protects you from having to modify your code if the implementation of a particular operation in an object changes. This could be as simple as changing the way a value is calculated or as complex as changing from a relational database to an XML-based data storage system. Regardless of the specifics involved, encapsulation will keep your OO systems humming right along even if a relatively drastic change has to be made to an object within the system.
Beans: They're Not Just a Breakfast Food
(with Apologies to Johnny Cash)
To summarize the idea of encapsulation, any code that interacts with an object should never modify the object's data directly. In procedural programming variable values such as someone's name are modified directly, but as we'll see in a future article this leads to problems that we can avoid with good OOP. This is why a best practice in OOP involves the creation and use of methods within objects known as getters and setters (also referred to as accessors and mutators). These are simple methods that allow us to retrieve and set values of data within objects through method calls, as opposed to accessing the data directly.
If an object has getters and setters for each of its attributes, it is actually a specific type of object known as a bean. The bean concept comes from the Java world, where everything is related to coffee in one way or another, so I suppose that's as good an explanation as any for the name. A bean is a type of object that is very commonly used to represent real-world constructs such as a Person, Computer, or Car. There are of course other types of objects you'll be using in OOP, but in my experience if people grasp real-world objects (which in turn are usually beans in OO systems), it's a lot easier to start working with other types of objects as well. The CFC example we'll see at the end of this article will technically be a bean.
Returning to the example above, after we create our matt object we'll want to set the values for matt's attributes so the object is no longer an empty shell of a Person. You've probably already surmised that since we can't access the object's data directly, we're going to be using the object's get and set methods to interact with the matt object. Let's tell matt what his first and last names are by using the object's setters for these attributes:
matt.setFirstName("Matt");
matt.setLastName("Woodward");
As you can see, the set methods take a single argument, a string, to set the values of first and last name. Once these values are set, we can then turn around and ask the matt object what its first and last name is by using the object's get methods:
<cfoutput>The matt object's first name is #matt.getFirstName()#, and
the matt object's last name is #matt.getLastName()#.</cfoutput>
I hope you're already starting to see how this can simplify many of your programming tasks. Once an object is instantiated and the data is populated within the object (and even that step isn't terribly complex), you simply ask the object for its data and can use it wherever it's needed. This makes for clean, flexible code that's easy to use and maintain.
Object Constructors
The final concept I'll address in this article before moving on to the specific code for our Person CFC is the concept of a constructor. A constructor is a method within a class that provides the means to construct the object. What this construction operation usually involves is setting any default data that's absolutely necessary for the object to function correctly once it's instantiated.
In the case of the bean object we're discussing, you can use this constructor method to create the object and set all of the attribute values rather than setting each attribute's value individually. Most objects will have what's called a "no-arg constructor," which means that if you want to instantiate the object but don't have the object's attribute values right at that particular moment, you can simply create the object, pass the constructor method no arguments or data, and the constructor will handle anything that's absolutely essential for that object to exist.
At this point we've hit upon one of the first differences of CFCs as compared to other OO languages such as Java. CFCs do not have the concept of a constructor. In Java, to create a new object you typically do something like this:
Person matt = new Person();
Because in Java the constructor method shares the same name with the object itself, that Person() call will invoke the object's constructor method. Let's revisit how we created our CFC objects earlier:
matt = CreateObject("component", "Person");
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:
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().
<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>
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:
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