Search code examples
frameworkscoldfusionrailocfmlcode-structure

How to reference global function library in CFML?


Dependency injection allows you to avoid referencing objects and scopes that are external to the object directly. You instead reference the injected dependency.

I want to know the best practice in the case of a global function library. I store my functions in the server scope currently. I want my project to be open source soon and easy for other developers to understand. I want the application to be easier to write unit tests for and be more loosely coupled.

Should I inject the server scope into EVERY object that uses a global function?

Or should I make an exception to the rule and put "server.functions.myFunction()" scope directly in the component when referencing these functions?

Here are code examples:

Method 1:

<cfcomponent>
    <cffunction name="init">
        <cfscript>
           server.functions.myFunction();
        </cfscript>
    </cffunction>
</cfcomponent>

Method 2:

<cfcomponent>
    <cffunction name="init">
        <cfargument name="serverScope" type="struct" required="yes">
        <cfscript>
            variables.serverScope=arguments.serverScope;
            variables.serverScope.functions.myFunction();
        </cfscript>
    </cffunction>
</cfcomponent>

Solution

  • I never got around to formalising my answer to this. based on what you say in the comments, I would do this:

    • decompose your global library into more purpose-specific components, which are then treated as objects (stateful), or - for all intents and purposes static libraries (not stateful).
    • yes, use dependency injection to inject just the ones you need for a given situation.

    I would not break encapsulation just for the sake of expedience.