Jump to ratings and reviews
Rate this book

Addison-Wesley Object Technology Series

Refactoring: Improving the Design of Existing Code

Rate this book
As the application of object technology—particularly the Java programming language—has become commonplace, a new problem has emerged to confront the software development community. Significant numbers of poorly designed programs have been created by less-experienced developers, resulting in applications that are inefficient and hard to maintain and extend. Increasingly, software system professionals are discovering just how difficult it is to work with these inherited, non-optimal applications. For several years, expert-level object programmers have employed a growing collection of techniques to improve the structural integrity and performance of such existing software programs. Referred to as refactoring, these practices have remained in the domain of experts because no attempt has been made to transcribe the lore into a form that all developers could use... until now. In Refactoring: Improving the Design of Existing Software, renowned object technology mentor Martin Fowler breaks new ground, demystifying these master practices and demonstrating how software practitioners can realize the significant benefits of this new process.

431 pages, Hardcover

First published January 1, 1999

Loading interface...
Loading interface...

About the author

Martin Fowler

44 books987 followers
Martin Fowler (b. 1963) is a software engineer, Chief Scientist at ThoughtWorks, and an outspoken advocate for best practices in enterprise software design, particularly in regard to agile software development methodologies, including extreme programming.

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
3,740 (46%)
4 stars
2,866 (35%)
3 stars
1,071 (13%)
2 stars
224 (2%)
1 star
82 (1%)
Displaying 1 - 30 of 355 reviews
Profile Image for Jesse Buss.
25 reviews7 followers
January 28, 2016
Overall I was disappointed in this book. Modern tools and IDE's have removed nearly all of the pain points that are laid out in this book, which made reading annoying and tiresome. I skipped the "Mechanics" section of every single refactor because they are just not relevant in 2016. Your compiler and IDE will tell you every thing you need to know in nearly all cases.

That being said the content is good, albeit very basic. I would recommend this to someone who is just out of college or with little to no experience. I don't feel that experienced developers would get much out of this book. I took a way a few nuggets but nothing that was too impactful. I think this book was likely groundbreaking when it was originally released in 1999, but 17 years is a lifetime in software development.
Profile Image for Ivan Idris.
Author 11 books23 followers
January 22, 2012
Refactoring is the process of rewriting software, without changing the way it functions, in order to improve its readability, testability or maintanability. A book has been written on the subject by Martin Fowler. Some of the chapters were written by other people.

“Refactoring: Improving the Design of Existing Code” is focused on OO programming (lots of Java examples) and Agile practices. It is setup as a catalog of refactoring techniques. Each page dedicated to a refactoring is clearly marked, so that you can easily look up a refactoring.

The book was written a decade ago. At that time IDE’s did not support advanced refactorings. Most of the methods described are fully automated in modern IDE’s. This means that you don’t have to follow the text that closely any more.

1. Refactoring, a First Example

The first chapter starts with a simple example. Java code is used throughout the example as well as UML diagrams.

2. Principles in Refactoring

The Why and When of refactoring are discussed. Also we get instructions on what to tell our manager about refactoring. This seems a bit silly to me, since I have never had to explain refactoring to my managers.

3. Bad Smells in Code

“Code Smells” is a frequently used Agile phrase. A phrase I don’t care that much about. Code works or it doesn’t, it can be ugly or unreadable, but it doesn’t smell. The list of “smells” makes sense, however some of the names are downright confusing. For instance, would you be able to tell me what “Refused Bequest” means?

4. Building Tests

This chapter talks about JUnit at length. I am sure you are aware that there are many other unit testing frameworks for programming languages other than Java such as PyUnit. We are told that before you start refactoring, you need to have tests. I think it is more of a chicken/egg dilemma. Sometimes you need to refactor first in order to test. Unit tests and functional tests are mentioned. Integration tests, however are completely ignored. How would you know whether the performance and memory usage of your system remained the same? Clearly, this chapter was written by a software developer, and not by somebody who likes breaking applications, I mean testing applications.

5. Toward a Catalog of Refactorings

Chapter 5 describes the catalog of refactorings to follow. It is the catalog metada in a sense.

6. Composing methods

