Coding conventions for writing cfc's in CF9?
-
20-09-2019 - |
Question
With the new ways of writing CFC in CF9, what are some of the coding convention new to CF9?
Here are some I can think of...
- always use LOCAL scope
- always include
init()
method that returns itself, sinceNew
will call init() if found. - do not put required arguments in
init()
if it is an ORM entity, otherwise expect Exceptions... - always use
THIS.setXXX
in where XXX is property name inside init(), so that it will call the implicit setters or custom setter if available. - abandon the pre-CF8 INSTANCE scope convention, see: http://henrylearnstorock.blogspot.com/2009/08/should-we-abandon-instance-scope-in-cf9.html
- no output=false for component and functions in script style CFC, see: http://www.coldfusionjedi.com/index.cfm/2009/8/26/Ask-a-Jedi-Impact-of-whitespace-and-script-based-CFCs
- use the cleaner and more efficient
isNull(arguments.optionalArg)
instead ofisDefined()
Solution
do we still need to set attribute output=false for component and functions in script style CFC?
I wouldn't think so. <cfscript>
by its nature suppresses any whitespace and needs writeOutput()
in order to have any output at all.
OTHER TIPS
Your init() method doesn't have to return the "this" scope if you are calling it using the "new my.cfc()" syntax. True story.
If you are inside a cfc and want to set a property, dont use this.setFoo(), just go setFoo(). Same goes for getFoo(). The this.xxx() is like going out the front door only to come back in. Also, your access=private custom getters and setters wont work as the functions wont be in the this scope.
"var foo" vs "local.foo" - personally, I prefer var'd variables as there is a) less code to type, and b) less code to read.
// there isnt a huge difference here
var today = now();
var tomorrow = dateAdd( 'd', 1, today );
local.today = now();
local.tomorrow = dateAdd( 'd', 1, local.today );
// but when you start getting more complex examples, it quickly blows out
var out = method( var1, var2, var3, var4, var5 );
local.out = method( local.var1, local.var2, local.var3, local.var4, local.var5 );
Use javadocs style comments. Documentation is your friend.
/**
* @hint This is a hint for the whole function
* @arg1 This is an argument hint
* @arg2 This is another argument hint
**/
public void function myFunction( string arg1 = 'default', boolean arg2 ) {
return true;
}
all functions that alter data should return some value even if it is a boolean that is currently always true. Functions have a way of eventually needing to return false