Monday, 13 April 2015

Lucee 5 beta: final keyword (redux)

G'day:
Community stalwart and "OK bloke even if he is Australian" Andy Myers made an observation on Twitter this morning:

This is a good question, and one I did not think to check.

My initial reaction was "probably not", given "Abstract/Final components/functions" doesn't mention them. But I figured the docs for the Lucee 5 beta are so uselessminimal that perhaps they just hadn't got around to documenting it. So I tried.

// FinalVariable.cfc
component {

    final public publicVar = "set in CFC"

}

// finalVariable.cfm
finalVariable = new FinalVariable()

finalVariable.publicVar = "new value"

echo(finalVariable.publicVar)

This should set publicVar to be "read only" for all intents and purposes. But when running the code:

new value

Odd. If final wasn't supported in that context, I'd expect a compile error. However it doesn't seem to work.

final arguments are a variation of this. An argument is just a variable, so it should be final-able too:


// FinalArguments.cfc
component {

    function f(final string x){
        x = "something else"
        echo(x)
    }

}

finalArguments = new FinalArguments()
finalArguments.f("value passed in")

Here the code in the function should not be able to update the value of x, as it's final. But:


That's not the correct error. Basically the parser is getting confused and thinks that final is type type here.

Actually having final on arguments could be quite handy. In situations wherein a complex object is passed as an argument, this will make sure the method code doesn't inadvertently update said argument, which would bleed out into the calling code. I was reading about someone being caught out by this (via someone else's code) just the other day on IRC (Ross: I'm looking at you ;-).

I think perhaps if Lucee are going to implement final, then they need to do the complete job, don't they? (Ticket raised: 286).

--
Adam