9.2.1 - Refactoring - Extract Method - podcast episode cover

9.2.1 - Refactoring - Extract Method

Nov 11, 202511 min
--:--
--:--
Download Metacast podcast app
Listen to this episode in Metacast mobile app
Don't just listen to podcasts. Learn from them with transcripts, summaries, and chapters for every episode. Skim, search, and bookmark insights. Learn more

Episode description

Software Engineering: A Modern Approach - Chapter 9 - Section 9.2.1 - Refactoring - Extract Method (AI-generated summary). Online book available at softengbook.org

Transcript

Ever feel like you're caught in, I don't know, an avalanche of information, just wishing someone could sift through it all and hand you the really important stuff? Well, that's pretty much what we do here on the Deep Dive. We take your sources, articles, research, whatever you've got, and we act as your guides, cutting through the noise to get

to the core knowledge. Think of it as a shortcut to being genuinely well informed, hopefully with a few surprising facts, maybe a bit of humor along the way. Today we're diving into software engineering, specifically a practice called refactoring, and even more specifically, one technique that some people call the Swiss Army Knife of code

improvement. That's right, and we're drawing our insights from software Engineering, a Modern approach by Marco Tulio Valente. We're really zeroing in on this concept called Extract method. So our mission, if you like, for this deep dive is to unpack what extract method actually is, how it works, and maybe most importantly, why it's such a valuable tool for anyone interested in how software gets built and, crucially, how it's maintained over time.

OK, let's get into it then. Let's unpack this right. So to really get extract method, we first need to talk about the bigger picture refactoring itself. Basically, refactoring is all about restructuring existing computer code. But here's the key thing. You do it without changing what the software actually does. From the outside, the behavior stays the same, but the inside, well, the internal structure changes.

The main goals, according to the book, are things like removing duplication, making it easier for developers to communicate about the code, and generally making the design simpler or more flexible. So it's not about adding new features or fixing bugs then? It's more like tidying up a really messy workshop. But for code. I think the book mentioned Martin Fowler. He really pushed this idea back in 2000, right? With his big list of refactorings.

He apparently laid out the steps, the pros, the cons for each one. Gave developers a common language, sort of. Exactly. A common vocabulary, A toolkit. It really boils down to what Kent Beck called good programming habits, and the source really emphasizes this. Beyond just fixing bugs or adding features, developers need to refactor often to ensure

systems maintainability. Maintainability just means how easy it is to understand the code, change it, add to it later on. You know, without breaking everything. If code isn't maintainable, it just gets harder and harder and more expensive to work with. Over time it becomes brittle. And that distinction is quite important, isn't it, 'cause sometimes you hear refactoring used for, well, all sorts of changes, like making code faster maybe, or improving the user interface.

That's true, the term can get used broadly, but for this deep dive and sticking to the books definition, we're using refactoring in its stricter sense. It means changes specifically aimed at improving the internal structure, the maintainability of the code itself, making the code base healthier. Essentially any performance gains or easier feature development are usually hay side effects, not the primary goal of refactoring itself. OK, got it. O refactoring is about internal

tidiness. Now let's zoom in on that Swiss army knife you mentioned. Extract method. What's the deal with this specific technique? Why is it considered so versatile? Well, its power lies in its simplicity, really. At its core, extract method means you take a specific chunk of code out of an existing method that's called the original method F You identify a logical block within F, maybe it

does one specific thing. Then you move that block into a completely new separate method, let's call the new 1G. And then back in the original method F, you just replace that block of code you removed with a simple call to your new method G. OK, so you're taking like one step from a complicated recipe, putting it in its own little label jar, and then the main recipe just says add contents of jar G here. Is that kind of the idea? That's a perfect analogy actually.

Yeah, Visually if methyl F does A then B, then C&B is the bit you want to extract. After you apply extract method, you get a new method G that just contains B and method S becomes do A then call G then do C It just cleans things up visually and logically makes the flow much clearer. And it's not just for pulling out one small bit, is it? The source mentioned variations. Absolutely, that's why it's the

Swiss army knife. You could extract several pieces from one long method, creating maybe G1G2 and G3. Or maybe even more powerfully, if you see the exact same chunk of code repeated and say 5 different methods, you can extract that common code into just one new method, G, and then all 5 original methods just called G Boom, duplication gone. Which is a huge win for maintainability. OK, that sounds incredibly useful, especially the duplication part. But what about the details?

Like if the code you pull out needs some information that was only available in the original method, or if it calculates something the original method needs later on, how does that work? Right, good question that gets into the mechanics. If the code you extract the code going into G uses variables that were local to the original method F, you have to pass those variables into G as parameters. Think of it like giving instructions.

You have to provide the necessary inputs, and similarly, if that extracted code produces some result that method F needs to continue its work, then the new method G has to return that value O. And one more thing, if there are variables used only within the extracted part, you should move their declarations into the new method G as well. Keep things tidy. These rules ensure everything still connects and works correctly after the change.

