1

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?

Millhorn
  • 2,953
  • 7
  • 39
  • 77
  • 1
    The former is returning a value to another variable, whereas the latter is just outputting the value. Both could be best practice, depending on what you are trying to achieve. I would say that you probably want to return the value into a new variable. So, the first approach is better. – Charles Robertson Jul 27 '20 at 19:55

2 Answers2

2

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.

Dan Bracuk
  • 20,699
  • 4
  • 26
  • 43
2

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>.

Scott Stroz
  • 7,510
  • 2
  • 21
  • 25