This chapter is the beginning of the catalog, which forms the “meat” of the book. I am just going to mention a few of the techniques listed in chapter 6.”Extract Method” is one of those refactorings I use on a daily basis. Sometimes things go wrong so we have to do the opposite refactoring “Inline Method”. The author starts using the term “temp” to mean temporary local variables.

7. Moving Features Between Objects

The author admits that he has trouble assigning responsibilities to objects. We are supposed to fix errors with “Move Method”, “Move Field”, “Extract Class” or other refactorings in this chapter.

8. Organizing Data

This chapter discusses a lot of different ways to simplify working with data. For instance, with these refactorings:

Replace Data Value with Object
Replace Array with Object

Also the refactoring “Replace Magic Number with Symbolic Constant” is explained a.k.a “Extract Constant”.

9. Simplifying Conditional Expressions

In my opinion the refactorings in this chapter need to be renamed. Apart from “Decompose Conditional”, which is clear enough. Although “Breaking up Conditional” might have been better.

10. Making Method Calls Simpler

Make method calls simpler by renaming them or replacing long parameter lists by objects. The latter technique could be a problem in concurrent programs. It is common to pass immutable values as parameters. You might not be able to replace them by immutable objects.

11. Dealing with Generalization

Generalization or in OO terms inheritance is a powerful mechanism, that tends to be overused a lot. You can push/pull a method or a field. Inheritance can be replaced by delegation and vice versa.

12. Big Refactorings

In this chapter starts what we can call the “dessert” part. No more simple refactoring recipes. Instead four refactorings that take a considerable amount of time.

13. Refactoring, Reuse and Reality

This chapter is an essay on Refactoring by William Opdyke.

14. Refactoring Tools

IDE’s have come a long way since this book was written. Most of the issues in this chapter are no longer valid.

15. Putting It All Together

This final chapter by Kent Beck is a bit mystical and vague. Those are his own words by the way. Some of the points make sense, but the chapter is written too much in a master talking to an apprentice style.

The book has a list of soundbites at the end. Literally. The fun thing is that you probably have heard or are going to hear a lot of these soundbites. “Refactoring” is a very useful book, albeit too focused on Java. Most recipes would work for another Object Oriented language. I give this book 5 stars out of 5.
Profile Image for Petar Ivanov.
83 reviews21 followers
July 22, 2021
It's a must-read for every software engineer or anyone involved in the programming world. I've picked most of the ideas in this book from other places such as Clean Code, The Clean Coder and etc, but still, I learned a couple of things.
Refactoring is a must-have in your toolbox. It should be done incrementally and always think twice before you start refactoring. Every "good practice" could be a nightmare in the end and vice versa. Have in mind that refactoring is a continuous process!
521 reviews10 followers
April 27, 2019
The second edition of the classic Refactoring book by Martin Fowler is more than just an update. It switched from Java to JavaScript for most of the examples, what lead to many renames of refactorings (for example: extract function instead of extract method). Most of the classical refactorings are still there and it had space for new ones like Split Phase – one practice I found by myself and now can refer to using a name. This tradition of giving names to practices around refactoring is continued and will be useful for the years to come.

The most significant change beside the programming language is that Fowler uses more and smaller steps to explain the refactoring. This makes it much easier to apply a refactoring to your own code and may change the perception of small steps being slow. The opposite is most often the case; smaller steps result in lot less fixing and debugging and that speeds up refactorings significantly.

I got the print edition and I’m disappointed with the thin paper they used. The back of the page can be seen and the headings use a rather bad combination of black and red that looks more like a defect than an intended design decision.
Profile Image for David Workman.
22 reviews13 followers
April 23, 2010
While this book is more of a reference book than a book to read through a memorise (and I intend to use it as such in the future), this book is well worth having for software engineers looking to improve their practices. Even if you don't subscribe to Martin Fowler's 'lots of small methods and classes' style of programming (and I admit, it takes some getting used to), the techniques in this book are still useful and applicable to any software project.

The book consists mainly of a catalog of refactorings. These can be thought of as a 'toolbox' for a programmer looking to clean up their code and improve the code's design, with each refactoring giving a description of how to apply it and a rationale as to when you may wish to. The tail end of the book consists of some large-scale refactorings which are much less mechanical and more hazy due to their much larger scope, and some chapters written by proponents of refactoring, including the renowned Kent Beck (of XP and Smalltalk fame).

