Combine multiple methods that perform similar actions that are different only in their internal values, by using a parameter that will pass the necessary special value.
The Parameterize Method is used to extract a portion of a method's logic and make it into a new method that takes parameters, in order to improve the readability and maintainability of the codebase. This can be useful when a method has a lot of conditional logic that makes it difficult to understand or maintain.
For example, consider the following method, which has a lot of conditional logic:
order = retrieveOrderFromDb(order.
}
handleNormalOrder(order);
}
handleExpressOrder(order);
}
handleCustomOrder(order);
}
}
}
To make the method more readable and maintainable, we can extract the portion of logic that handles different order types into a new method called handleOrder that takes a parameter called orderHandler:
order = retrieveOrderFromDb(order.
}
saveOrderToDb(order);
}
handleNormalOrder(order);
}
handleExpressOrder(order);
}
handleCustomOrder(order);
}
}
}
In this example, we have extracted the portion of logic that handles different order types into a new method called handleOrder. This method takes two parameters, order and orderType, and uses the orderType to determine which function to call to handle the order. This improves the readability of the processOrder method by reducing the amount of conditional logic it contains and making it clear that it performs multiple actions.
Another benefit is that it allows for reusing the extracted method in other parts of the codebase. For example, in the above example, if we have another method that also needs to handle different order types, we can simply call the handleOrder method and pass in the appropriate order and order type, instead of duplicating the conditional logic in the other method.