Yesterday I discussed an approach to making scripts more readable by eliminating unnecessary nested If statements. Today I want to look at something else entirely. Do you see anything wrong with this code?
Well, perhaps “wrong” isn’t the best term to use — how about “less-than-optimal”?
What stands out for me is the repeated invocation of two Get functions. Why ask the FileMaker calculation engine the same questions over and over again? By asking the questions just once, and inserting the answers into variables, the calculation engine will do less work and your script will run faster.
Of course for a short script, you won’t notice the difference, but you can save a noticeable amount of time (not to mention “wear and tear” on the calc engine) by not asking the same questions over and over again.
So far we’ve been looking at Get functions, but any question that gets asked multiple times is a good candidate for this treatment. For example, if you have an unstored calculated balance_due field, and your script refers to it more than once, throw it into a $balanceDue variable, and refer to the variable instead.
Here’s a more complex example: each named variable ensures the calculation engine won’t need to answer the same question more than once.
There’s always a tradeoff and a judgement call to make when balancing readability against efficiency, but in this case I think the named variables, if anything, make the code easier to read.
[Update 4/21/11: I realize I told a minor fib above when I said “each named variable…”; the $dtn365 variable is only used once after it’s been declared, but in terms of readability, I think using a named variable was a good choice.]