重构改善既有代码的设计javascript

重构,对于每个开发者都至关重要,特别是对于那些需要进阶的高级程序员。根据二八理论,20%的重构方法,能解决80%的坏代码。笔者最近查阅较多js编码指南以及重新阅读了《代码整洁之道》、《重构:改善既有代码的设计》两本经典书籍(强烈建议每隔一段时间看,每次都有新体会),整理出以下几个要点,帮助大家以最小的记忆,重构大部分坏代码。如果想全面了解重构方式,可以看笔者整理的AI Javascript风格指南 (opens new window)

# 坏代码判断

坏代码对每个人、每个项目标准都不一样,但以下几点大概率会是坏代码,需要使用重构方法进行代码重构。

  • 重复代码
  • 过长函数
  • 过大的类
  • 过长参数列表

# 重构方法

# 1. 好的命名

好的命名贯穿整个软件编码过程,好命名包括合理使用大小写定义、缩进等。目前前端工程提供很多lint或format工具,能很方便的帮助工程检测和自动化,不清楚的同学可以看看笔者AI前端工具链 (opens new window)。不管是变量名、函数名或是类名,一个好的命名会加快自身开发效率以及阅读代码效率,毕竟程序读的次数会比写的次数多的多。读github上优秀源码就知道,有时候只要看函数名就知道作者的意图。

# 2. 函数单一职责

软件工程中最重要原则之一。刚毕业不久的开发人员容易出现这个问题,觉得业务逻辑很复杂,没办法再细分成单独函数,写出很长的业务函数。但根据笔者指导小伙伴经验,大多数是临时变量过多,导致看不穿业务逻辑的本质;其实重构过程中一步步分解职责,拆分成细小函数并用恰当的名称命名函数名,能很快理解业务的本质,说不定还能发现潜藏的bug。

# 3. 通过引入解释性变量或函数,使得表达更清晰

# 4. 更少的嵌套,尽早 return

# 5. 以HashMap取代条件表达式

# 其他

实践以上列举的重构方法,能解决项目中大部分的坏代码,但还有许多重构方法,能让你的代码变得干净整洁易于阅读。

  • 清晰的项目目录结构
  • ES6+语法糖
    • destructuring
    • rest
    • Array Methods
    • arrow function
    • 函数默认参数
    • async/await
    • let/const 代替var
  • 常用全部使用const,并字母全部为大写
  • 使用合适的函数名或变量名代替注释
  • 善于利用js中的&& 与 ||
  • 避免‘否定情况’的判断
  • 尽量不写全局函数与变量
  • 采用函数式编程,ES6 Array支持的很好
  • 移除重复的代码
  • 移除注释的代码

# 参考文章

  • clean-code-javascript (opens new window)
  • JavaScript 编码风格指南 (opens new window)
  • Google JavaScript Style Guide (opens new window)
  • The AirBnb JavaScript Style Guide (opens new window)

重构改善既有代码的设计javascript

  • Home
  • My Books
  • Browse ▾

    • Recommendations
    • Choice Awards
    • Genres
    • Giveaways
    • New Releases
    • Lists
    • Explore
    • News & Interviews

    • Art
    • Biography
    • Business
    • Children's
    • Christian
    • Classics
    • Comics
    • Cookbooks
    • Ebooks
    • Fantasy
    • Fiction
    • Graphic Novels
    • Historical Fiction
    • History
    • Horror
    • Memoir
    • Music
    • Mystery
    • Nonfiction
    • Poetry
    • Psychology
    • Romance
    • Science
    • Science Fiction
    • Self Help
    • Sports
    • Thriller
    • Travel
    • Young Adult
    • More Genres

Open Preview

See a Problem?

We’d love your help. Let us know what’s wrong with this preview of 重构 改善既有代码的设计 第2版 平装版 by Martin Fowler.

Thanks for telling us about the problem.

Friend Reviews

To see what your friends thought of this book, please sign up.

Reader Q&A

To ask other readers questions about 重构 改善既有代码的设计 第2版 平装版, please sign up.

Popular Answered Questions

重构改善既有代码的设计javascript

Madhur Ahuja The book examples are in Java not C#. You will still benefit from it. Make sure you have read Gang of four design patterns before reading this book.

Community Reviews

 ·  7,834 ratings  ·  343 reviews

重构改善既有代码的设计javascript

Start your review of 重构 改善既有代码的设计 第2版 平装版

重构改善既有代码的设计javascript

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 littl

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.

...more

重构改善既有代码的设计javascript

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, s

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.

...more

重构改善既有代码的设计javascript

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!
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!
...more

重构改善既有代码的设计javascript

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 continue 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.

...more

重构改善既有代码的设计javascript

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 ref

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.

...more

重构改善既有代码的设计javascript

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

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.

...more

重构改善既有代码的设计javascript

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.

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.

...more

重构改善既有代码的设计javascript

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 machin

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.

...more

重构改善既有代码的设计javascript

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 a 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.

...more

重构改善既有代码的设计javascript

Very pleasant to read! The language is straightforward and clear, plus many examples.

重构改善既有代码的设计javascript

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
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.
...more

重构改善既有代码的设计javascript

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 choic

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.

...more

重构改善既有代码的设计javascript

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

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. :)

...more

重构改善既有代码的设计javascript

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 eve

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.

