Thursday, October 1, 2009

Implicit Getters and Setters

While the addition of implicit getters and setters for properties in ColdFusion is really nice, I'm still a little jealous of the how they're handled in Groovy.

Take the typical User object.


<cfcomponent name="User">

<cfproperty name="firstName" />
<cfproperty name="lastName" />

</cfcomponent>


In ColdFusion, you would interact with this object like such:


<cfset user = new User() />
<cfset user.setFirstName("Tony") />
<cfset user.setLastName("Nelson") />

<cfoutput>
Hello, my name is #user.getFirstName()# #user.getLastName()#
</cfoutput>


Pretty basic. Now how would that look if ColdFusion had implicit getters and setters like Groovy:


<cfset user = new User() />
<cfset user.firstName = "Tony" />
<cfset user.lastName = "Nelson" />

<cfoutput>
Hello, my name is #user.firstName# #user.lastName#
</cfoutput>


Much cleaner. Now before you say it's just accessing the properties directly (as if they were stored in the this scope), there's more to it than that. When you're accessing the property, the call is still being routed through the implicit getters and setters. This means you can still add your own custom logic to the properties by overriding their methods.

To demonstrate, let's add a 3rd property to the User component, fullName, and add our own getter.


<cfcomponent name="User">

<cfproperty name="firstName" />
<cfproperty name="lastName" />
<cfproperty name="fullName" />

<cffunction name="getFullName">
<cfreturn getFirstName() & " " & getLastName() />
</cffunction>

</cfcomponent>


Now let's update our code:


<cfset user = new User() />
<cfset user.firstName = "Tony" />
<cfset user.lastName = "Nelson" />

<cfoutput>
Hello, my name is #user.fullName#
</cfoutput>


Even though it looks like we're accessing the fullName property directly, it will still be routed through getFullName(), which should output "Tony Nelson".

I've gone back and forth on whether or not this is a good thing. On one hand, you're calling a method even though it doesn't look like it. On the other, it's a lot cleaner. Some people may argue that access to properties should remain hidden behind Accessors (getters) and Mutators (setters), but in truth they still are.

Besides, if our goal is to have rich business objects that have both properties and behavior, shouldn't we be able to treat the properties like they were just simply properties and nothing more? To me, having a getter implies there's some additional behavior required in order to retrieve a property, which in most cases there isn't. What are we really gaining by masking the call to a property behind a method?

Monday, September 21, 2009

ColdFusion and Frameworks

If you haven't read it yet, I would suggest reading this post by Matt Woodward. Very good points.

Honestly, if ColdFusion has been around for almost 15 years, why don't we have anything that comes even remotely close to Ruby on Rails or Grails? You could make the case that ColdFusion on Wheels and ColdBox are similar in their implementations, but then there are people that swear by Model-Glue, Mach-II, and Fusebox... and then there's Edmund, FW/1, onTap, etc... and those are just the front controller frameworks. If you want the total package, you'll have to wire in ColdSpring, LightWire, Transfer, Reactor, MXUnit, cfcUnit, cfSpec, etc...

Unfortunately, the ColdFusion framework community is so fragmented that I don't think there will ever be a widely-accepted, well-designed, dominant framework - a framework that just works - a framework that some developers might actually confuse with a language, like what happens with Rails(Ruby) and Grails(Groovy). Right now there are just too many smart ColdFusion developers all working on their own versions of the same thing.

Tuesday, September 1, 2009

Annotation-based Dependency Injection using ColdSpring

ColdSpring is by far the most essential tool I need for building ColdFusion applications. However, I'm not a huge fan of writing a ton of XML and I'm certainly not a fan of writing a lot of getters and setters inside my components.

To help ease that pain, I borrowed a feature from Model-Glue 3 and extended ColdSpring to create the "beans" scope.

Little did I realize ColdSpring can already handle a lot of what I wanted to do without having to modify ColdSpring itself simply by creating a factory post processor. To automatically inject the "beans" scope into my ColdSpring-managed beans, I created the following BeansScopeFactoryPostProcessor.cfc:


<cfcomponent>