In a manner very similar to the GoF Design Patterns book, the refactorings are grouped into sections of similar functionality, and most of the refactorings have an inverse refactoring (extract method has an inverse of inline method, there is both push-up hierarchy and push-down hierarchy for fields and methods, and so on), which are useful in different circumstances. This aids the book as a reference book, and many refactorings also refer to other refactorings within the book as potential followups or re-use them as smaller sub-sets of a larger refactoring (such as extract superclass involving pushing methods and fields up the class hierarchy).

Overall, the book is worth a read-through to familiarise yourself with the content, and keeping close at hand for if you need to remember the details of a specific refactoring. The writing is clear and concise and the refactorings are mostly self-contained so you don't need to go searching over many sections to find all the details. A solid, although not exactly thrilling, book and definitely a foundation for programmers looking to improve their coding skills.
Profile Image for Ehsan Gazar.
122 reviews7 followers
February 8, 2019
This book is not just for refactoring, it's for understanding how professional are thinking about their code. You can use these methods even in writing the first line of your code.

This is one of the books that every developer should read to transform his knowledge to be in more readable and flexible code.
Profile Image for Andreea.
43 reviews17 followers
January 6, 2013
If you are interested in improving and maintaining the quality of your code this book should be on your reading list. It is not the kind of book you read once and forget about it. When you are doing refactoring it’s always recommended to come back and check the categories explained in it.

What I really enjoyed is that it confirmed some of the ideas I already had about software development. On the first hand you should have a robust test suite in order to be certain that refactoring didn’t change the behavior of the software. Furthermore, you should never start writing new features on top of code that looks like it needs refactoring. First refactor and then write new code. Lastly, refactoring should not stop the progress of your project, but be continuously integrated with the development phase.

The book was written a while ago and some comments regarding the effectiveness of refactoring tools are a little bit outdated, but since it is not concerned with providing a catalogue of this kind of tools, this aspect is not so relevant.
Profile Image for Michael Koltsov.
93 reviews54 followers
June 6, 2021
This year was supposed to be full of reading and learning new things, but the reality has shown that it had different plans for my time. That's why it took me much longer that usual to finish this book and therefore I may forget some of the things that I found interesting in it.

I must admit that as a writer Martin Fowler has his unique style that you start to grasp after finishing just a few pages of any of his books. He's one of the father figures of the "make code for humans not for the machines" movement that some may also call "clean code & architecture". It's always interesting when in his books his starts to mention his buddies who'd contributed a lot to make developer's life easier. In this book for example I found out that "smelly code" saying was invented because Kent Beck had to fight two things simultaneously: someone's bad code as well as smelly diapers. A quick glance to other people's lives is something that you can't often find in technical books.

Speaking of the book itself I don't think that there was much to be surprised about since the first edition. More controversial refactoring methods have been added, it always frightens me when one example contradicts with the one that you read a few pages ago. But that's the art of writing elegant code that can pass code reviews. You never know what type of refactoring will be useful until you try all of them. And some of them can be opposite to one another, but that what makes good developers artists not just craftsmen.

I enjoyed the choice of switching to Javascript to illustrate the refactorings. It made the book much more concise and at the same time if JS is not your primary language it makes you think how this or that example would work in your language. That's the right way to go in my opinion.
Profile Image for Ashkan Entezari.
28 reviews1 follower
April 9, 2020
Refactoring is definitely an educational read for any programmer. It covers many areas of refactoring from why we need it to how we should do it and get it done. The only regret that I have right now is reading the first edition of this book (+20 years old!) while there was a second edition which was published 2 years ago. When I read the change-log, it didn't seem like very different but as soon as I picked-up the book I realized how outdated it is in some parts. There are tons of discussions around how to make sure our refactoring doesn't break the program and at the end there is a chapter dedicated to refactoring tools (apparently only available for Smalltalk at the time) and how we need it for Java and other programming languages. I was reading all these while knowing these days all IDEs have these tools integrated in them and for example I never worry about changing a method name!
But other than this, it was very educational and I think developers can benefit from it.

