重构,改善既有代码

《重构:改善既有代码的设计》读书笔记

(2013-05-12 09:08:09)
  

---- 2013-05-12 09:08:09  ----

 

Chapter1:

1、fun太长,分割到其他类。

2、当需要给一段代码写注释时,往往可以把这段代码提取成一个fun。

3、少写重复代码。

4、多内聚,if can,把fun搬到该属于的类中。(大多数情况下,方法应该被移动到那些属性被使用的类中)

5、当需要给某段程序添加代码,感觉比较难添加时,先重构该程序使之易添加,再添加该代码。

6、重构前先建立测试环境,自检单元测试。

7、提取函数时,关注其内的变量,值不变的函数可以传进来,值变化的变量须格外关注。

8、重构须审慎小步进行,这样犯错的时候就容易发现。

9、好的代码需要清晰地传达她在做什么,而变量的命名是个关键因素。

10、傻瓜写的代码只有计算机看得懂,好的工程师写的代码人类看的懂。

 

----  2013-05-1922:00:00  ----

 

1、优先使用对象组合而不是继承

 

2、一般建议构造函数中不包含太多逻辑


3、要投入时间和精力保持代码整洁、敞亮。

 

4、DRY原则: 系统中的每一项知识都必须具有单一、无歧义、权威的表示。

 

5、开发人员应该遵守人人为我,我为人人的黄金法则。

 

---- 2013-05-26 22:00:00  ----


1、解决可读性差:能够清晰表达意图的好的命名;细粒度的方法;遵循单一职责原则的类;清晰的结构与模块的关系。

2、解决逻辑重复:遵循 DRY原则;合理利用封装;

3、解决添加困难:遵循开放封闭(OCP)原则:对扩展开放,对修改封闭。

4、解决复杂条件逻辑:封装或分解分支;以多态替代条件分支;好的方法命名。

 

---- 2013-05-27 22:00:00  ----

 

1、接近项目晚期的时候不要重构,在那个点,往往利大于弊。

 

2、一旦你公开一个接口,你就不再可以安全地使用它了,还有编辑他的调用者。
    Do notpublish interfaces prematurely.Modify your code ownership policiesto smooth refactoring.

 

3、Good programmers certainly have spent at least some timecleaning up their code.

 

---- 2013-05-28 22:00:00  ----

 

1、重复代码->长方法->大类->过长参数


2、If you have a good look at me for a method you do not need tolook the body.


3、清晰代码的要诀就是保持方法的短小,以及能清晰表达意图的方法名。


4、方法名表达意图而不是做了什么


5、we fell the need to comment something, we write a methodinstead.Such a method contains the code that was commented but idnamed after the intention of the code rather than how it doesit.(根据代码的用途而非实现来命名,

 

6、好的方法名应该从调用者的角度来考虑,接口类似)

 

7、方法参数太多时,往往可以通过Replace Temp with Query来减少,实在不行再考虑Replace methodwith Method Object

 

8、单一职责原则要求,就一个类而言,应该只专注于做一件事和仅有一个引起变化的原因。

唯有专注,才能保证对象的高内聚;唯有单一,才能保证对象的细粒度。

When you feel the need to write a comment, first try to refactorthe code so that any comment becomes superfluous.

 

---- 2013-05-29 22:00:00  ----


Chapter 6 Composing Methods


1、Extract Method 抽取方法 -> You have a code fragmentthat can be grouped togeter.(Turn the fragment into a method whosename explains the purpose of the method)

 

2、Inline Method 内联方法 -> A method's body is justas clear as its name.(Put the mothod's body into the body of itscallers and remove the mothod)

 

3、InLine Temp 内联临时变量。 ->You have a temp that isassigned to once with a simple expression, and the temp is gettingin the way of other refactorings.(Replace all references to thattemp with the expression.)

 