<cffunction name="postProcessBeanFactory" access="public" returntype="void">

<cfset var local = {} />

<cfset local.beanDefs = getConcreteBeanClasses() />

<cfloop collection="#local.beanDefs#" item="local.beanName">

<cfset local.beanList = getBeanScopeList(local.beanDefs[local.beanName]) />

<cfif local.beanList neq "">

<cfset local.bean = getBeanFactory().getBean(local.beanName) />

<cfset injectBeansScope(local.bean,local.beanList) />

</cfif>

</cfloop>

</cffunction>

<cffunction name="getConcreteBeanClasses" access="private" returntype="struct">

<cfset var local = {} />

<cfset local.classes = {} />

<cfset local.beanDefs = getBeanFactory().getBeanDefinitionList() />

<cfloop collection="#local.beanDefs#" item="local.beanName">

<cfif not local.beanDefs[local.beanName].isAbstract()>
<cfset local.classes[local.beanName] = local.beanDefs[local.beanName].getBeanClass() />
</cfif>

</cfloop>

<cfreturn local.classes />

</cffunction>

<cffunction name="injectBeansScope" access="private" returntype="void">
<cfargument name="bean" required="true" />
<cfargument name="beanList" required="true" />

<cfset var local = {} />

<cfif isCFC(arguments.bean)>

<cfset local.beans = {} />

<cfloop list="#arguments.beanList#" index="local.beanName">
<cfset local.beans[local.beanName] = getBeanFactory().getBean(local.beanName) />
</cfloop>

<cfset arguments.bean.__setVariable = variables.__setVariable />

<cfset arguments.bean.__setVariable("beans",local.beans) />

<cfset StructDelete(arguments.bean,"__setVariable") />

</cfif>

</cffunction>

<cffunction name="getBeanScopeList" access="private" returntype="string">
<cfargument name="bean" required="true" />

<cfset var local = {} />

<cfset local.metaData = getComponentMetaData(arguments.bean) />

<cfset local.beanList = "" />

<cfif StructKeyExists(local.metaData,"beans")>

<cfloop list="#local.metaData.beans#" index="local.beanName">
<cfset local.beanList = ListAppend(local.beanList,local.beanName) />
</cfloop>

</cfif>

<cfset local.extendedMetaData = local.metaData />

<cfloop condition="StructKeyExists(local.extendedMetaData,'extends')">

<cfif StructKeyExists(local.extendedMetaData,"beans")>

<cfloop list="#local.extendedMetaData.beans#" index="local.beanName">

<cfif not listFindNoCase(local.beanList,local.beanName)>
<cfset local.beanList = ListAppend(local.beanList,local.beanName) />
</cfif>

</cfloop>

</cfif>

<cfset local.extendedMetaData = local.extendedMetaData.extends />

</cfloop>

<cfreturn local.beanList />

</cffunction>

<cffunction name="setBeanFactory" access="public" returntype="void">
<cfargument name="beanFactory" required="true" type="coldspring.beans.BeanFactory" />

<cfset variables.beanFactory = arguments.beanFactory />

</cffunction>

<cffunction name="getBeanFactory" access="private" returntype="any">

<cfreturn variables.beanFactory />

</cffunction>

<cffunction name="__setVariable" access="public" returntype="void">
<cfargument name="key" required="true" />
<cfargument name="value" required="true" />

<cfset variables[arguments.key] = arguments.value />

</cffunction>

<cffunction name="isCFC" access="private" returntype="boolean">
<cfargument name="object" required="true" />

<cfset var metaData = getMetaData(arguments.object) />

<cfreturn isObject(arguments.object) and structKeyExists(metaData,"type") and metaData.type eq "component" />

</cffunction>

</cfcomponent>


Long story short, it looks at all the beans defined in ColdSpring, checks their metadata for a "beans" attribute inside the cfcomponent tag, and automatically injects the requested beans into the component inside a variables.beans struct.

To get ColdSpring to process my beans, I define the factory post processor as such:


<bean id="beanInjector" class="test.BeansScopeFactoryPostProcessor" factory-post-processor="true" />


