Thursday, August 21, 2008

The invoke once principle

I often come across code in a method or function definition that will use another function or method invocation to return some value. This invocation is then used more than once throughout the body of code in question. This is done because the value returned by the method is used in this new context.

The problem is, this probably isn't very efficient. Function or methods that return a value should only be invoked once in a particular context. This is usually done at or near the beginning of the code we are writing. We invoke the function or method and assign the return value to a meaningful variable name which is then used throughout the rest of the method we are developing.

This is useful when the code we are developing has no effect on the state of the value returned by the function or method invocation. There are same scenarios when invocation is necessary every time the value is needed. This is seldom the case but it does happen.

The general idea behind this principle is to avoid method invocation wherever possible. If we only need to initialize a value once in our code and there is no chance of our code disrupting the value's state, than this is the way to go.