4、Replace Temp with Query。用查询代替局部变量->You areusing a temporary variable to hold the result of anexpression.(Extract the expression into a method.Replace allrefrences to the temp with the new method.The new method can thenbe used in other methods.)
   Replace Tempwith Query often is a vital step before Extract Method.Localvariables make it difficult to extract, so replace as manyvariables as you can with queries.
(如果query method返回的结果每一次都不尽相同,则需要用临时变量保存querymethod的值,而不是任其被调用几次)

 

 

5、Introduce Explaining Variable 用解释型变量替换复杂表达式->You have a complicated expression,(Put the result of theexpression, or parts of the expression, in a temporary variablewith a name that explains the purpose)

 

 

6、Split Temporary Variable 分离变量-> You have atemporary Valiable assigned to more than once, but is not a loopvariable nor a collecting temporary variable.(Make a separatetemporary for each assignment)

 

 

7、Remove Assignments to Parameters 消除直接修改入参。 ->The code assigns to a parameter.(Use a temporary bariableinstead)

 

 

8、Replace Method with Method Object.用方法对象代替方法。 You have a longmethod that uses local variables in such a way that you cannotapply Extract Mehod.(Turn the method into its own object so thatall the local variables become fields on that object.You can thendecompose the method into other methods on the same object)

 

 

9、Substitute Algorithm.优化内部算法 -> You want toreplace algorithm with one that is clearer.(Replace the body of themethod with the new algorithm)

 

 ---- 2013-06-02 22:23:00  ----


Chapter 7 Moving Fratures Between Objects

 

Often classes becoe bloated with too many responsibilities.Inthis case I use Extract Class to separate some of theseresponsiblities.

 

1、Move method. 移动类方法-> A method is, or will be,using or used by more features of another class than on which it isdefined.(Create a new method with a similar body in the class ituses most.Either turn the old method into a
               simple delegation, or remove italtogether.(当类A中的一个方法接收类B的一个对象最为输入参数,并主要对其进行操作时,就需要考虑是否
        需要将该方法移动到类B中。)

 

2、Move Field.移动类属性 -> A feild is, or will be,used by another class more than the class on which it isdefined.(Create a new field in the target class, and change all itsuser)

 

3、Extract Class. 提取类-> You have one class doingwork that should be done by two.(Create a new class and move therelevantfields and methods from the old class into the newclass)
   When to split class-> A good sign is that a subset of the data and asubset of the methods seem to go together.Ohter good signs aresubsets of data that usually change together or are
   particularly dependent on eachother.)

 

4、Inline Class. 内联类(同上反) -> A class is not doingvery much.(Move all its features into another class and deleteit)
  采用此重构方法时,需要考虑被inline的类,被inline的类应该是粒度小的对象。

 

5、Hide Delegate. 隐藏委托 -> A client is calling adelegate class of an object.(Create methods on the server to hidethe delegate)

 

6、Remove Middle Man. 消除中间人(同上反) -> A class isdoing too much simple delegation.(Get the client to call thedelegate directly)

 

7、Introduce Foreign Method. 引入外函数 -> A serverclass you are using needs an additional method, but you can notmodify the class.(Create
   a method int the client withan instance of the server class as its first argument)

 

 

 ---- 2013-06-10 14:11:00  ----

 

 Chapter 8 Organizing Data

1、Self Encapsulate Field 自封装属性 -> You areaccessing a field directly, but the coupling to the field isbecoming awkward.(Create getting and setting methods for the fieldand use only
   those to access the field)

 

2、Replace Data Value with Object. 用对象代替数据值 -> Youhave a data item that needs additional data or behavior.(Turn thedata item into an object)

 

3、Change Value toReference.修改值为引用[新建的可以是同一个对象](用一个容器HashTable)保存值,新建时有的直接里面取)-> You hava a class with many equal instances thatyou want to replace with a single object.(Turn the object into areference object)
(Reference objects are things like customer or account. Each objectstands for one object in the real world, and you use the objectidentity to test whether they are equal.
Value objects are things like date or money. They are definedentirely through their data values.系统中可能有多个这样的值,如“2013.06.10”,所以你需要写equals 方法和HashCode)

 

