Using local variables passed as parameters or using instance variables (advice please)

Is there a rule of thumb or some such advice that would help me decide when to pass local variables as parameters to a subroutine/submacro or just to use an instance variable in both the calling macro and sub macro. In my head I keep flip flopping [I just spent some quality time changing all instances of "local__Year" to "instance__Year" and back again!]. Thanks for any advice

Dave

Absent a response from those more experienced/knowledgable than me, here's my take...

Q1 -- How many values do I want to return?

A subroutine/submacro can only return a single value (or nothing, obviously). You can get round this by using a data structure that can contain multiple values, eg an array or a dictionary, but that is extra work for you. It's also extra documentation -- choosing good variable names can make a macro practically self-documenting but returning a multi-value data structure adds a level of obfuscation that really should be explained (especially if you've a memory as bad as mine!).

Q2 -- Is this subroutine/submacro something I'll want to use elsewhere?

It's a lot easier to use a "black box", where all you need to know are the input parameters and the returned data structure, in other macros than it is to open up the sub and check all your instance variable names against it -- you're not only checking for matches on the variables you want to share, but also clashes with variables you don't. That might be trivial in short macros, but in longer ones with many variables -- and especially if there are multiple subs -- that could be a real pain.

Q3 -- Just for me, or someone else?

We intuitively understand the macros we've written (but see above about remembering them a year later!) and can get away with "sloppy" practices because of that. But if the macros are to be used by others we should build in more resilience and ease of maintenance -- and that generally means parameter passing (with well-documented return data structures where necessary) rather than shared variables.

Those are some of the considerations I can think of -- perhaps others will chip in with more. But if you want a rule of thumb, it's the same old, boring, thing:

Always scope your variables as tightly as you can.

And that means using parameters and returns rather than shared variables wherever practical.

Of course, "wherever practical" is a biggie :slight_smile: I've yet to get my head round KM's Dictionaries, so for a throwaway multi-value-returning sub I'd use shared instance variables. For something more permanent I'd have to knuckle down and learn how to use Dictionaries!

Interested to see how others respond...

2 Likes

Thanks Nige, this is very helpful. I would bet that my memory is no better than yours! I'll stick to the narrow as possible scope rule.

Dave