The Main Take-aways:
- It modularizes refactoring: defines categories of all the common small refactorings and assigns a name for each. Then it defines bigger refactorings as combination of these smaller, standard refactorings.
- This list of refactorings can be studied to better understand code smells and what we can do to fix them (or avoid them in the first place)
- a piece of software is never perfect and its lifetime it should always evolve and change. We can never get it all right in the first place so we should incorporate refactoring in our day-to-day programming. We should not think of it as waste of time but as an essential part of perfecting our software. It gives us a second chance to take another look at the program and fix the issues we couldn't see in the first place.
- Refactoring should be done in small steps and ideally these steps shouldn't get done all in one sitting. We should do a few small steps here and there as we develop and maintain our programs.
- After each step we should run the tests to make sure we haven't broken anything. If we are missing tests, we should and them first and then think about refactoring that part.
Profile Image for Zahra Dashti.
361 reviews103 followers
June 12, 2020
یک کتاب تکنیکال، خوب و روان و صد البته جذاب. به راحتی می‌شه با کتاب ارتباط گرفت، مخصوصا از بخش کاتالوگ ریفکتورها که کاملا تکنیکی هست و کاربردی. به محض شروع مطالعه این کتاب، به راحتی می تونید از آموزه‌هاش در کدنویسی روزمره‌تون استفاده کنید. البته یک نقد جدی به کتاب دارم و اون اینه‌که واقعا نویسنده، چه انگیزه‌ای داشته که مثالها و نمونه کدهای ویراست دوم کتاب رو، با جاوااسکریپت آورده؟ (بعضی مثالها با جاواست) در حالی که ویراست اول، ظاهرا با جاوا بوده. واقعا انگیزه نویسنده رو در این بخش درک نکردم، به نظر صرفا سلیقه شخصی بوده، با این وجود، و با وجود اینکه خیلی کامل با syntax جاوااسکریپت آشنا نبودم، کتاب کاملا برام مفید واقع شد. نسخه غیرکاغذی کتاب (من به ورژن html دسترسی داشتم) چند بخشی در بخش کاتالوگ refactoring بیشتر داشت. همچنین لینک‌های خوبی به سایر بخش‌های مرتبط کتاب یا بخشهایی از سایت نویسنده داشت که مناسب و به جاست. بعد از خوانش اول، می‌شه از کتاب به عنوان یک مرجع و هندبوک برای refactoring استفاده کرد و همیشه بهش رجوع کرد. برای هر نوع ریفکتور هم عنوانی بیان شده که اغلب خود عنوان به اندازه کافی گویاست، اما خوب توضیحات و دلایا و مثال هم، به اندازه لازم و کافی در کتاب هست.
این کتابیه که مطمئنم با لذت می‌خونید و از خوندنش خسته نمی‌شین.
Profile Image for Vladimir Sechkarev.
29 reviews4 followers
February 25, 2019
До прочтения я писал плохой код; теперь я, слегка обновив приоритеты, пишу код чуть лучше. Это настолько радостное осознание собственного прогресса, что я готов простить книге и суховатый стиль, и отсутствие ответов на весьма кмк важные вопросы вроде приоритетов различных видов рефакторинга. Очень, очень хорошо.
Profile Image for Prodrom.
18 reviews
June 17, 2022
Very pleasant to read! The language is straightforward and clear, plus many examples.
Profile Image for Ahmad hosseini.
270 reviews66 followers
October 20, 2020
At the beginning of the book, Martin Fowler states:
“My aim is to show you how to do refactoring in a controlled and efficient manner. You will learn to refactor in such a way that you don’t introduce bugs into the code but methodically improve its structure.”
Well, he has done it perfectly.
There are a lot of #refactoring methods in the book that can inspire you to write better #code and improve the structure of your #software. Some of them are complex and some of them are so simple that maybe you have used them before but Mr. Fowler provided a controlled, #efficient and step by step manner for all of them.
5 reviews
March 19, 2019
You hear something about refactoring and you want to see what it is ?
You want to make your code better but don't know how to do it ?

If your answer is yes, then this book is for you.
Martin Fowlers 'Refactoring' is in my opinion the best book about this subject.

Author describes many refactoring techniques and explain how and when to use them.
Each technique has it's own example write in javascript - code is very easy to understand
and you won't have any problems to apply it in your language of choice.

What is nice about this book, is that author shows us that knowing those techniques is simple not enough.
There is always more than one way of doing things. Good example is 'Inline Variable' and 'Extract Variable'
pattern - they are doing opposite things and you cannot tell which one is better :) All depends
from context and you should decide which one to use based on your experience and good sense of design.
In the end code should be easier to understand and easier to modify.