...more

重构改善既有代码的设计javascript

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

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.

...more

重构改善既有代码的设计javascript

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.

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.

...more

重构改善既有代码的设计javascript

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.

重构改善既有代码的设计javascript

Great introductory book to the topic for people not already nose deep into software design.

重构改善既有代码的设计javascript

It's more like a reference than a book, so it's a bit dry to read. It's more like a reference than a book, so it's a bit dry to read. ...more

重构改善既有代码的设计javascript

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 conven

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.

...more

重构改善既有代码的设计javascript

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 - ma

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 ;-)

...more

重构改善既有代码的设计javascript

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 breakt 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.

...more

重构改善既有代码的设计javascript

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 te

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.

...more

重构改善既有代码的设计javascript

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 develo 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...

...more

重构改善既有代码的设计javascript

Finally finished this, long after the book club for it was over! This is a classic, which means there are both really good pieces of wisdom in here as well as concerns that don't need to be worried about so much anymore with more modern tools and text editors. The majority of the book is kind of a reference of refactoring "recipes" with checklists to go through to make sure you haven't missed something--time will tell if I end up using that reference portion. The descriptions and motivations for Finally finished this, long after the book club for it was over! This is a classic, which means there are both really good pieces of wisdom in here as well as concerns that don't need to be worried about so much anymore with more modern tools and text editors. The majority of the book is kind of a reference of refactoring "recipes" with checklists to go through to make sure you haven't missed something--time will tell if I end up using that reference portion. The descriptions and motivations for performing said refactorings was all good though, since it went through both when you would or wouldn't use something. The main thing I learned was that your code should pretty much constantly be in a state of needing refactoring, since you shouldn't refactor until you know what the next thing you're doing is and it should be the first step. ...more

重构改善既有代码的设计javascript

Good way to end a year!
A must-read reference for every developer, not only ones dealing with legacy code but ones starting new project to save the project on the long-run.

The book is well written, provides samples, examples, diagrams, steps to follow, side-notes, commentary, and basically everything you would need to fully understand a refactoring method.

While the book doesn't provide revolutionary solutions to perform refactoring (you shouldn't perform major refactoring in one step anyway), a l

Good way to end a year!
A must-read reference for every developer, not only ones dealing with legacy code but ones starting new project to save the project on the long-run.

The book is well written, provides samples, examples, diagrams, steps to follow, side-notes, commentary, and basically everything you would need to fully understand a refactoring method.

While the book doesn't provide revolutionary solutions to perform refactoring (you shouldn't perform major refactoring in one step anyway), a lot of the examples are things that any developer would do instinctively, and that's the beauty of it.

The book is organized, so you can easily skip a refactoring method if you are already familiar with it, dig deep into another method which you find interesting to fully understand.

Will definitely get back to it as a reference!

...more

重构改善既有代码的设计javascript

The best programming book I've read in a long time.

There are a lot of design and analysis books but not a lot of programming books. I would gladly read anything from Fowler. It's so simple of a concept but it goes against a lot of 'common sense'. Essentially, don't over design. Don't spend too much time in design and analysis that you've been told to do based on the wrong assumptions of the waterfall model (which never worked).

Kent's book on Test-driven Development is a great companion to this

The best programming book I've read in a long time.

There are a lot of design and analysis books but not a lot of programming books. I would gladly read anything from Fowler. It's so simple of a concept but it goes against a lot of 'common sense'. Essentially, don't over design. Don't spend too much time in design and analysis that you've been told to do based on the wrong assumptions of the waterfall model (which never worked).

Kent's book on Test-driven Development is a great companion to this as you need a strong testing framework to do non-trivial refactorings.

...more

重构改善既有代码的设计javascript

This book can give you a motivation to start refactoring & how to do it the right way.
From my perspective, this book 70% like a catalog to look up when you have a case & need to refactor it.
I can't remember all of the patterns, but I can index it whenever I don't have any idea how to refactor it.
One more thing that around the pattern which covers by this book good focus for OOP than others. I didn't like this point too much.
This book can give you a motivation to start refactoring & how to do it the right way.
From my perspective, this book 70% like a catalog to look up when you have a case & need to refactor it.
I can't remember all of the patterns, but I can index it whenever I don't have any idea how to refactor it.
One more thing that around the pattern which covers by this book good focus for OOP than others. I didn't like this point too much.
...more

重构改善既有代码的设计javascript

You *must* read this book if you are computer programmer and if you are even slightly serious about it. Even if I had picked up most of the ideas from other places, I still learned a great deal from this book.

重构改善既有代码的设计javascript

This book represents one of the building blocks of good programming. Most of the examples are in java, and most of the techniques are already implemented by IDE such as IntelliJ. Still, the ideas can be applied in any programming language, with or without an IDE.

Goodreads is hiring!

If you like books and love to build cool products, we may be looking for you.
Learn more »

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. 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. ...more

Other books in the series

News & Interviews

重构改善既有代码的设计javascript

  Here at Goodreads World Headquarters, we are—rather predictably—in the habit of giving books as gifts. To family. To friends....

“I’m not a great programmer; I’m just a good programmer with great habits.” — 21 likes

“Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.” — 11 likes

More quotes…

Welcome back. Just a moment while we sign you in to your Goodreads account.

重构改善既有代码的设计javascript