100% found this document useful (1 vote)
557 views

Refactoring_ Improving the Design of Existing Code 2nd Edition Martin Fowler All Chapters Instant Download

Martin

Uploaded by

silisostin6w
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
557 views

Refactoring_ Improving the Design of Existing Code 2nd Edition Martin Fowler All Chapters Instant Download

Martin

Uploaded by

silisostin6w
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Get ebook downloads in full at ebookmeta.

com

Refactoring_ Improving the Design of Existing Code


2nd Edition Martin Fowler

https://ebookmeta.com/product/refactoring_-improving-the-
design-of-existing-code-2nd-edition-martin-fowler/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Refactoring Improving the Design of Existing Code 2nd


Edition Martin Fowler

https://ebookmeta.com/product/refactoring-improving-the-design-of-
existing-code-2nd-edition-martin-fowler/

ebookmeta.com

2018 International Existing Building Code 1st Edition


International Code Council

https://ebookmeta.com/product/2018-international-existing-building-
code-1st-edition-international-code-council/

ebookmeta.com

International Existing Building Code (International Code


Council Series) 2018 1st Edition International Code
Council
https://ebookmeta.com/product/international-existing-building-code-
international-code-council-series-2018-1st-edition-international-code-
council/
ebookmeta.com

The Polish Navy 1918 45 From the Polish Soviet War to


World War II 1st Edition Przemys■aw Budzbon Paul Wright
Illustrator
https://ebookmeta.com/product/the-polish-navy-1918-45-from-the-polish-
soviet-war-to-world-war-ii-1st-edition-przemyslaw-budzbon-paul-wright-
illustrator/
ebookmeta.com
Ask Alice 1st Edition Kell Frillman

https://ebookmeta.com/product/ask-alice-1st-edition-kell-frillman/

ebookmeta.com

Foundations of Celestial Mechanics 1st Edition Elena


Bannikova

https://ebookmeta.com/product/foundations-of-celestial-mechanics-1st-
edition-elena-bannikova/

ebookmeta.com

Reason in the Service of Faith 1st Edition Paul Helm

https://ebookmeta.com/product/reason-in-the-service-of-faith-1st-
edition-paul-helm/

ebookmeta.com

Strictly Pleasure 1st Edition Carrie Elks

https://ebookmeta.com/product/strictly-pleasure-1st-edition-carrie-
elks/

ebookmeta.com

Brighter Stars Special Edition Logan Kelly

https://ebookmeta.com/product/brighter-stars-special-edition-logan-
kelly/

ebookmeta.com
Louis I Kahn The Nordic Latitudes Fay Jones Collaborative
Series 1st Edition Per Olaf Fjeld

https://ebookmeta.com/product/louis-i-kahn-the-nordic-latitudes-fay-
jones-collaborative-series-1st-edition-per-olaf-fjeld/

ebookmeta.com
List of Refactorings
Change Function Declaration (124) Remove Flag Argument (314)
Change Reference to Value (252) Remove Middle Man (192)
Change Value to Reference (256) Remove Setting Method (331)
Collapse Hierarchy (380) Remove Subclass (369)
Combine Functions into Class (144) Rename Field (244)
Combine Functions into Transform Rename Variable (137)
(149) Replace Command with Function
Consolidate Conditional Expression (344)
(263) Replace Conditional with
Decompose Conditional (260) Polymorphism (272)
Encapsulate Collection (170) Replace Constructor with Factory
Encapsulate Record (162) Function (334)
Encapsulate Variable (132) Replace Derived Variable with Query
Extract Class (182) (248)
Extract Function (106) Replace Function with Command
Extract Superclass (375) (337)
Extract Variable (119) Replace Inline Code with Function
Hide Delegate (189) Call (222)
Inline Class (186) Replace Loop with Pipeline (231)
Inline Function (115) Replace Nested Conditional with
Inline Variable (123) Guard Clauses (266)
Introduce Assertion (302) Replace Parameter with Query (324)
Introduce Parameter Object (140) Replace Primitive with Object (174)
Introduce Special Case (289) Replace Query with Parameter (327)
Move Field (207) Replace Subclass with Delegate (381)
Move Function (198) Replace Superclass with Delegate
Move Statements into Function (213) (399)
Move Statements to Callers (217) Replace Temp with Query (178)
Parameterize Function (310) Replace Type Code with Subclasses
Preserve Whole Object (319) (362)
Pull Up Constructor Body (355) Separate Query from Modifier (306)
Pull Up Field (353) Slide Statements (223)
Pull Up Method (350) Split Loop (227)
Push Down Field (361) Split Phase (154)
Push Down Method (359) Split Variable (240)
Remove Dead Code (237) Substitute Algorithm (195)
Refactoring
Second Edition
Pearson Addison-Wesley
Signature Series

