I wrote the following function:

  <cffunction name="check_session_valid" returntype="boolean">
    <cfif NOT StructKeyExists(session,"username") OR (len(session.username) EQ 0)>
     <script>location.href = 'logout.cfm'</script>
     <cfabort>
    </cfif>
    <cfset session.myApp_start = now()>  
    <cfreturn true>
  </cffunction>

In my .cfm page, I can call that function using

<cfset session_valid = application.lib.check_session_valid()>

OR

#application.lib.check_session_valid()#

What's the difference? Best practice?

2

There are 2 best solutions below

0
On BEST ANSWER

Since you asked about best practice, which is a matter of opinion, I think you can improve your function by having it returning either true or false depending on whether or not session.username exists and has a length greater than 0. Then you can use it like this:

<cfif application.lib.check_session_valid()>
code for this condition
<cfelse>
<cflocation href = "logout.cfm">  
<!--- note that cfabort is not necessary --->
<cfif>

Regarding your specific question, I think the extra variable, session_valid, is a waste of typing. However, that is simply my opinion.

Not related to your question, I found it curious that you would direct users to a page called logout.cfm. Often users are directed to a page that allows them to log in.

0
On

To be honest, both are valid and both would be considered best practice depending on what you are trying to do.

My rule of thumb is if I will need to use the result of a function call more than once, I will set it to a variable

myResult = application.lib.check_session_valid();

If I will only need to use the variable once I would do what Dan mentioned

if( application.lib.check_session_valid() ){
    // Do stuff
}

The difference between the examples you showed are

<cfset session_valid = application.lib.check_session_valid()>

This will set the variable named session_valid to whatever is returned from the call to check_session_valid().

#application.lib.check_session_valid()#

This will, in .cfm pages, simply render the value returned from the call to check_session_valid() assuming it is inside of a <cfoutput> tag. There are other places this would also render the value, such as inside a <cfsavecontent>.