4、Change Reference to Value.修改引用为值[新建的是不同对象] ->You have a reference object that is small, immutable, and awkwardto manage. (Turn it into a value object)

 

5、Replace Array withObject.用对象代替数组(里面不是同类型的数据)->You hava an array inwhich certain elements mean different things.(Replace the arraywith an object that has a field for each element)

 

6、Duplicate Observed Data.重复的被观察数据 -> You havadomain data available only in a GUI control, and domain methodsneed access.(Copy the data to a domain object. Set up an observerto synchronize the two pieces of data)
   可以用观察者模式或者监听法实现数据同步更新。

 

7、Change Unidirectional Association to Bidirectional.改变单向关系为双向-> You have two classes that need to use eachother's features, but there is only a one-way link.

 

8、Change Bidirectional Association to Unidirectional.改变双向关系为单向-> You have a two-way association but one class nolonger needs features from the other.(Drop the unneeded end of theassociation)

 

9、Replace Magic Number with Symbolic Constant. 用常量代替魔鬼名字

 

10、Encapsulate Field. 封装属性。-> There is a publicfield.(Make it private and provide accessors)

 

 11、Encapsulate Collection.封装集合(原来的返回集合get方法改为不可修改,使用Collections.unmodifiable,然后添加方法专门用来修改集合元素)。-> A method returns a collection.(Make it return aread-only view and provide add/remove methods)

 

 ----  2013-06-1110:31:00  ----

 

1、Replace Record with Data Class. 用数据类替换记录 -> Youneed to interface with a record structure in a traditionalprogramming environment.(Make a dumb object for the record.)

 

2、Replace Type Code with Class.用类替换类型编码(这条没用, 枚举就可以搞定)-> A class has a numeric type code that does notaffect its behavior.(Replace the number awith a new class)

 

3、Replace Type Code with Subclasses. 用子类代替类型编码.-> You have an immutable type code affects thebehavior of a class.(Replace the type code with subclasses)

 

4、Replace Type Code with State / Strategy.用状态模式代替类型编码 You have atype code that affects the behavior of a class, but you cannot usesubclassing.

 

5、Replace Subclass with Fields.用属性代替子类. -> Youhave subclasses that vary only in methods that return constantsdata.(Change the methods to superclass fields and eliminate thesubclasses)

 

6、Replace Conditional with Polymorphism 用多态替换条件表达式-> You have a conditional that chooses differentbehavior depending on the type
   of an object.(Move each leg ofthe conditional to an overriding method in a subclass. Make theoriginal method abstract)

 

 

7、Introduce null Object 引入空对象 -> You haverepeated checks for a null value.(Replace the null value with anull object)

 

 

8、Other Special Cases (如NAN)

 

 

9、Introduce Assertion. 引入断言 -> A section of codeassumes something about the state of the program(Make theassumption explicit an assertion)
   (Use assertioins to checkthings that need to be true)

  

 

----  2013-06-1512:00:00  ----

 

Chapter 10

 

Coming up with interfaces that are easy to understand and use isa key skill in developing good object-oreiented software。

 

Good interfaces show only what they have to and no more.

 

1、Rename method 重命名 -> The name of a method doesnot reveal its purpose.(Change the name of the method)
   Naming is a key tool incommunication,inproving this skill is the key to being a trulyskillful programmer.

 

2、Add Parameter 添加参数 -> A method needs moreinformation from its caller.(Add a parameter for an object that canpass on this information)
   (调用比较多的话,先写个新的方法,然后用旧的调用,最后再全部替换)

 

3、Remove Parameter. 删除参数 -> A parameter is nolonger used by the method body.(Remove it)

 