Visit informit.com/awss for a complete list of available publications.

T he Pearson Addison-Wesley Signature Series provides readers


with practical and authoritative information on the latest trends in
modern technology for computer professionals. The series is based on
one simple premise: great books come from great authors.

Books in the Martin Fowler Signature Series are personally chosen


by Fowler, and his signature ensures that he has worked closely with
authors to define topic coverage, book scope, critical content, and
overall uniqueness. The expert signatures also symbolize a promise to
our readers: you are reading a future classic.

Make sure to connect with us!


informit.com/socialconnect
Refactoring
Improving the Design of Existing Code

Second Edition

Martin Fowler
with contributions by Kent Beck

Boston • Columbus • New York • San Francisco • Amsterdam • Cape Town


Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
São Paulo • Sydney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in this book, and the publisher
was aware of a trademark claim, the designations have been printed with initial capital
letters or in all capitals.

The author and publisher have taken care in the preparation of this book, but make no
expressed or implied warranty of any kind and assume no responsibility for errors or
omissions. No liability is assumed for incidental or consequential damages in connection
with or arising out of the use of the information or programs contained herein.

For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to
your business, training goals, marketing focus, or branding interests), please contact our
corporate sales department at corpsales@pearsoned.com or (800) 382–3419.

For government sales inquiries, please contact governmentsales@pearsoned.com.

For questions about sales outside the U.S., please contact intlcs@pearson.com.

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2018950015

Copyright © 2019 Pearson Education, Inc.

Cover photo: Waldo-Hancock Bridge & Penobscot Narrows Bridge by Martin Fowler
Lightbulb graphic: Irina Adamovich/Shutterstock

All rights reserved. Printed in the United States of America. This publication is protected
by copyright, and permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the Pearson Education
Global Rights & Permissions Department, please visit www.pearsoned.com/permissions/.

ISBN-13: 978-0-13-475759-9
ISBN-10: 0-13-475759-9

1 18
For Cindy
—Martin
This page intentionally left blank
Contents

Foreword to the First Edition ..................................................................... xi


Preface ...................................................................................................... xiii

Chapter 1: Refactoring: A First Example ........................................................... 1


The Starting Point ........................................................................................ 1
Comments on the Starting Program .......................................................... 3
The First Step in Refactoring ....................................................................... 5
Decomposing the statement Function ............................................................ 6
Status: Lots of Nested Functions .............................................................. 22
Splitting the Phases of Calculation and Formatting ............................... 24
Status: Separated into Two Files (and Phases) ....................................... 31
Reorganizing the Calculations by Type ................................................... 34
Status: Creating the Data with the Polymorphic Calculator ................. 41
Final Thoughts ............................................................................................ 43

Chapter 2: Principles in Refactoring ................................................................ 45


Defining Refactoring .................................................................................. 45
The Two Hats ............................................................................................. 46
Why Should We Refactor? ........................................................................ 47
When Should We Refactor? ...................................................................... 50
Problems with Refactoring ........................................................................ 55
Refactoring, Architecture, and Yagni ....................................................... 62
Refactoring and the Wider Software Development Process ................. 63
Refactoring and Performance .................................................................... 64
Where Did Refactoring Come From? ....................................................... 67
Automated Refactorings ............................................................................ 68
Going Further ............................................................................................. 70

vii
viii Contents

Chapter 3: Bad Smells in Code ......................................................................... 71


Mysterious Name ........................................................................................ 72
Duplicated Code ......................................................................................... 72
Long Function ............................................................................................. 73
Long Parameter List ................................................................................... 74
Global Data ................................................................................................. 74
Mutable Data .............................................................................................. 75
Divergent Change ...................................................................................... 76
Shotgun Surgery ......................................................................................... 76
Feature Envy ............................................................................................... 77
Data Clumps ............................................................................................... 78
Primitive Obsession ................................................................................... 78
Repeated Switches ...................................................................................... 79
Loops ........................................................................................................... 79
Lazy Element .............................................................................................. 80
Speculative Generality ............................................................................... 80
Temporary Field ......................................................................................... 80
Message Chains .......................................................................................... 81
Middle Man ................................................................................................. 81
Insider Trading ........................................................................................... 82
Large Class .................................................................................................. 82
Alternative Classes with Different Interfaces .......................................... 83
Data Class ................................................................................................... 83
Refused Bequest ......................................................................................... 83
Comments ................................................................................................... 84

Chapter 4: Building Tests .................................................................................. 85


The Value of Self-Testing Code ................................................................ 85
Sample Code to Test .................................................................................. 87
A First Test .................................................................................................. 90
Add Another Test ....................................................................................... 93
Modifying the Fixture ................................................................................ 95
Probing the Boundaries ............................................................................. 96
Much More Than This ............................................................................... 99

Chapter 5: Introducing the Catalog ............................................................... 101


Format of the Refactorings ...................................................................... 101
The Choice of Refactorings ..................................................................... 102
Contents ix

Chapter 6: A First Set of Refactorings ........................................................... 105


Extract Function ....................................................................................... 106
Inline Function ......................................................................................... 115
Extract Variable ........................................................................................ 119
Inline Variable .......................................................................................... 123
Change Function Declaration ................................................................. 124
Encapsulate Variable ................................................................................ 132
Rename Variable ...................................................................................... 137
Introduce Parameter Object .................................................................... 140
Combine Functions into Class ................................................................ 144
Combine Functions into Transform ....................................................... 149
Split Phase ................................................................................................ 154

Chapter 7: Encapsulation ................................................................................ 161


Encapsulate Record .................................................................................. 162
Encapsulate Collection ............................................................................ 170
Replace Primitive with Object ................................................................ 174
Replace Temp with Query ...................................................................... 178
Extract Class ............................................................................................. 182
Inline Class ............................................................................................... 186
Hide Delegate ........................................................................................... 189
Remove Middle Man ............................................................................... 192
Substitute Algorithm ................................................................................ 195

Chapter 8: Moving Features ............................................................................ 197


Move Function .......................................................................................... 198
Move Field ................................................................................................ 207
Move Statements into Function .............................................................. 213
Move Statements to Callers .................................................................... 217
Replace Inline Code with Function Call ............................................... 222
Slide Statements ....................................................................................... 223
Split Loop .................................................................................................. 227
Replace Loop with Pipeline .................................................................... 231
Remove Dead Code ................................................................................. 237

Chapter 9: Organizing Data ............................................................................ 239


Split Variable ............................................................................................ 240
Rename Field ............................................................................................ 244
Replace Derived Variable with Query ................................................... 248
x Contents

Change Reference to Value .................................................................... 252


Change Value to Reference .................................................................... 256

Chapter 10: Simplifying Conditional Logic ................................................... 259


Decompose Conditional .......................................................................... 260
Consolidate Conditional Expression ...................................................... 263
Replace Nested Conditional with Guard Clauses ................................ 266
Replace Conditional with Polymorphism .............................................. 272
Introduce Special Case ............................................................................ 289
Introduce Assertion .................................................................................. 302

Chapter 11: Refactoring APIs ......................................................................... 305


Separate Query from Modifier ................................................................ 306
Parameterize Function ............................................................................. 310
Remove Flag Argument ........................................................................... 314
Preserve Whole Object ............................................................................ 319
Replace Parameter with Query ............................................................... 324
Replace Query with Parameter ............................................................... 327
Remove Setting Method .......................................................................... 331
Replace Constructor with Factory Function .......................................... 334
Replace Function with Command .......................................................... 337
Replace Command with Function .......................................................... 344

Chapter 12: Dealing with Inheritance ........................................................... 349


Pull Up Method ........................................................................................ 350
Pull Up Field ............................................................................................. 353
Pull Up Constructor Body ....................................................................... 355
Push Down Method ................................................................................. 359
Push Down Field ...................................................................................... 361
Replace Type Code with Subclasses ...................................................... 362
Remove Subclass ...................................................................................... 369
Extract Superclass .................................................................................... 375
Collapse Hierarchy ................................................................................... 380
Replace Subclass with Delegate ............................................................. 381
Replace Superclass with Delegate .......................................................... 399

