目 录Chapter 1: CleanCode(新增评注47条) 1There Will BeCode 2BadCode 3The Total Cost ofOwning a Mess 5The Grand Redesign inthe Sky 6Attitude 6The PrimalConundrum 7The Art of CleanCode? 8What Is CleanCode? 9Schools ofThought 15We AreAuthors 17The Boy ScoutRule 18Prequel andPrinciples 18Conclusion 18Bibliography 19Chapter 2: MeaningfulNames(新增评注19条) 21Introduction 21Use Intention-RevealingNames 22AvoidDisinformation 24Make MeaningfulDistinctions 25Use PronounceableNames 26Use SearchableNames 27AvoidEncodings 28HungarianNotation 28MemberPrefixes 29Interfaces andImplementations 29Avoid MentalMapping 30ClassNames 30MethodNames 30Don’t Be Cute31Pick One Word perConcept 32Don’tPun 32Use Solution DomainNames 33Use Problem DomainNames 33Add MeaningfulContext 33Don’t Add GratuitousContext 35FinalWords 36Chapter 3:Functions(新增评注25条) 39Small! 42Blocks andIndenting 43Do One Thing44Sections withinFunctions 45One Level ofAbstraction per Function 45Reading Code from Topto Bottom:The StepdownRule 46SwitchStatements 46Use DescriptiveNames 48FunctionArguments 49Common MonadicForms 50FlagArguments 50DyadicFunctions 51Triads 52ArgumentObjects 52ArgumentLists 52Verbs andKeywords 53Have No SideEffects 53OutputArguments 54Command QuerySeparation 55Prefer Exceptions toReturning Error Codes 56Extract Try/CatchBlocks 57Error Handling Is OneThing 57The Error.javaDependency Magnet 57Don’t RepeatYourself 58StructuredProgramming 59How Do You WriteFunctions Like This? 59Conclusion 60SetupTeardownIncluder 60Bibliography 62Chapter 4:Comments(新增评注18条) 65Comments Do Not Make Upfor Bad Code 67Explain Yourself inCode 68GoodComments 68LegalComments 68InformativeComments 69Explanation ofIntent 69Clarification 70Warning ofConsequences 71TODOComments 71Amplification72Javadocs in Public APIs72BadComments 72Mumbling 73RedundantComments 73MisleadingComments 76MandatedComments 76JournalComments 77NoiseComments 78ScaryNoise 80Don’t Use a CommentWhen You Can Use a Function oraVariable 80PositionMarkers 80Closing BraceComments 81Attributions andBylines 82Commented-OutCode 82HTMLComments 83NonlocalInformation 83Too MuchInformation 84InobviousConnection 84FunctionHeaders 84Javadocs in NonpublicCode 85Example 85Bibliography 88Chapter 5:Formatting(新增评注13条) 89The Purpose ofFormatting 90Vertical Formatting90The NewspaperMetaphor 91Vertical OpennessBetween Concepts 92VerticalDensity 93VerticalDistance 94VerticalOrdering 99HorizontalFormatting 99Horizontal Openness andDensity 100HorizontalAlignment 101Indentation 103DummyScopes 104TeamRules 105Uncle Bob’s FormattingRules 106Chapter 6: Objects andData Structures(新增评注12条) 109DataAbstraction 110Data/ObjectAnti-Symmetry 111The Law ofDemeter 114TrainWrecks 115Hybrids 116HidingStructure 116Data TransferObjects 117Active Record118Conclusion 118Bibliography 119Chapter 7: ErrorHandling(新增评注7条) 121Use Exceptions RatherThan Return Codes 122Write YourTry-Catch-Finally StatementFirst 123Use UncheckedExceptions 125Provide Context withExceptions 126Define ExceptionClasses in Terms of a Caller’sNeeds 126Define the NormalFlow 128Don’t ReturnNull 129Don’t PassNull 130Conclusion 131Bibliography 131Chapter 8:Boundaries(新增评注6条) 133Using Third-Party Code134Exploring and LearningBoundaries 136Learninglog4j 137Learning Tests AreBetter Than Free 138Using Code That DoesNot Yet Exist 139CleanBoundaries 140Bibliography 141Chapter 9: UnitTests(新增评注13条) 143The Three Laws of TDD144Keeping TestsClean 145Tests Enable the-ilities 146CleanTests 147Domain-Specific TestingLanguage 150A DualStandard 150One Assert per Test153Single Concept perTest 154F.I.R.S.T. 155Conclusion 156Bibliography 156Chapter 10:Classes(新增评注12条) 157ClassOrganization 158Encapsulation158Classes Should BeSmall! 158The SingleResponsibility Principle 161Cohesion 162Maintaining CohesionResults in Many Small Classes 163Organizing forChange 169Isolating fromChange 172Bibliography 174Chapter 11:Systems(新增评注10条) 175How Would You Build aCity? 176Separate Constructing aSystem from Using It 176Separation of Main178Factories178DependencyInjection 179ScalingUp 180Cross-CuttingConcerns 183JavaProxies 184Pure Java AOPFrameworks 186AspectJAspects 189Test Drive the SystemArchitecture 190Optimize DecisionMaking 191Use Standards Wisely,When They Add DemonstrableValue 191Systems NeedDomain-Specific Languages 191Conclusion 192Bibliography 192Chapter 12:Emergence(新增评注5条) 195Getting Clean viaEmergent Design 195Simple Design Rule 1:Runs All the Tests 196Simple Design Rules2–4: Refactoring 196NoDuplication 197Expressive 199Minimal Classes andMethods 200Conclusion 201Bibliography 201Chapter 13:Concurrency(新增评注15条) 203Why Concurrency?204Myths andMisconceptions 205Challenges 206Concurrency DefensePrinciples 207Single ResponsibilityPrinciple 207Corollary: Limit theScope of Data 207Corollary: Use Copiesof Data 208Corollary: ThreadsShould Be as Independent as Possible 208Know YourLibrary 209Thread-Safe Collections209Know Your ExecutionModels 210Producer-Consumer 210Readers-Writers 211DiningPhilosophers 211Beware DependenciesBetween SynchronizedMethods 212Keep SynchronizedSections Small 212Writing CorrectShut-Down Code Is Hard 212Testing ThreadedCode 213Treat Spurious Failuresas Candidate Threading Issues 214Get Your NonthreadedCode Working First 214Make Your Threaded CodePluggable 214Make Your Threaded CodeTunable 215Run with More ThreadsThan Processors 215Run on DifferentPlatforms 215Instrument Your Code toTry and Force Failures 215Hand-Coded 216Automated 217Conclusion 218Bibliography 219Chapter 14: SuccessiveRefinement(新增评注18条) 221ArgsImplementation 223How Did I DoThis? 228Args: The RoughDraft 229So IStopped 240On Incrementalism241StringArguments 243Conclusion 280关于第15章、第16章和第17章 281Chapter 15: JUnitInternals 283The JUnitFramework 284Conclusion 297Chapter 16: RefactoringSerialDate 299First, Make ItWork 300Then Make ItRight 302Conclusion 316Bibliography 316Chapter 17: Smells andHeuristics 317Comments 318C1: InappropriateInformation 318C2: ObsoleteComment 318C3: RedundantComment 318C4: Poorly WrittenComment 319C5: Commented-OutCode 319Environment 319E1: Build Requires MoreThan One Step 319E2: Tests Require MoreThan One Step 319Functions 320F1: Too ManyArguments 320F2: OutputArguments 320F3: FlagArguments 320F4: DeadFunction 320General 320G1: Multiple Languagesin One Source File 320G2: Obvious Behavior IsUnimplemented 320G3: Incorrect Behaviorat the Boundaries 321G4: Overridden Safeties321G5:Duplication 321G6: Code at Wrong Levelof Abstraction 322G7: Base ClassesDepending on TheirDerivatives 323G8: Too MuchInformation 324G9: DeadCode 324G10: VerticalSeparation 324G11: Inconsistency324G12:Clutter 325G13: ArtificialCoupling 325G14: Feature Envy325G15: SelectorArguments 326G16: ObscuredIntent 327G17: MisplacedResponsibility 328G18: InappropriateStatic 328G19: Use ExplanatoryVariables 329G20: Function NamesShould Say What TheyDo 329G21: Understand theAlgorithm 330G22: Make LogicalDependencies Physical 330G23: PreferPolymorphism to If/Else or Switch/Case 331G24: Follow StandardConventions 332G25: Replace MagicNumbers with Named Constants 332G26: BePrecise 333G27: Structure overConvention 333G28: EncapsulateConditionals 334G29: Avoid NegativeConditionals 334G30: Functions ShouldDo One Thing 334G31: Hidden TemporalCouplings 335G32: Don’t BeArbitrary 336G33: EncapsulateBoundaryConditions 336G34: Functions ShouldDescend Only One Level of Abstraction 337G35: Keep ConfigurableData at High Levels 338G36: Avoid TransitiveNavigation 339Java 339J1: Avoid Long ImportLists by Using Wildcards 339J2: Don’t InheritConstants 340J3: Constants versusEnums 341Names 342N1: Choose DescriptiveNames 342N2: Choose Names at theAppropriate Level of Abstraction 343N3: Use StandardNomenclature Where Possible 344N4: UnambiguousNames 344N5: Use Long Names forLong Scopes 345N6: AvoidEncodings 345N7: Names ShouldDescribe Side-Effects 345Tests 346T1: InsufficientTests 346T2: Use a CoverageTool 346T3: Don’t Skip TrivialTests 346T4: An Ignored Test Isa Question about anAmbiguity 346T5: Test BoundaryConditions 346T6: Exhaustively TestNear Bugs 346T7: Patterns of FailureAre Revealing 347T8: Test CoveragePatterns Can BeRevealing 347T9: Tests Should BeFast 347Conclusion 347Bibliography 347Appendix A: ConcurrencyII 349Client/ServerExample 349TheServer 349AddingThreading 351ServerObservations 351Conclusion 353Possible Paths ofExecution 353Number ofPaths 354DiggingDeeper 355Conclusion 358Knowing YourLibrary 359ExecutorFramework 359NonblockingSolutions 359Nonthread-SafeClasses 361Dependencies BetweenMethods Can Break ConcurrentCode 362Tolerate the Failure363Client-BasedLocking 363Server-Based Locking 365IncreasingThroughput 366Single-ThreadCalculation of Throughput 367Multithread Calculationof Throughput 367Deadlock 368MutualExclusion 369Lock &Wait 369NoPreemption 369CircularWait 370Breaking MutualExclusion 370Breaking Lock &Wait 370BreakingPreemption 371Breaking CircularWait 371Testing MultithreadedCode 372Tool Support forTesting Thread-BasedCode 374Conclusion 375Tutorial: Full CodeExamples 375Client/ServerNonthreaded 375Client/Server UsingThreads 379Appendix B:org.jfree.date.SerialDate 381Appendix C: CrossReferences of Heuristics 441Epilogue 445