4、Separate Query from Modifier 从修改中分离查询 -> Youhave a method that returns a value but also changes the state of anobject.(Create two
   methods, one for the query andone for the modification)

 

5、Parameterize method. 参数化方法[类似的代码段或方法用带参数的方法替换]-> Several methods do similar things but withdifferent values contained in the method body.(Create onemethod
   that uses a parameter for thedifferent values)

 

6、Replace Parameter with Explicit Methods 用清晰的方法代替参数->  You have a method that runsdifferent code depending on the values of an enumeratedparameter.

 

 

2013.7.24


7、Preserve Whole Object  保存整个对象 ->You are getting several values from an object and passing thesevalues as parameters in a method call.(Send the whole objectinstead)

 

8、Replace parameter with Method 用方法代替参数 -> Anobject invokes a method, then passes the result as a parameter fora method. The receiver can also invoke this method(Remove
   the parameter and let thereceiver invoke the method)

 

9、Introduce Parameter Object 引入参数对象 -> Youhave  group of parameter that naturally gotogether.(Replace them with an object)
   将方法的参数封装为对象会带来两个好处:

  1)提高方法的可读性(对象名称可以概括若干个参数合起来的意思)  

   2)提高可扩展性(参数个数变化时)


10、Remove Setting Method 移除设置函数 -> A field should beset at creation time and never altered.(Remove any setting methodfor that field)

 

2013.07.25

11、Hide Method 隐藏方法 -> A method is not used byany other class.(Make the method private)

 

12、Replace Constructor with Factory Method 用工厂方法代替构造函数 -> You want to do more than simpleconstruction when you create an object.(Replace the constructorwith a factory method)

 

13、Encapsulate Downcast -> 封装往下类型转换 A methodreturns an object that needs to be downcasted by its callers.(Movehe downcast to within the method)

 

2013.07.27

 

14、Replace Error Code with Exception 用异常代替错误码 ->A method returns a special code to indicate an error.(Throw anexception instead)
   understandability is next to godliness

 

15、Replace Exception with Test 用条件判断检查代替异常 -> Youare throwing an exception on a condition the caller could havechecked first.(Change the caller to make the test first)
   微软的开发人员提出了Tester-Doer模式,因为异常的抛出与捕获会对系统造成指数级影响。

 

2013.07.28

 

Chapter 11  Dealing with Generalization

1、Pull Up Field 提升属性 -> Two subclass have thesame field.(Move the field to the superclass)

 

2、Pull Up Method 提升方法 -> You have methods withidentical results on subclasses.(Move them to the superclass)

 

3、Pull Up Constructor Body 提升构造函数体 -> You haveconstructors on subclasses with mostly identical bodies.(Create asuperclass constructors; call this from the subclass methods)

 

4、Pull Down Method 下放函数 -> Behavior on asuperclass is relevant only for some of its subclasses. Move it tothose subclasses.

 

5、A field is used only by some subclasses. Move the field tothose subclasses.

 

6、Extract Subclass 提取子类 -> A class has featuresthat are used only in some instances.Create a subclasses for thatsubset of features.

 

7、Extract Superclass 提取父类 -> You have two classeswith similar features. Create a superclass and move the commonfeatures to the superclass.

 

8、Extract Interface 提取接口 -> Several clients usethe same subset of a class's interface, or two classes have part oftheir interfaces in common.
   (Extract the subset into aninterface) egg:一个函数,参数传入一个类,在函数中调用了该类的两个方法,另一个类也传入调用同样的两个方法->传入提取了这两个方法的接口)


2013.08.10

9、Collapse Hierachy 合并继承层次 -> A superclass andsubclass are not very different.(Merge them together)

 

10、From Template Method 塑造模板函数 -> You have twomethods in subclasses that perform similar steps int the sameorder, yet the steps are diffrent.(Get the steps into methods withthe same signature, so taht original methods become the same. Thenyou can pull them up)