OK, so it really is versatile, handles different situations. You breakdown big methods, make them focus, give them clear names and the original method just becomes this sequence of calls. Much easier to follow, I imagine. Exactly. The book gives a really great real world example. It was from an Android system. There was this method called

oncreate. It's a standard thing in Android that runs when a component starts up, and this particular oncreate method was responsible for setting up a whole bunch of database tables. And how long was the source said? Over 200 lines, right? Just creating tables for things like cell signals, SMS messages, locations. Wow, trying to understand or debug that must have been really tough. Where would you even start? Precisely.

It was a classic example of a method doing way too much, so a developer took extract method to it not just once, but seven times. Each time they pulled out the logic for creating one specific database table and they created new methods with really clear names like CREATE CELL SIGNAL TABLE or CREATE SILENCE SPACE table. You knew exactly what each one did, just from the name. OK, and here's the kicker right? What happened to the original

200 line on create method? After those 7 extractions, it was reduced to just 7 lines, just a list of calls. Call create cell signal table, call Crete silence table, and so on. That's a massive improvement in clarity. And apparently each new method only needed one input, the database connection itself. Exactly. Think about the difference that makes. A new developer joins the team, looks at on create and instantly understands the high level process. OK, it creates these 7 tables.

If there's a bug related to the SMS table, you know exactly where to look. The Create silent Steam stable method You don't have to hunt through 200 lines anymore. It reduces the cognitive load, speeds up debugging, makes changes less risky, it turns complexity into manageable units. Now understanding the how is important, but the why is maybe even more interesting. Why do developers actually do this? The book points to a study from 2016 looking at GitHub projects.

They found developers had, believe it or not, 11 distinct motivations for using extract method. 11 different reasons that really does drive home the Swiss army knife idea it's long to a lot of different problems So what were the main ones what was the number one reason developers reached for this tool the. Biggest one by far. It came up 43 times in their study was code reuse. Often a developer needs a piece of logic that's already written, but it's buried inside some other method.

So they use extract method to pull that logic out, make it his own reusable method, and then they can call it from wherever they need it. No more copy pasting. Yeah, that. Makes sense, The book had a quote from a developer about that didn't something like. I always try to reuse code because when there's a lot of code redundancy it gets overwhelmingly more complicated. And when something changes in code that is duplicated somewhere, it usually needs to be changed there also.

That really highlights the pain of duplicated code down the line. The maintenance nightmare it. Really is find a bug in duplicated code and you have to find and fix every single copy. It's so easy to miss. One extraction solves that. OK, so the second most common reason found 25 times was introducing an alternative signature for an existing method an. Alternative signature. OK, what does that mean in plain English? Why extract for that it's?

Basically about offering slightly different ways to use a piece of functionality, Maybe a simpler way or more advanced way without duplicating the core logic. So imagine you have a log method that just writes a message to a file. Simple enough. A developer might extract the actual file writing part into a new internal method. Then they could create a new version of the log method, maybe one that takes an extra option

like a boolean flag saying. Also print this message to console the original simpler log method which is called the extracted core logic with the console flag set to false. The new one calls it with the flag set to true or based on the parameter OK. Gotcha. So you end up with maybe 2 log methods for the user of that code, 1 simple one with more options, but they both rely on that same extracted piece of core logic underneath.

So even a small change like adding an if statement based on that new flag still leverages the extracted method keeps the core logic in one place. Precisely, it avoids duplicating the fundamental file writing part. Beyond those top 2, the study found other important reasons too, like making code easier to test when you break down a big method into smaller ones, each small method is easier to test in isolation. You can write specific tests for create cell signal table, for example.

That's much harder when it's all tangled up in 200 lines, right? Testing becomes more focused, more manageable. Boost confidence too, I bet. What else? Well. Closely related is improving understanding by reducing complexity. That Android example is perfect here, just making the code easier to read and grasp by breaking it into named logical tongues, turning a dense paragraph into bullet points.

Essentially it just lowers the mental barrier to understanding what's going on. And one other common 1 was facilitating new features. Sometimes you need to add something new that uses part of an existing complex method. Extracting the relevant part first makes it cleaner and safer to then build the new feature on top of or alongside that extracted logic without messing up the original method. It prepares the code for change so.

You can really see how extract method isn't just some technical trick, it's a fundamental strategy. It's about creating code that's cleaner, easier to understand, and crucially, easier to maintain and change over the long haul. It really is a versatile tool for code health. Absolutely. Understanding these kinds of foundational concepts and the real world reasons why developers use them, like we saw in that study, really helps appreciate the craft involved in

software engineering. It shows why these practices are so important for building software that lasts. Well, thank you for joining us on this deep dive into extract method. Really fascinating stuff.

Transcript source: Provided by creator in RSS feed: download file
For the best experience, listen in Metacast app for iOS or Android