Search This Blog

Friday, August 29, 2014

ColdFusion: Using Implicit getters and setters

Usually, I wrote my own getters and setters. It's kind of habit since the introduction of <cfcomponent>...</cfcomponent>. However, it took time and made the code longer. So, I decided to try implicit getters and setters by setting accessors="true" and using <cfproperty />. There are two important things that I found:

  • We can override implicit getters and setters with our own. However, the implementation has to be both (getter and setter). It cannot be only either getter or setter only.
  • The getter and setter attribute in <cfproperty /> is to limit access if they can be called from inside only. Setting getter/setter to false mean the method cannot be called from outside the component. It does not mean to generate or not to generate getter/setter for that property.


<!--- Enable implicit getters and setters --->
<cfcomponent output="false" accessors="true">

  <!--- Override its getter and setter. See getDelay() and setDelay(). --->
  <cfproperty name="delay" type="numeric" />
  <!--- Use its implicit getter and setter  --->
  <cfproperty name="text" type="string" />
  <cffunction name="init" output="false">
    <!--- Set initial values --->
    <cfset THIS.setDelay(0) />
    <cfset THIS.setText("Hi again.") />

    <cfreturn THIS />

  <cffunction name="echo" output="false" hint="Echoes back whatever received.">
    <cfargument name="data" required="true" />

    <cfset sleep(THIS.getDelay()) />

      & " This process was delayed for " & (THIS.getDelay() / 1000) & " seconds." 
      & " Another property with implicit getter/setter: " & THIS.getText() />

  <!--- While accessor="true" creates implicit getters/setters, we can override them.
    However, the implementation has to be one set (getter and setter).
    It cannot be only getter or setter. --->
  <cffunction name="getDelay" output="false" returntype="numeric">
    <cfreturn THIS.delay />
  <cffunction name="setDelay" output="false" returntype="void" hint="Sets delay in seconds.">
    <cfargument name="delay" type="numeric" required="true" />
    <cfset THIS.delay = ARGUMENTS.delay * 1000 />


Reference: Implicit Get and Set Functions

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.