Static for Ben

I’m taking this out of the other thread, as it’s off topic.

Sometimes a method is unrelated to an object, it’s related to the class. A fairly common situation is to have a static factory method that creates an instance of an object via a non-standard mechanism, eg:

// Person.cfc
component {
    function init(firstName, lastName) {
        variables.firstName = arguments.firstName
        variables.lastName = arguments.lastName
    }

	function getFullName() {
		return "#firstName# #lastName#"
	}

    static function createFromArray(nameParts) {
        return new Person(nameParts[1], nameParts[2])
    }
}
<!--- test.cfm --->
<cfscript>
ben = Person::createFromArray(["Ben", "Nadel"])

writeOutput(ben.getFullName())
</cfscript>
// output
Ben Nadel

One doesn’t want to mess with the constructor: it’s fine. One also doesn’t want to rejig the code so an “empty” Person can be created and then somehow poke the name parts into it. One wants a function that facilitates creating the object via a different mechanism.

I’ve kept the mechanism very simple and generic here, because if the inputs drifted too far into some bespoke approach, the factory method would probably cease belonging to Person, and best be put somewhere else (or in a proper PersonFactory class). I think an array is general enough for this to be legit. One could perhaps implement it as fromArray instead. Still a class method, not an object one though.

It simply doesn’t make sense to implement createFromArray / fromArray as an object method. There is no object.

This is actually pretty neat. Most of my components don’t have much need for dynamic instantiation since they are just “workflow” components for marshaling data around the system. That said, this seems like it would be great for “library” components that can have swapped behaviors.

For example, imagine a StatsD component that can be created with different types of “transport” behaviors - UDP, HTTP, “no-op”. Seems like having a series of “factory methods” that can do all the construction for you would be cool.

1 Like

Absolutely. Take java.lang.Math for example: it doesn’t represent the behaviour of an object, it is just a library of maths functions. So they’re all static.

If your method is connected to the class conceptually, but doesn’t act on the state of an object: it might be better to be static.