This week I was walking through some code in a code review and the question came up, why do I use the “extra” instance structure within my components. For example, in my init() function for every component, I have a line of code that looks like this:
<cfset variables.instance = structNew() />
Then, when I setup a new attribute for the component, I would store it in a variable like this:
<cfset variables.instance.foo = "bar" />
So, beyond personal habit, why do I do this? There are several reasons, some of which may be more valid in different contexts.
- It tends to make variables more obvious in the code so that you know what is a local variable for a function versus a global attribute for the component.
- You can dump this structure and see a quick snap shot of the ‘state’ of the component. While you can dump the variables scope, you will not only get the variables but also lots of function meta data which is not always desirable.
- For the OO purists out there, having all of the attributes contained within a structure like this makes it very simple to write the equivalent of a “copy” constructor.
- For components that might be extended in the future by yourself or another developer, you run the risk of variable collisions – that is variables with the same name in the base component as well as the extended component. By using a specially named structure for your instance variables, this can be prevented.
I don’t know if this was reason enough to convince my colleague, but it is reason enough for me to keep doing this in my components. Is this a wide spread best practice or am I the only one?