Ask a Jedi: Converting a set of static method calls to dynamic calls

Hatem asks:

I have the following set of calls, currently hard coded: <cfif fileexists("#curpath##CaseStudy.getIMG1()#.jpg")>
<cffile action="delete" file="#curpath##CaseStudy.getIMG1()#.jpg">
<cffile action="delete" file="#curpath#thumbs\#CaseStudy.getIMG1()#.jpg">
<cffile action="delete" file="#curpath#small\#CaseStudy.getIMG1()#.jpg">
<cffile action="delete" file="#curpath#large\#CaseStudy.getIMG1()#.jpg">
</cfif>
As you can see, it calls getImg1 for each. I need to do this for images 1-4. How can I make it dynamic?

As with most things, there are multiple solutions. The most direct answer is to simply switch to cfinvoke. Assume you are in a loop and N is your loop counter, this will get the value you want:

<cfinvoke component="#casestudy#" method="getIMG#n#" returnVariable="image">

You would then use the variable image in your CFIF and your file deletes.

Another route would be to replace those 4 getImgN methods with one method that simply takes an index: getImg(n). I’d be willing to bet your 4 methods are extremely similar. Your CFC would be a bit cleaner if you switched up the API a bit. (This is my assumption however not having seen your entire CFC.)

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments