Use case for static vs. instance methods

When LCF made static methods available I didn’t initially use them that much. Lately I find that I’m using them more and more. I like the handiness of having a method available to me in a cfc without the overhead of having to create an instance just to access one or two methods from within it. As an example I have a formvalidation.cfc. One of the methods it offers is the removeQuotes method. The init method requires a form structure to be sent. There’s a whole lot of stuff the formvalidation.cfc looks for but if I just wanted to use the removeQuotes method I would have to submit a bogus structure with the field values I wanted to check. Now I can just call formvalidation::removeQuotes( fldValue ). I find that I’m using this a lot.

In structuring things this way I stumbled across something interesting, it was new to me anyway. You can have a method name in all access modes. In the formvalidation.cfc I have a public removeQuotes method and a static removeQuotes method. I thru in a private removeQuotes method to see if that worked and it did. I got rid of it after the test.

I’m mostly curious what the pro’s and con’s might be of using static methods as opposed to instance methods.

1 Like

I’ve become quite a fan of static variables and methods too. It’s allowed me to move away from the “Service/DAO/Model/View/Controller” pattern people might be familiar with, and just focus on MVC.

In other words, I’ve moved code that was in Services and DAOs - e.g. returning sets of objects - into the components in the Model as static methods, so that everything domain-related is together.

This feel more cohesive to me, and having everything in one place can also make testing easier.

One downside I’ve come up against though, is that dependency injection (DI) isn’t really possible, as there aren’t any instances into which dependencies can be injected. I’ve explored using the static “scope” for this but found it unreliable.

It’s a bit quirky in some respects as you’ve found, but on the whole I really like having “static” as an option when building components.

1 Like