Contact Me

Extract Method

Move a section of code from a method into a new method

 Assuming you have have a code fragment that can be grouped together, move this code to a separate new method (or function) and replace the old code with a call to the method, in order to improve the readability and maintainability of the codebase. This can be useful when a method has grown too large or has too many responsibilities, making it difficult to understand or maintain.


 For example, consider the following method, which has several lines of code that perform different actions:

class Order {

processOrder(orderId) {

// Retrieve order from database

const order = retrieveOrderFromDb(orderId);

// Validate order

if (!validateOrder(order)) {

  return;

}

// Calculate total

const total = calculateTotal(order);

// Send email to customer

sendEmail(order.customerEmail, 'Order Confirmation', `Your total is ${total}.`);

// Save order to database

saveOrderToDb(order);

// Print receipt

printReceipt(order);

}

 To improve the readability and maintainability of this method, we can extract the section of code that sends an email to the customer into a new method called sendOrderConfirmationEmail:

class Order {

processOrder(orderId) {

// Retrieve order from database

const order = retrieveOrderFromDb(orderId);

// Validate order

if (!validateOrder(order)) {

  return;

}

// Calculate total

const total = calculateTotal(order);

this.sendOrderConfirmationEmail(order, total);

// Save order to database

saveOrderToDb(order);

// Print receipt

printReceipt(order);

sendOrderConfirmationEmail(order, total) {

  sendEmail(order.customerEmail, 'Order Confirmation', `Your total is ${total}.`);

}

}

 In this example, we have extracted the section of code that sends an email to the customer into a new method called sendOrderConfirmationEmail. This improves the readability of the processOrder method by reducing the amount of code it contains and making it clear that it performs multiple actions, and also makes the sendOrderConfirmationEmail method self-explanatory, it is clear that it's sending an order confirmation email, which makes it easy to understand and maintain.

 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 send an order confirmation email, we can simply reuse the sendOrderConfirmationEmail method, instead of duplicating the code in the other method.