Contact Me

Parameterize Method

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:

class Order {

processOrder(order) {

  // Retrieve order from database

  order = retrieveOrderFromDb(order.id);

  // Validate order

  if (!validateOrder(order)) {

   return;

  }

  // Handle different order types

  if (order.type === 'normal') {

   handleNormalOrder(order);

  } else if (order.type === 'express') {

   handleExpressOrder(order);

  } else if (order.type === 'custom') {

   handleCustomOrder(order);

  }

// Save order to database

saveOrderToDb(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:

class Order {

processOrder(order) {

  // Retrieve order from database

  order = retrieveOrderFromDb(order.id);

  // Validate order

  if (!validateOrder(order)) {

   return;

  }

  // Handle order using the given order handler

  this.handleOrder(order, order.type);

  // Save order to database

  saveOrderToDb(order);

}

handleOrder(order, orderType) {

  if (orderType === 'normal') {

   handleNormalOrder(order);

  } else if (orderType === 'express') {

   handleExpressOrder(order);

  } else if (orderType === 'custom') {

   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.