Why variables that we don't modify should be final?

John Carter <[email protected]> Fri, 28 May 2010 14:32:46 +1200
Newsgroups gmane.comp.programming.refactoring
Message-ID <[email protected]>
On Wed, May 26, 2010 at 7:56 AM, Alberto Ivo <[email protected]> wrote:
> I just passed PMD in my Java code.. and a lot of variables the PMD says that
> should be final.. just because I do not modify.
> I know that, like this, it's safer because I'm sure that it wil be not
> modified ever...
> But, besides that, is there another advantage? like performance or anything
> else?

As my code evolves and matures I find I'm using the ruby .freeze
method more and more.

Why?

Well, I started off just hunting threading bugs with it... but now I
have stopped doing threading (multi-process only for me thanks, much
simpler / more robust).

Yet I'm still putting in more ".freeze" calls.

Somehow my code is cleaner and better thought out if I can put a
"freeze" at the end of the constructor, or shortly thereafter.

Object instance variables a bit like globals in the sense they can
propagate causality though your systems along paths orthogonal to the
flow of control.

ie. When we look at a line of code, our instinct is that it is
affected only by the lines above it in the function and the function
parameters, and it only affects the lines below and the output
parameters.

But if we have references to mutable objects all over the place, then
anything with a reference  to an object that we also have on the line
of code we're considering, can _also_ affect the behaviour of that
line.

Sometimes I feel we should only ever have one reference to one object
instance, which would mimic the way we live our lives.

The ball is in my hand.
I give the ball to you.
You have the ball in your hand.
The ball is now no longer in my hand.

However that tends to produce copying of data. The alternative is to
only work with references to immutable objects.

-- 
John Carter                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : [email protected]
New Zealand


------------------------------------

Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/refactoring/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/refactoring/join
    (Yahoo! ID required)

<*> To change settings via email:
    [email protected] 
    [email protected]

<*> To unsubscribe from this group, send an email to:
    [email protected]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/