1.9. Generalizing a Function to Enhance Reusability
Problem
You want to perform slight variations of an action without having to duplicate multiple lines of code to accommodate the minor differences.
Solution
Add parameters to your function to make it flexible enough to perform slightly different actions when it is invoked rather than performing exactly the same action or producing the same result each time.
Define the parameters that account for the variability in what you want the function to do:
function myParamsFunction (param1, param2, param3) {
trace("The average is " + (param1 + param2 + param3)/3);
}If you don’t know the exact number of parameters the
function will receive, use the built-in arguments
array to handle a variable number of parameters.
Discussion
A function that doesn’t accept parameters generally produces the same result each time it is invoked. But you often need to perform almost exactly the same actions as an existing function, but with minor variations. Duplicating the entire function and then making minor changes to the second version is a bad idea in most cases. Usually, it makes your code harder to maintain and understand. More importantly, you’ll usually find that you need not only two variations but many variations of the function. It can be a nightmare to maintain five or six variations of what should ideally be wrapped into a single function. The trick is to create a single function that can accept different values to operate on.
For example, if you have ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access