Software Design/Parameterize Function or Class

Parameterize Function (also Parameterize Class) is a refactoring primarily aiming at removing logic duplication in the code as per DRY principle. This corresponds to Parameterize Function refactoring described in Refactoring.

Example
See an example of this refactoring on Parameterize Function catalog entry.

Parameterize Class is a generalization of Parameterize Function: an additional parameter is stored in a field of the class and is used in one or several functions belonging to the class.

Why
Parameterizing functions and classes makes them more reusable and thus allows to eliminate repetition in the existing code.

Why not
It's easier to make a mistake by passing a wrong argument to a parameterized function than to call a wrong function when there several separate ones with different names.

The meaning of the calls to parameterized functions may be less apparent to readers, especially when the new parameter is. Applying practice Use a enum with two values instead of boolean (and, more generally, Use named constants instead of magic values and Use class instead of primitive type) may alleviate this problem. For example, compare the following versions of the same code:

Mitigation of the drawbacks: keep the delegation layer
A solution for both drawbacks of Parameterize Function is keeping the old functions and make them delegate to the new parameterized functions, but that contributes to the size of the code and makes it more navigation-heavy in turn. The code with more redirection function calls may also be less efficient, especially in interpreted environments.

Effects on efficiency
Parameterize Function and Parameterize Class might affect the runtime efficiency of the software in a number of contradictory ways.

Positive:
 * Parameterizing functions and classes leads to a reduction in the total amount of the code, hence the instruction cache may be used more effectively.

Negative:
 * Parameterized code may not be compiled as efficiently as specialized code. For example, immediate values can't be used in parameterized code, or integral division can't be replaced with a bit shift when the divisor (which is a power of two) is turned into a parameter.
 * Parameterizing alternative logic leads to additional branches which might be predicted poorly under some circumstances.
 * Parameterizing a class with a field means that the field's value should be read from memory when it could have resided a register otherwise.

Related refactorings and practices

 * Don't repeat logic in several places