<cf_disclaimer>
I am NOT an OOP expert, I don’t play one on TV, nor did I stay in a Holiday Inn Express last night. I am fairly new to OOP. Please keep that in mind when reading this, especially if you wish to flame me.
</cf_disclaimer>
The other day at work there was a discussion outside my office about the way some CF developers are handling the creation on objects and how we use the init() method. The way I handle init() comes from the way I initially learned about using objects. Here’s a snippet:
<cfset myObj = createObject(“component”, “user”).init(args) />
What this does is create an object and call the init() method at the same time. However, one caveat is that in you must specify a returntype (which needs to equal the object you are instatiating) for you init() method, and use <cfreturn this /> in the method.
One of my co-workers thinks this is a bad idea. He suggests doing this:
<cfset myObj = createObject(“component”, “user”) />
<cfset myObj.init(args) />
Why? The only thing I could really make sense of is that we are treating init() as a constructor (because CF does not have *real* constructors), and constructors typically do not return anything (at least, to my knowledge, not in Java -- which I think was the OO language being referenced in the discussion). And by having init() return something, you are ‘breaking’ some OO principles.
While I did not take part in the discussion (because I really didn’t think I could bring anything worthwhile in to the discussion), it got me thinking about the issue
I may be wrong (and if so, please correct me), but in Java, when you create or instantiate an object, you get an init-ed object back (the constructor is called automatically). So, while using
<cfset myObj = createObject(“component”,”user”).init(args) />
may ‘break’ some OO principles, creating and using the object, to me, seems more OO-like (or Java-like) because you get a fully init-ed object when you create it.
For me, at least, it helps me to understand OOP a bit more when I use
<cfset myObj = createObject(“component”,”user”).init(args) />
because if I were creating classes in Java, I would not have to have a second line of code run my constructor (and I know, I would not have to call me constructor at time of creation either, its just easier for me to ‘get it’ doing it this was)
Are there any other compelling arguments for or against either of these methods?