Skip to content


Extract Method: an in-depth motivation

Extract method is one of the easiest refactorings within the GoF patterns. Developers tend to look at large methods and use Extract Method only then. Well, there is a lot more to this simple refactoring then just splitting up large methods. Let’s digg in!

Separation of responsibility

Methods should have 1 concern (responsibility, purpose, … ). Let’s look into the matter with an example. Consider following code:

public void createCustomer(Map requestParameters) {
	Customer customer = new Customer();
	customer.setName = requestParameters.get("name");
	//Check if a customer was already registered with that name
	if (customerService.getCustomerByName(customer.getName()) != null) {
		System.out.println("Customer already exists");
		return;
	}
	customer.setShoppingCart(new ShoppingCart());
	customerService.save(customer);
}

The above code is something I scraped together, it’s not real code. But it illustrates something I see regular. The method name is save. So I expect that the code only does some saving. Instead it creates a new customer, checks if it’s valid (no double names) and then saves it. So the method is actually performing 3 things.

This method should be refactored into 4 methods. The first method, which I would call bindValidateAndSave is the algorithm method. It tells what to do, not how it’s done. Its responsibility is to provide the algorithm. The 3 other methods would be called bindCustomer (bind and add new shoppingCart), validateCustomer and saveCustomer.

With the last method (saveCustomer) I get the WHY? question a lot, since the extracted method is actually only 1 line of code long. Although it might not improve readability for programmers, it’s a paradigm shift in how the method is addressed. In our example, if the saveNewCustomer calls customerService.save() it’s responsible that the save method is actually called right. Instead if we let it delegate to a newly extracted method (saveCustomer) it isn’t responsible for the explicit saving. Instead now it defines the algorithm. In this case bind, validate, save. The implementation is just the save method.

Working in this fashion takes some getting used to, but in the end I truly believe this produces stabler and more maintainable code.

Self-describing methods

The second insight I have about the Extract Method refactoring, is removing comments from my code. A lot of fresh developers believe writing comments is the key to great software. As Martin Fowler stated in his excellent book Refactoring, comments are really a bad smell that something is wrong. Either your code is too complex or too long winded. Extracting code just to give it a nice method name helps readability. Take for instance the following example:

public void eat(Food food)  {

	//Other eat actions...
	//Need to blow on the food cause it might be hot
	while (food.getTemp() > 50) {
		mouth.blow();
	}
}

Although the example is completely stupid, it would be slightly less stupid if written like this:

public void eat(Food food)  {

	//Other eat actions...

	blowWhileHot(food);
	mouth.eat(food);
}

private void blowWhileHot(Food food) {
	while (food.getTemp() > 50) {
		mouth.blow();
	}
}

Et voila, our code just became A LOT more readable.

I agree, both examples are intertwined in most cases, but there is a difference between the two.

Both insights are developed by reading Refactoring, a book that definitely made it into my top 10 list!

Got any comments, let’s hear them!

Andries

Posted in Java, refactoring.


6 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. sp says

    Although you do show the benefits of the paradigm pretty clearly, I think it’s still too hard for most developers (including myself) to adopt this style of coding.

    Also, all links in your article lead to “/”, showing site address in the title instead.

  2. Andries Inzé says

    Thx for the input. I changed to replaced the links, they are now working, although I have no idea what I did wrong the first time.

    Why is this style of programming too hard?

  3. sp says

    Sorry for long answer, I thought I’d be emailed on new comments here.

    I think “hard” isn’t exactly the right word. What I meant is just that one always has to convince himself that it’s actually worth trying something new especially when the old approach works more or less. Unfortunately, people often prefer to stick to the old methods (again, I’m not exception).

    Although I must say I’ve tried this on the little js-driven web-app and it works great for me so far :) .

  4. Idetrorce says

    very interesting, but I don’t agree with you
    Idetrorce

  5. Andries Inzé says

    Motivate yourself?

Continuing the Discussion

  1. Stress Management » Extract Method: an in-depth motivation linked to this post on October 18, 2007

    [...] Find the link to this great post here. [...]



Some HTML is OK

or, reply to this post via trackback.