11、Replace Inheritance with Delegation 用委托代替继承 -> Asubclass uses only part of a superclasses inerface or does not wantto inherit data.(Create a feild for the superclass, ajust methodsto deltegate to the superclass, and remove the subclassing)


12、Replace Delegation with Inheritance 用继承代替委托 ->You are using delegation and are often writing many simpledelegations for the entire inerface.(Make the delegating class asublass of the delegate)


Chapter 12 Big Refactorings

1、Tease Apart Inheritance  分解继承层次-> You have an inheritance hierarchy that is doingtwo jobs at once.(Create two hierarchies and use delegation toinvoke one from the other)
   将两个不同变化方向的功能硬塞入同一个继承体系中,就会像一辆两个轮子反方向转的马车会人仰马翻。因此,我们有必要分离这两个变化的功能,分别建立继承体系,再以委派的方式建立二者之间的关联。

 

2、Covert Procedural Design to Objects 将过程式的设计转化为对象-> You have code written in a procedural style.(Turnthe data records into objects, break up the behavior, and move thebehavior to the objects)

 

3、Separate Domain from Presentation 将领域逻辑与表现分离 ->You have GUI classes tht contain domain logic .(Separate the domainlogic into separate domain classes)

 

4、Extract Hierarchy 提取继承层次 -> You have a classthat is doing too much work, at least in part through manyconditional statements.(Create a hierarchy of classes in which eachsubclass represents a special case)


   我目前就在对一个一流系统进行重构,深感重构之难。我的经验或者教训就是首先应该集中攻克主要的核心功能,且主要是考虑代码的重用性与可扩展性。重构不可大步迈进,可以针对主要的类和方法,一点一点地进行清理,其细心与耐心的程度不亚于考古学家发掘古迹。建立单元测试是必要的,它既能帮助清理遗留系统的原有功能,类之间的依赖关系,以及理清客户端的调用方式,又能避免重构不至于引入新的bug。重构时,可以适当借助UML,使我们可以尽快地掌握原有系统的类结构。AndyHunt认为,“不要急于修复一段没能真正理解的代码。”重构同样如此,没有理解代码就盲目进行重构,效果只能适得其反。不过,利用一些重构手法,例如RenameMethod,Extract Method等,通过小步骤地改善代码,有助于我们对代码的理解。
   然而,遗留系统的重构之殇总是让人痛苦不堪,尤其是当我们要面对如意大利通心粉一般的代码时,我总会产生临阵脱逃的想法。因而,最佳做法还是一边开发,一遍重构,这是编程人员应该具备的良好“卫生”习惯。


相关优秀书籍:
《More Effective C++35个改善编程与设计的有效方法》   ScottMeyers  侯捷


《More Exceptional C++》 中文版 Herb Sutter


《提高C++编程性能的编程技术》Dov Bulka / David Mayhew


《More Effective C++改善程序与设计的55个具体做法》   ScottMeyers  侯捷

《程序员修炼之道 - 从小工到专家》Andrew Hunt / David Thomas


