Mark Needham

Thoughts on Software Development

Coding: Why do we extract method?

with 9 comments

Ever since I've read Uncle Bob's Clean Code book my approach to coding has been all about the 'extract method' refactoring – I pretty much look to extract method as much as I can until I get to the point where extracting another method would result in me just describing the language semantics in the method name.

One of the approaches that I've come across with regards to doing this refactoring is that it's only used when there is duplication of code and we want to reduce that duplication so that it's all in one place and then call that method from two places.

While this is certainly a valuable reason for doing extracting method I think there are other reasons why we would want to do it more frequently than just this.

Expressing intent

One of the main reasons we design code in an object oriented way is that it often allows us to describe the intent of our code more clearly than we would be able to it we wrote it with a more procedural approach and I think the same thing applies when extracting methods inside a class.

Quite often when reading code we're interested in knowing a bit more about a class than we can derive from its name but we're not really that interested in all the low level details of its implementation.

If methods have been extracted abstracting all that detail away from us then we're able to quickly glance at the class and fairly quickly work out what is going on and then move back to working out what we were actually doing in the first place.

It makes code easier to read

A consequence of extracting that detail away is that it makes the code easier to read because we don't have to hold as much information about what is going on in our head at any one time.

The aim is to try and ensure that the chunks of code that we extract into a method are all at the same level of abstraction – Neal Ford refers to this as the Single Level of Abstraction Principle (SLAP) in The Productive Programmer.

We would therefore not have a chunk of code which described some business concept or rule mixed in with a bit of code that was interacting with the database as an extreme example.

I find myself most frequently extracting method when I come across several lines of code doing similar operations, the aim being that when we read the code we don't need to care about each of the individual operations but just the fact that operations are being done.

It exposes semantic errors

One benefit which I hadn't actually appreciated until recently is that extracting a method can actually help to identify areas of code which shouldn't actually be where they are.

We were recently working on some code around starting up a Selenium session where the 'ResetSeleniumSession' method was doing the following:

public ISelenium ResetSeleniumSession()
{
	if(Selenium != null)
	{
		Selenium.Stop();
	}
	Selenium = new CustomSelenium(....)
	Selenium.Start()
	Selenium.Open(ApplicationRootUrl);
	Selenium.WindowMaximize();
}

We didn't think those last two lines belonged in there so we extracted them out so that we could make sure that the opening of the selenium client was still being done in all the places that ResetSeleniumSession was being called:

public ISelenium ResetSeleniumSession()
{
	...
	Selenium = new CustomSelenium(....)
	Selenium.Start()
	LoadAndMaximise(ApplicationRootUrl);
}

Later on another colleague passed by and saw us looking at this method and pointed out that it was wrong that we were launching the client from inside this method and had probably been added into that method by mistake!

Maybe that code would have been spotted anyway but it had been like that for a while and I think extracting it out into its own method to make it more obvious was useful for exposing that.

In Summary

That's all I can think of for the moment although I'm sure there are more reasons why we'd want to extract method.

From my experience extract method is the most useful refactoring that we can do and it can quickly make a bit of code that seems impossible to understand somewhat readable and it can help keep new code that we write easy for others to understand instead of becoming a legacy mess.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • HackerNews
  • StumbleUpon
  • Twitter

Written by Mark Needham

June 4th, 2009 at 8:30 pm

Posted in Coding

Tagged with , ,

9 Responses to 'Coding: Why do we extract method?'

Subscribe to comments with RSS or TrackBack to 'Coding: Why do we extract method?'.

  1. Yeah, I love SLAP/Composed Method/extract method, too.

    Another benefit, extending your last point, is that it makes it easier to identify groups of methods that should be moved into their own class.

    Mwanji Ezana

    5 Jun 09 at 12:40 am

  2. I wonder how r u test driving those refactors … or if they r simply refactors already covered by tests

    cheers
    mike

    mike

    5 Jun 09 at 2:34 am

  3. I use extract method regularly during refactoring typically to help express intent/make it more readable and keeping everything at the same level of abstraction. I find this greatly helps me understand what a class is doing and keep its responsibility focused. Recently I was told by our tech lead that my code is hard to understand because too many classes and methods. I stated the reasons why I prefer small methods and classes. He seemed unmoved, how would you go about trying to show the benefits of extracting methods?

    Ryan

    5 Jun 09 at 6:41 am

  4. // Later on another colleague passed by and saw us looking at this method and pointed out that it was wrong that we were launching the client from inside this method and had probably been added into that method by mistake!

    I'm not quite sure why your friend said that extracting this method was wrong?

    Kamal

    5 Jun 09 at 2:37 pm

  5. @Kamal – sorry probably not explained too clearly. I meant my colleague noticed the code was in the wrong place due to the fact that us extracting the method had made it more obvious.

    Mark Needham

    5 Jun 09 at 4:00 pm

  6. @mike yeh they were covered by tests already.

    @Ryan I guess if you get the chance to work together on some code with the Tech Lead that might be a good chance to try out some of the refactorings that you want to do and see what they think.

    I've been wondering recently about the trade off between keeping code consistent with what's there and taking action which makes the code better in your mind but different to how things are done elsewhere.

    Mark Needham

    5 Jun 09 at 4:25 pm

  7. Extract method is great. But how about better support of grouping methods in IDE and the language ? It's a pain to jump between 50 methods in one file.

    Guoliang Cao

    5 Jun 09 at 10:54 pm

  8. @Guoliang I think the same thing. It would be great if IDEs could show you the code of "related methods" without having to jump to it. Like peeking into the internals inline.

    The simplest case is when you extract a few lines to a private method, where do you put it? At the end of the class, or next to the method that uses it? And what if a second method starts using the private one?

    Source file declaration order doesn't matter for the compiler, it shouldn't matter for IDEs, either.

    Mwanji Ezana

    8 Jun 09 at 1:22 am

  9. @Mark
    "I've been wondering recently about the trade off between keeping code consistent with what's there and taking action which makes the code better in your mind but different to how things are done elsewhere."

    I think you gave the solution in the previous paragraph: communicate with the team, expose the benefits, get the green light to try it in one area of the code and spread it virally from there.

    Mwanji Ezana

    8 Jun 09 at 1:24 am

Leave a Reply