<cfset user = new User() />
<cfset user.setFirstName("Tony") />
<cfset user.setLastName("Nelson") />
<cfoutput>
My name is #user.getFirstName()# #user.getLastName()#
</cfoutput>
I'd much rather prefer true implicit getters and setters a la Groovy, ActionScript, C#, etc...
<cfset user = new User() />
<cfset user.firstName = "Tony" />
<cfset user.lastName = "Nelson" />
<cfoutput>
My name is #user.firstName# #user.lastName#
</cfoutput>
After working with jQuery a little more, I really like the convention used on their event helpers, like
change() and change(fn). If you pass in an argument, it binds a new observer. If you don't pass in an argument, it triggers the event.I was able to apply similar logic to my entities in ColdFusion with the help of
onMissingMethod() inside a base class that my entities extend.
component {
public void function set(required string property, required any value) {
if (structKeyExists(this,"set#arguments.property#")) {
if (!structKeyExists(arguments,"value") || isNull(arguments.value) || (isSimpleValue(arguments.value) && arguments.value eq "")) {
evaluate("set#arguments.property#(javacast('NULL',''))");
}
else {
evaluate("set#arguments.property#(arguments.value)");
}
}
}
public any function get(required string property) {
if (structKeyExists(this,"get#arguments.property#")) {
local.value = evaluate("get#arguments.property#()");
}
if (!structKeyExists(local,"value")) {
local.value = "";
}
return local.value;
}
public any function onMissingMethod(required string missingMethodName, required struct missingMethodArguments) {
if (structIsEmpty(arguments.missingMethodArguments)) {
return get(arguments.missingMethodName);
}
set(arguments.missingMethodName,arguments.missingMethodArguments[1]);
return this;
}
}
Now if I pass in an argument, it sets the property. If I don't pass an in argument, it gets the property, leaving me with the following code:
<cfset user = new User() />
<cfset user.firstName("Tony") />
<cfset user.lastName("Nelson") />
<cfoutput>
My name is #user.firstName()# #user.lastName()#
</cfoutput>
And in case you didn't read the code, also included in the base class are generic
get() and set() methods that relay calls to the actual property getters and setters in order to maintain proper encapsulation.