For those unaware of how factory post-processors work, ColdSpring will look for any beans where factory-post-processor="true" and automatically call postProcessBeanFactory() on those beans once the bean factory has been initialized.

To keep the code relatively small in this post, I removed any comments. Hopefully it's still somewhat straight-forward and easy to follow.

Friday, August 28, 2009

CF9 Front Controller Framework

I want to start writing a very simple front controller framework for CF9 that combines convention simplicity from ColdBox with configuration flexibility from Model-Glue, while borrowing a couple things from Rails/Grails/SpringMVC. Here's what a sample controller might look like:


component extends="Controller" {

public void function listUsers() {

var users = list("User");

render("users/list.cfm",{users=users});

}

public void function showUser() {

var user = get("User",params.userID);

render("users/show.cfm",{user=user});

}

public void function editUser() {

if(exists(flash,"user")) {
var user = flash.user;
}
else {
var user = get("User",params.userID);
}

render("users/edit.cfm",{user=user});

}

public void function saveUser() {

var user = get("User",params.userID);

populate(user,params);

var errors = validate(user);

if(!has(errors)) {

save(user);

flash.message = "User updated successfully";

redirect("showUser",{userID=user.getID()});

}
else {

flash.user = user;

flash.message = errors;

redirect("editUser",{userID=user.getID()});
}

}

public void function deleteUser() {

delete("User",params.userID);

flash.message = "User deleted successfully";

redirect("listUsers");

}

}

Saturday, August 8, 2009

How smart should an object be?

Since I'm relatively new to OOP, one thing I've been struggling with lately is how smart should I make my domain objects. Should an object know how to save itself? Take the following code for example:


user = new User();
user.setFirstName("Tony");
user.setLastName("Nelson");
user.save();


This type of code follows the Active Record design pattern, where domain objects contain your CRUD operations.

Hibernate, which acts as a Data Access Object, takes a slightly different approach. Rather than having the object save itself, Hibernate performs the CRUD.


user = entityNew("User");
user.setFirstName("Tony");
user.setLastName("Nelson");
entitySave(user);


Since Hibernate has become the ORM of choice in ColdFusion, I've decided that an object should not know how to save itself. Now with that in mind, should an object know how to populate itself? Consider the following code:


user = new User();
user.setFirstName(arguments.firstName);
user.setLastName(arguments.lastName);
user.setEmail(arguments.email);
user.setPassword(arguments.password);
user.setBirthDate(arguments.birthDate);
user.setGender(arguments.gender);
user.setHeight(arguments.height);
etc...


Pretty sure we've all seen code like this, where you're just taking all the arguments and calling their corresponding setters by adding "set" in from the argument name. Wouldn't it be a lot simple to just do:


user = entityNew("User");
user.populate(arguments);
entitySave(user);


But again, since a user shouldn't know how to save itself, it probably shouldn't know how to populate itself either, which gives us:


user = entityNew("User");
entityPopulate(user,arguments);
entitySave(user);


Mmmm... entityPopulate() would be a handy little tool. Now what about validation? Same theory applies...


user = entityNew("User");
entityPopulate(user,arguments);
errors = entityValidate(user);
if(ArrayLen(errors) == 0) {
entitySave(user);
}

Well it's short, although I'm not sure it's entirely clear what we're saving since it's so generic. But again, maybe that's a good thing. Ideally, you could get rid of all the "entity" stuff and make a really generic Service that looked like this:


user = new("User");
populate(user,arguments);
errors = validate(user);
if(ArrayLen(errors) == 0) {
save(user);
}


That almost looks as good as pseudo-code, with the only thing that's a little code-y being ArrayLen(errors). Speaking of which, there should be a generic length() function that can accept an array, query, struct, or string and return its length, regardless of data type. Man, that would be pretty sweet. Then the code would look even shorter.


user = new("User");
populate(user,arguments);
errors = validate(user);
if(length(errors) == 0) {
save(user);
}


Seems pretty clean. Just for fun, how would that look using smarter objects and a little method chaining?


user = new("User").populate(arguments);
errors = user.validate();
if(length(errors) == 0) {
user.save();
}


Not too shabby. And now you see my struggles.