《UNIX编程艺术》 Eric S.Raymond
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 重构改善既有代码是指对一个已经存在的代码进行优化和改进,从而提高代码的可读性、可维护性和可扩展性。对于电子书的MOBI格式来说,重构改善有以下几个方面的作用。 首先,重构可以提高代码的可读性。通过重构,我们可以优化代码的结构,使其更加清晰易懂。对于MOBI格式来说,我们可以重新组织文件的结构,提取出公共的代码片段,增加注释和文档说明,使其更容易理解和维护。 其次,重构可以增强代码的可维护性。通过重构,我们可以降低代码的复杂度,减少代码的冗余和重复,使其更易于维护和修改。对于MOBI格式来说,我们可以使用面向对象的设计原则,提取出独立的功能模块,使其可以独立测试和维护。 再次,重构可以提高代码的可扩展性。通过重构,我们可以将代码的功能进行模块化和解耦,使其能够灵活扩展和增强功能。对于MOBI格式来说,我们可以设计可插拔的功能模块,使其能够方便地添加新的特性和支持新的格式。 最后,重构可以提高代码的性能和效率。通过重构,我们可以优化代码的算法和数据结构,减少不必要的计算和存储开销,提高代码的执行效率。对于MOBI格式来说,我们可以优化文件解析和渲染的算法,提高电子书的加载速度和用户体验。 综上所述,通过重构改善既有代码,对于电子书的MOBI格式来说,可以提高可读性、可维护性、可扩展性,同时也可以提高性能和效率。重构是一个长期持续的过程,需要不断地改进和优化,以保持代码的健康和可持续发展。 ### 回答2: 重构改善既有代码是指通过对已有代码的优化和修改,使其更加易于理解、扩展和维护。对于电子书的mobi格式文件,可以采取以下重构改善措施: 首先,对代码进行模块化重构。将功能相关的代码段封装为独立的模块或类,使其具备高内聚性和低耦合性。例如,可以将与电子书内容解析和渲染相关的代码放置于一个独立的模块中,与界面交互相关的代码放置于另一个模块中。这样可以使代码结构更加清晰,易于理解和维护。 其次,采用设计模式对代码进行重构。设计模式是一种被广泛应用于软件开发中的经验总结,可以提供可靠、灵活和可维护的解决方案。对于电子书mobi格式的代码,可以采用一些常见的设计模式,如工厂模式、单例模式、观察者模式等,来改善代码的设计和结构。 此外,注重代码的可读性和可维护性也是重要的重构目标。通过添加适当的注释、命名变量和函数等,使代码更加清晰易懂。同时,消除重复代码、提取公共代码,使代码更加简洁、可复用。 最后,进行性能优化是重构过程中的另一个关键点。通过分析和定位性能瓶颈,优化代码的执行效率,提高电子书mobi文件的加载速度和响应能力。可以采用一些优化技术,如缓存、异步加载等,来改善代码的性能。 总结起来,通过模块化重构、采用设计模式、提高可读性和可维护性、性能优化等措施,可以改善电子书mobi格式的既有代码。这样可以使代码更加健壮、可扩展和易于维护,提高电子书的用户体验。 ### 回答3: 重构是指对既有代码进行优化和改进,以提高代码质量、可维护性和可扩展性。 首先,对于电子书 mobi 文件的重构,可以从文件结构和命名方面着手。通过整理文件和目录结构,使其更加清晰和简洁,方便代码的阅读和维护。同时,对于变量、函数和类的命名,遵循一致且有意义的命名规则,以增加代码的可读性。 其次,可以通过减少代码冗余来改善代码。通过分析重复出现的代码块,并将其提取为可复用的函数或类,以减少代码量和维护成本。此外,还可以利用面向对象编程的特性,将功能相关的代码封装成类,以提高代码的灵活性和可重用性。 另外,重构还可以通过代码的重组和优化来改善代码的性能。首先,可以对算法和数据结构进行优化,以减少时间复杂度和空间复杂度。此外,通过减少不必要的计算和避免频繁的IO操作,可以进一步提高代码的执行效率。 此外,重构还需要考虑代码的可测试性。通过引入单元测试和集成测试,可以对重构后的代码进行验证,以确保代码的正确性和稳定性。同时,还可以通过使用自动化测试工具,提高测试的效率和覆盖率。 最后,还可以通过代码注释和文档编写来改善代码的可维护性。通过为代码添加清晰的注释,可以方便其他开发人员的理解和维护。同时,编写详细和准确的文档,可以帮助其他人员快速上手并了解代码的功能和使用方法。 综上所述,重构改善既有代码的电子书 mobi 文件可以通过优化文件结构和命名、减少代码冗余、提高性能、提升可测试性和编写文档等方式来实现。重构的最终目的是提高代码的质量和可维护性,使其更加易读易懂、高效稳定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值