It will also help you to decide when and why you should refactor your code.

"The first time you do something, you just do it. The second time you do something similar, you wince
at the duplication, but you do the duplicate thing anyway. The third time you do something similar,
you refactor"
-- Don Roberts

In practice I would probably refactor when first duplication appears. But the general idea behind this quote is that you
don't have to refactor from the beginning. Code doesn't have to be perfect from day one. You will make it better
on the way. Your code is never done. It's evolving all the time and there is always room for improvement.

"You have to refactor when you run into ugly code - but excellent code needs plenty of refactoring too"
-- Martin Fowler

This book will give you solid reference how to refactor your code - both, the ugly one and the excellent one.

Going through this book, I found that I'm already using many patterns in my day to day job.
At some point I probably used all of them. It's always good to see that what you are doing
is consider good practice - and now I can refer to each technique by name :)

Can I say something bad about this book ?

No! I think this book is perfect and it will give you solid techniques and background to make your
code better.

Well, the only bad thing that I can say about this book, is it's build quality. I have the newest version of this book,
published in 2019 by Addison-Wesley, and in my opinion the build quality is a joke. The book has 408 pages, it cost about 50$, and the paper
is so thin you can almost look through it. Pages will crease even if you try to turn them very carefully.
I wish it got thick, non glossy paper. For this price I expected something better.

Can I recommend this book ?

100% YES! I think that every developer should read this book and keep it on his desk.
I know that I will. I always keep my most important programming books around me, and this book will
be one of them. The other ones are 'Clean Code' and 'Code Complete'. I look at them when I'm
stuck or when I need some inspiration.

My final rating for this book is 5/5.
December 4, 2016
This book is a must-read for every software developer. I would personally recommend it to my team members.

I totally agree with Martin and his vision that the changes should be incremental. I think everyone that tried a "complete rewrite" at some point failed or at least achieved unsatisfactory results. Maybe they didn't completed in time or didn't achieve the expected results.

The most important aspect that is emphasized in the book is that you should apply refactoring when you need to, not just going blindly and refactoring everything. What we have in our team as a good rule of thumb is basically what is promoted in this book - once you start working on a new feature or fixing a bug and you see any issues with the code your started working on, you start refactoring and then implement the feature or fix the bug. In some cases you can fix the bug and refactor later, but the important thing is doing only ONE thing a time.

I liked that Martin says that these refactoring are not a silver-bullet and gives them in "pairs", e.g. remove class with extract class. I think he makes the readers think if they actually need to perform any refactorings at all and that they all depend on the context.

Remember that refactoring is a process, not an event. :)
Profile Image for Stuart Leal.
23 reviews1 follower
December 13, 2021
Funny enough, I feel this should be placed higher in priority as a topic to learn than design patterns.

The reason is that you don't design as often as you go and contribute to a project that has already been started.

Usually designing big chunks is critical for adding a new big feature, or fixing architecture issues (bad design) to allow more agility in fixing issues. This is when design patterns will come handy.

But, refactoring is a far more practical skill that usually you can go and use in every single one of your code reviews, assuming it contains a feature update/fix of any sort.

There are a lot of refactorings. It took me a while to read them all. But I think it's worth the time. I feel I've become a different programmer because of this.
Profile Image for Chan Myae San Hlaing.
5 reviews1 follower
February 18, 2022
I think I'll probably mark this book is currently-reading throughout my career. Because I am referencing it every now and then even today.

When I first read it, I dropped it after a few chapters. I was a naive junior programmer and the book was a bit mundane and boring. I am not getting anything special out of it.

Years later, when I get to work on a legacy code base with every code smell in the book manifesting here and there, I start to appreciate this book.

Each of the techniques in the book on their own doesn't seem all that useful. But the trick is when you master how to appropriately combine them to get your code into better shape gradually.

I think it is definitely a must-read for programmers who want to get good at their craft.
Profile Image for Mengyi.
53 reviews4 followers
March 25, 2020
Biggest takeaway is to take really small steps when refactoring, which the book demonstrated a lot with detailed examples. A lot of times I felt uncomfortable during refactoring, but now I know it's because that I cut corners and didn't take small enough steps.