Bibliography ............................................................................................. 405


Index .......................................................................................................... 409
Foreword to the First Edition

“Refactoring” was conceived in Smalltalk circles, but it wasn’t long before it found
its way into other programming language camps. Because refactoring is integral
to framework development, the term comes up quickly when “frameworkers” talk
about their craft. It comes up when they refine their class hierarchies and when
they rave about how many lines of code they were able to delete. Frameworkers
know that a framework won’t be right the first time around—it must evolve as
they gain experience. They also know that the code will be read and modified
more frequently than it will be written. The key to keeping code readable and
modifiable is refactoring—for frameworks, in particular, but also for software in
general.
So, what’s the problem? Simply this: Refactoring is risky. It requires changes
to working code that can introduce subtle bugs. Refactoring, if not done properly,
can set you back days, even weeks. And refactoring becomes riskier when prac-
ticed informally or ad hoc. You start digging in the code. Soon you discover new
opportunities for change, and you dig deeper. The more you dig, the more stuff
you turn up. . .and the more changes you make. Eventually you dig yourself into
a hole you can’t get out of. To avoid digging your own grave, refactoring must
be done systematically. When my coauthors and I wrote Design Patterns, we
mentioned that design patterns provide targets for refactorings. However, identi-
fying the target is only one part of the problem; transforming your code so that
you get there is another challenge.
Martin Fowler and the contributing authors make an invaluable contribution
to object-oriented software development by shedding light on the refactoring
process. This book explains the principles and best practices of refactoring, and
points out when and where you should start digging in your code to improve it.
At the book’s core is a comprehensive catalog of refactorings. Each refactoring
describes the motivation and mechanics of a proven code transformation. Some
of the refactorings, such as Extract Method or Move Field, may seem obvious.
But don’t be fooled. Understanding the mechanics of such refactorings is the
key to refactoring in a disciplined way. The refactorings in this book will help
you change your code one small step at a time, thus reducing the risks of evolving

xi
xii Foreword to the First Edition

your design. You will quickly add these refactorings and their names to your
development vocabulary.
My first experience with disciplined, “one step at a time” refactoring was when
I was pair-programming at 30,000 feet with Kent Beck. He made sure that we
applied refactorings from this book’s catalog one step at a time. I was amazed at
how well this practice worked. Not only did my confidence in the resulting code
increase, I also felt less stressed. I highly recommend you try these refactorings:
You and your code will feel much better for it.

— Erich Gamma, Object Technology International, Inc.


January 1999
Preface

Once upon a time, a consultant made a visit to a development project in order


to look at some of the code that had been written. As he wandered through the
class hierarchy at the center of the system, the consultant found it rather messy.
The higher-level classes made certain assumptions about how the classes would
work—assumptions that were embodied in inherited code. That code didn’t suit
all the subclasses, however, and was overridden quite heavily. Slight modifications
to the superclass would have greatly reduced the need to override it. In other
places, an intention of the superclass had not been properly understood, and
behavior present in the superclass was duplicated. In yet other places, several
subclasses did the same thing with code that could clearly be moved up the
hierarchy.
The consultant recommended to the project management that the code be
looked at and cleaned up—but the project management wasn’t enthusiastic.
The code seemed to work and there were considerable schedule pressures. The
managers said they would get around to it at some later point.
The consultant had also shown what was going on to the programmers working
on the hierarchy. The programmers were keen and saw the problem. They knew
that it wasn’t really their fault; sometimes, a new pair of eyes is needed to spot
the problem. So the programmers spent a day or two cleaning up the hierarchy.
When finished, they had removed half the code in the hierarchy without reducing
its functionality. They were pleased with the result and found that it became
quicker and easier both to add new classes and to use the classes in the rest of
the system.
The project management was not pleased. Schedules were tight and there was
a lot of work to do. These two programmers had spent two days doing work that
added nothing to the many features the system had to deliver in a few months’
time. The old code had worked just fine. Yes, the design was a bit more “pure”
and a bit more “clean.” But the project had to ship code that worked, not code
that would please an academic. The consultant suggested that a similar cleanup
should be done on other central parts of the system, which might halt the project

xiii
Other documents randomly have
different content
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.

You might also like