Site icon Being Software Craftsman (DFTBA)

Extract Method

Extract method is the most frequently used refactoring technique. It reorganizes the code for better reuse and readability.

Ah! alright. Let’s proceed.

Use the extract method in following cases —

When your class contains a long method.

A long method does more than one thing and it is not considered as cohesive. The method more than 10 lines could be considered the as long method.

See this example of a long method, It is doing more than one thing.

Setting up GST rates, item/category mapping, accepting user inputs, calculation and so on. 

A long method is considered a code smell. 

Now see the refactored version of the above long method.

It is divided into small, cohesive, fine-grained methods which are doing one and only one thing.


When you favor a comment to express the intent of the code.

Before

 ...
// Parse input and convert it into Document
var xDocument = XDocument.Parse(input);
var document = new Document
{
   Title = xDocument.Root.Element("title").Value,
   Text = xDocument.Root.Element("text").Value
};
...

Here let’s get rid of comment [Parse input and convert it into Document]. 

After

...
var doc = ParseInput(input);
var serializedDoc = JsonConvert.SerializeObject(doc);
...
private Document ParseInput(string input)
{
    var xDocument = XDocument.Parse(input);
    var document = new Document
    {
        Title = xDocument.Root.Element("title").Value,
        Text = xDocument.Root.Element("text").Value
    };
    return document;
}

When the extract method helps you to improve readability.

Do you know that people extract method for a single line too? Because it adds to the readability of the code. Sometimes a statement may be difficult to interpret. In that case, you could use the extract method to convey intent instead of taking the aid of comment.


When there is a code duplication or copy-paste.

Consider below example, it is formatting date and code is duplicated. Perhaps, lines are copied and pasted.

Before

    var formattedStartDate = startDate.ToString("dd MMMM yyyy");
    var formattedEndDate   = endDate.ToString("dd MMMM yyyy");

As soon as you see copy and paste of lines of code then go for an extract method refactoring even if it is a small portion of code.

After

    var formattedStartDate = FormatDate(startDate);
    var formattedEndDate  = FormatDate(endDate);

public string FormatDate(DateTime date)
{
   return date.ToString("dd MMMM yyyy");
}

The advantage


Points to Ponder —


Extract method only if you can give an intuitive name.

Exit mobile version