The book also "refactors to patterns" a lot, which I found helpful reading immediately after the design pattern book.
16 reviews
March 19, 2023
This book offers many practical and hands-on advice on how to clean up exisiting codebases, especially those ones that contain very 'legacy' code which appear to be beyond saving.
The catalog provided with list of refactorings is something I think I will be able to refer to in the future as I face these similar situations in my personal software development journey.
It is highly useful for the workplace because it has lists of code smells indexed with common refactorings to solve them. Addtionally, there is a diagram to quickly understand what a refactoring does, mechanics of what the you should do step by step implement it and also a detailed example should you require more insight.
Profile Image for Steve Fenton.
Author 17 books21 followers
January 25, 2019
What I like most about this book is that many of the refactorings are accompanied by an inverse equivalent. Like the GoF book on patterns, the idea behind the library is to commit the existence of patterns to memory, but refer back to the library when you want to apply one.
Profile Image for Yury Jefse.
85 reviews4 followers
March 17, 2021
Gostei da estrutura do livro, de como é claro ao explicar cada técnica, e como é aplicado. Os códigos da edição que li, que é a segunda, é escrito em Javascript já seguindo as tecnologias que estão badaladas no mercado. Vale ressaltar que esse livro é mais indicado para iniciantes até intermediário. Se você é avançado e espera coisas novas aqui, infelizmente você vai se frustrar; mas caso queira reforçar conceitos e técnicas de boas práticas, esse livro é bom.
Profile Image for Rômulo Oliveira.
5 reviews1 follower
January 10, 2019
Um dos melhores livros de programação que se pode ter, atemporal. Ainda não havia lido e fiquei feliz de ver que já sabia e aplicava muito dos conceitos do livro, graças a ótimos colegas que trabalhei e me inspiram. Vai continuar fazendo parte do dia a dia, principalmente a versão web, muito fácil de consultar.

Saber refatorar bem (quando, como, porquê e para quê) separa os pequenos dos grandes, e esse livro é o guia definitivo para isso.
Profile Image for Thang.
74 reviews9 followers
November 25, 2019
It's more like a reference than a book, so it's a bit dry to read.
Profile Image for Aleksander Meterko.
19 reviews1 follower
March 6, 2017
A solid book for a developer which contains a number of so-called "code smells", which should tell you that this specific piece of code needs to be refactored, along with techniques to achieve this result. Although these techniques seems outdated as modern IDEs are able to make most of these refactorings automatically for you (and these automation is described in Chapter 14) it is still good to know when to perform these refactorings.

This book may be read both as a reference guide (it has convenient reference table) or from cover to cover as it is written in a readable and comprehensive language.
Profile Image for Simon Booth.
39 reviews
August 4, 2019
Good in its day

This is the book that introduced the concept of refactoring to the wider software engineering community. A refactoring is a change to the structure of code that does not change its functionality. Prior to this the prevailing wisdom was "if it ain't broke don't fix it", and whilst this is still a sensible principle in general most programmers know that code can be broken even when it produces the correct output. Refactoring the code can help to fix those less tangible problems - making code easier to understand, modify and maintain.

In the 20 years since the first edition this has become an uncontroversial point and "refactoring" has entered the daily lexicon of the software engineering discipline. Surely time for an update to the classic text on the subject to bring it up to date with all the learning that 20 years of widespread practise have revealed!

Unfortunately it seems that there isn't much new to say. The refactoring techniques have been shuffled around a bit, sometimes consolidated or split, but they all seem very familiar. They are now so familiar that they seem trivial in fact, so obvious they barely need mentioning. Whilst there is value in establishing a common lexicon for these common operations, the detailed step by step examples become a chore to read through because they are so obvious.

One of the major changes in this anniversary edition is that the examples in Java from the first edition (it was fashionable at the time) have been rewritten in Javascript (it was fashionable at the time). This is a questionable choice... Javascript is idiosyncratic, and a weakly typed language does not illustrate the form of some of the techniques described well. So many of the examples are qualified with "because javascript..." or "in a statically typed language..." that it must have occurred to the author that the book would be clearer (and probably shorter) if the examples had been written in a language more suitable to what they were intended to illustrate.

Most of the examples boil down to making small, incremental changes and then running your comprehensive set of tests (which take a few seconds to run) to make sure you didn't make a mistake. Fine if you're working on some small, isolated piece of code with unit tests accessible at a keystroke... Less helpful when you're working with part of a legacy system that takes 15 minutes to build and 30 to run through its tests (if they exist). Unfortunately the latter are where refactoring is probably most needed.

