Hi Tomek,

On Fri, 2015-08-28 at 08:30 +0000, Tomek Rekawek wrote:
> Hello,
> 
> I’m trying to avoid re-assigning local variables whenever it’s
> possible. For me it makes the code easier to reason about - I know
> that the variable “state" created at the beginning of the method is
> the same one I can access at the end. If I need the child state at
> some point I can create the new variable. The same applies for the
> parameters (I think it’s some kind of code smell to reassign
> parameter anyway).


I partly agree with your statement about ease of reasoning, but I would
not assign that much weight to the gains, compared to the effort.

Note that final variables / parameters guarantee that the variable's
_identity_ does not change, not the variable's _state_. The concepts
overlap for primitives and immutable objects but not for mutable
objects. In fact, I'd argue that a larger class of errors stems from
changing the state received parameters, like collections, rather than
changing the identity of a local parameter.

As for changing parameters, I think it boils down to code style
preference. I for one prefer to change local parameters for instance
when 'cleaning' passed in arguments. A couple of straw-man examples
follow:

    public static boolean hasEmpty(Collection<?> coll) {
        if ( coll == null )
            coll = Collections.emptyList();
        
        return coll.contains("");
    }

    public static boolean isParent(String maybeParent, String
maybeChild) {
        if ( maybeParent == null )
            maybeParent = "/";
        else if ( maybeParent.endsWith("/") && !maybeParent.isEmpty() )
            maybeParent = maybeParent.substring(0, maybeParent.length()
- 1);
        
        // TODO actual implementation
    }

I am sure that there are elegant ways of doing while not changing the
parameter's identity, but for me the above idiom is the right balance
between conciseness and understandability.

Cheers,

Robert

Reply via email to