ConstructiCat Logo
CodeBust.
Browse section ▾

Add Parameter.

Problem

A method doesn’t have enough data to perform certain actions.

Solution

Create a new parameter to pass the necessary data.

##Example

Before
void charge() {
  bank.transfer(amount);
}
After
void charge(Date asOf) {
  bank.transfer(amount, asOf);
}

##Why Refactor

You need to make changes to a method and these changes require adding information or data that was previously not available to the method.

The alternative is to add a new private field that holds the data the method needs. A parameter is preferable when the data is needed only occasionally or changes frequently, so there’s no point in keeping it in the object all the time. Otherwise, add a private field and fill it with the necessary data before calling the method.

##Benefits

  • The method receives the data it needs explicitly from the caller: the dependency is visible in its signature instead of being hidden in the object’s state.

  • Occasional or frequently changing data doesn’t have to be stored in the object all the time, so the class doesn’t accumulate fields that are needed only for a single call.

##How to Refactor

  1. See whether the method is defined in a superclass or subclass. If the method is present in them, you will need to repeat all the steps in these classes as well.

  2. The following step is critical for keeping your program functional during the refactoring process. Create a new method by copying the old one and add the necessary parameter to it. Replace the code for the old method with a call to the new method. You can plug in any value to the new parameter (such as null for objects or a zero for numbers).

  3. Find all references to the old method and replace them with references to the new method.

  4. Delete the old method. Deletion isn’t possible if the old method is part of the public interface. If that’s the case, mark the old method as deprecated.