The book is worth adding to your library and at least skimming to pick up some patterns and terminology if you're new to programming. You might occasionally even find yourself consulting it as a reference for how to do a refactoring, though the answer is probably "in the obvious way".

The author should rightly be proud of the fact that his original text was so influential that 20 years later it is hard to imagine that there was a time when it needed to be written ;-)
Profile Image for Costin Manda.
551 reviews15 followers
February 28, 2019
It was long overdue for me to read a technical book and I've decided to go for a classic from 1999 about refactoring, written by software development icons as Martin Fowler and Kent Beck. As such, it is not a surprise that Refactoring: Improving the Design of Existing Code feels a little dated. However, not as much as I had expected. You see, the book is trying to familiarize the user with the idea of refactoring, something programmers of these days don't need. In 1999, though, that was a breakthrough concept and it needed not only explained, but lobbied. At the same time, the issues they describe regarding the process of refactoring, starting from the mechanics to the obstacles, feel as recent as today. Who didn't try to convince their managers to allow them a bit of refactoring time in order to improve the quality and readability of code, only to be met with the always pleasant "And what improvement would the client see?" or "are there ANY risks involved?" ?

The refactoring book starts by explaining what refactoring means, from the noun, which means the individual move, like Extract Method, to the verb, which represents the process of improving the readability and quality of the code base without changing functionality. To the defense of the managerial point of view, somewhere at the end of the book, authors submit that big refactoring cycles are usually a recipe for disaster, instead preaching for small, testable refactorings on the areas you are working on: clean the code before you add functionality. Refactoring is also promoting software testing. One cannot be confident they did not introduce bugs when they refactor if the functionality is not covered by automated or at least manual tests. One of the most important tenets of the book is that you write code for other programmers (or for yourself), not for the computer. Development speed comes from quickly grasping the intention and implementation when reading, maintaining and changing a bit of code. Refactoring is the process that improves the readability of code. Machines go faster no matter how you write the code, as long as it works.

The book is first describing and advocating refactoring, then presenting the various refactoring moves, in a sort of structured way, akin to the software patterns that Martin Fowler also attempted to catalog, then having a few chapter written by the other authors, with their own view of things. It can be used as a reference, I guess, even if Fowler's site does a better job at that. Also, it is an interesting read, even if, overall, it felt to me like a rehearsal of my own ideas on the subject. Many of the refactorings in the catalog are now automated in IDEs, but the more complex ones have not only the mechanics explained, but the reasons for why they should be used and where. That structured way of describing them might feel like repeating the obvious, but I bet if asked you couldn't come up with a conscious description of the place a specific refactoring should be used. Also, while reading those specific bits, I kept fantasizing about an automated tool that could suggest refactorings, maybe using FxCop or something like that.

Things I've marked down from the book, in the order I wrote them down in:
- Refactoring versus Optimization - Optimizing the performance or improving some functionality should not be mixed up with the refactoring of code, which aims to improve readability of code while preserving the initial functionality. Mixing them up is pitting the two essential stages of development one against the other.
- Methods should use their data of their own object - one of the telltales of need to refactor is when methods from an object use data from another object. It smells like the method should be moved in the responsibility of that other object.
- When it is easy to refactor, choose a simple design - Of course the opposite is true, as well: when you know it will be hard to refactor a piece of code, try to design it first. If not, it is better to not add unnecessary complexity. This is in line with the KISS concept.
- Split your application into self encapsulated parts - One of the ways to simplify refactoring is to separate your application into bits that you can manage separately. If you didn't design your application like that, try to first split it, then refactor.
- Whenever you need to write a comment, consider extracting a method with a meaningful name - or renaming methods to be more expressive.
- Consider polymorphism when seeing a switch statement - Now that is an interesting topic in itself. Why would polymorphism help here? How could it be simpler to understand than a switch/case statement? The idea behind this is that if you have a switch somewhere, you might have it somewhere else as well. Instead of taking decisions inside each method, it is better to split that behaviour in separate classes, each describing the particular value that the switch would have operated on.
- Test before refactoring - this would have been drilled in your head already, but if not, the book will do that to you. In order to not add faults to the program with the refactoring, make sure you have tests for the existing functionality, tests that should pass after the refactoring process, as well.
- The Quantity pattern - Review the Quantity pattern in order to improve readability and encapsulate simple common actions performed on specific types of units.
Split conditionals into methods - in other words try to simplify your conditional blocks to if conditionMethod() then ifMethod() else elseMethod(). It might seem a sure way to get to a fragmented code base, with small methods everywhere, but the idea is sound. A condition, after all, is an intention. Encapsulate it into a well named method and it will be very clear what the programmer intended. Maybe the same method will be used in other places as well, and then, using polymorphism, one can get rid of the conditional altogether.
- Use Null objects - an interesting concept that I haven't even considered before. It is easy to recognize the need for a Null object when there are a lot of checks for null. if x==null then something() else x.somethingElse() would be turned into a simple x.something() if instead of null, x would be an object that represents empty, but still has attached behavior. An interesting side effect of this is that often the Null object can be made an immutable singleton.
- Code inside Assertions always executes - This is a gotcha I found interesting. Imagine the following code: Assert.IsTrue(SomeCondition()) Even if the Assert object is designed to not execute anything in Release mode, only compiled in Debug, the method SomeCondition() will execute all the time. One option is to use an extra condition: Assert.IsTrue(Assert.On&&SomeCondition()) or, in C#, try to send an expression: Assert.IsTrue(()=>SomeCondition())
- Careful when replacing method parameters with parameter object in parallel processing scenarios - Which nowadays means always. Anyways, the idea is that old libraries designed for parallel processing used large value parameter lists. One might be inclined to Introduce Parameter Object, but that introduces a reference object that might lead to locking issues. Just another gotcha.
- Separate Modifier from Query - This is a useful convention to remember. A method should either get some information (query) or change some data (modifier), not both. It makes the intention clear.

That's about it. I have wet dreams of cleaning up the code base I am working on right now, maybe in a pair programming way (also a suggestion in the book and a situation when pair programming really seems a great opportunity), but I don't have the time. Maybe this summary of the book will inspire others who have it.
Profile Image for Yevgeniy Brikman.
Author 3 books589 followers
August 2, 2014
Pros: presenting refactoring as a regular part of the development process is an important step forward. The example at the start of the book is a great demonstration if why this stuff matters. Nice to systematically catalog code smells.

Cons: the code smells section is great, but has no actual code examples. The chapters that go through the refactoring moves are better, but having each one isolated makes it boring to read. The big refactoring chapters are only UML diagrams, which are not good teaching aids. I think walking through a few medium sized examples, as in the first chapter, would've been more effective.

Finally, the exclusive focus on java and OO makes sense, but misses much of the power of functional programming, which removes the need for some types of refactoring entirely. Also, it's a somewhat old version of Java, so the content can feel a little dated.

Overall: an important book to get a sense of refactoring, but the examples leave a lot to be desired.

Good quotes:

With refactoring you find the balance of work changes. You find that design, rather than occurring all up front, occurs continuously during development. You learn from building the system how to improve the design. The resulting interaction leads to a program with a design that stays good as development continues.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

It reminds me of a statement Kent Beck often makes about himself, "I'm not a great programmer; I'm just a good programmer with great habits."

A heuristic we follow is that whenever we feel the need to comment something, we write a method instead.
Profile Image for Nick.
125 reviews9 followers
April 18, 2012
I was having a great time reorganizing and hopefully improving some Java at work, and a coworker had mentioned this book. Good stuff. I didn't read through the whole reference section, but took a quick look at some. It seems like the IDE I was using (IntelliJ) had a bunch of refactorings (not sure what the overlap is with this catalog) available as keyboard shortcuts, basically. But it's still fun to read about. Unfortunately, I got this book approximately the same week I shifted off Java development for the time being.

One of the things I'm curious about is, as mentioned in this book, that refactoring strongly-typed languages (I probably don't have the lingo quite right here... well-typed?), like Java, is much more straightforward than other languages, like Javascript or Python. I've done some large-enough-for-now JS development, and feel like I have some sense of some of the patterns there. Most of my Python has been one-off scripts, but I'd really like to do more with it. Someday...
Displaying 1 - 30 of 355 reviews

Can't find what you're looking for?

Get help and learn more about the design.