Restructuring and pattern: Improving the third part in the Code Trilogy

Source: Internet
Author: User

I. trilogy of code improvement

Design Patterns> reconstruction and patterns. That is, design-> refactoring the new design.

The design pattern mainly describes more than 20 modes, which brings us a classic solution to common design problems, thus changing the face of the entire object-oriented development. Designed.

Refactoring improves the design of existing code, summarizes the various refactoring techniques we will use, and brings us an efficient process of improving code, this completely changed the way of object-oriented design. Focuses on removing the taste of bad code.

Reconstruction and pattern are reconstruction related to the design pattern. The pattern is not designed but reconstructed. A good design is not designed, but reconstructed. Don't be afraid of changes. As long as you change the law, it will not be a disaster, but a good opportunity for progress. Focuses on the design mode + Reconstruction means.

Before reading the reconstruction and mode, you 'd better read the first two books: design mode and reconstruction.

The design pattern represents the traditional software development idea: a good design will produce good software, so it is worth the time to complete and meticulous design before the actual development. Refactoring represents the wave of Agile Software Development: software can not be perfectly designed at the very beginning, so it can be developed first, then, we can improve the design by constantly making minor changes to the Code. They explain the importance of design from different perspectives. Some people plan the mode very early before writing any code, while some start to add the mode after writing a lot of code.
The second mode of use is refactoring, because it is to change the system design without adding system features or changing its external behavior.
Some people add a pattern to the program, just because they think the pattern can make the program easier to modify; more people just want to simplify the current design.
If the code has been written, both of these situations are refactoring, because the former makes modification easier through refactoring, while the latter completes the modification after refactoring.
Although the mode is something that can be seen in the program, the mode is also a program conversion.
Reconstruction is a means to achieve the design model, and the design model is often the purpose of reconstruction.

Ii. Reasons for restructuring and Pattern
We should reconstruct the implementation mode, trend mode, and removal mode (refactoring to, towards, and away from pattern), instead of using the mode in advance design, it is no longer too early to add the mode to the code. This skill avoids over-design, and does not mean insufficient design. 1. Over-design: The flexibility and complexity of the Code exceeds the requirement. At the beginning of the design, I thought that some places would change frequently and even began to use some design mode to reserve extensions, but later I did not make any changes, that is, it led to the waste of design and functions.
2. Insufficient Design Causes of insufficient design:
1) programmers have no time, no time, or time cannot be reconstructed. 2) programmers have insufficient knowledge about good software design.
3) programmers are required to quickly add new functions in existing systems
4) programmers are forced to carry out too many projects at the same time.
If the long-term design is insufficient, the pace of software development may change to "fast, slow, and slower". The possible consequence is:
Version 1.0 was delivered soon, but the code quality was poor.
Version 2.0 is also delivered, but poor quality code slows us down
In an attempt to deliver a future version, with the multiplication of inferior code, the development speed is getting slower and slower. Finally, people lose confidence in the entire process of systems, programmers, and even putting everyone into this situation.
When we got to version 4.0 or later, we realized that this was definitely not the case. We started to consider restarting. 3. Test-driven development and continuous refactoring,Test-driven development and continuous refactoring provide a lean, iterative, and well-trained programming style that maximizes relaxation and increases productivity. Benefits of using test-driven development and continuous refactoring: 1) maintaining a low number of defects 2) bold refactoring 3) get simpler and better code 4) There is no natural connection between the stress mode and refactoring during programming. The mode is the destination you want to achieve, reconstruction is the path to reach the destination from somewhere else. 4. Evolutionary DesignEvolutionary Design is the trend design, mainly to avoid over-design. The design structure is generated through reconstruction, that is, the implementation mode or the reconstruction trend mode. The idea designed for design is not suitable for big projects. Gradual reconstruction from reconstruction to design pattern is the king of the design pattern.

Evolutionary architecture design often used in Agile development:

Many programmers may have encountered this problem: A piece of code needs to be modified, but no one is willing to take over. Why? This code happens to be an interface between two components, which is too difficult to modify. In an evolutionary design, we often make such changes. The Code should be "active" and "extensible", and must not remain unchanged without the need for strong changes. Because of this, evolutionary design can improve the design quality and the quality of the entire system.

Chapter 1 Creation 6.1 Replace the constructor with Creating MethodWhen there are multiple constructors in the class, it is difficult to decide which one to use during development, you can replace the constructor motivation with the Creation Method of the returned object instance that can describe the intent: creation Method -- A static or non-static new instance Method in the class that is responsible for instantiating the class. Because there is no restriction on the name of the Creating Method, you can use the name that best expresses the created object. There are too many constructors in the class → refining the class or refining the subclass or replacing the constructor With the Creation Method to clarify the constructor's intention advantages and disadvantages: + The constructor can better express the types of instances created. + the constructor's limitations are avoided, for example, the number and type of parameters of the two constructors cannot be the same + It is easier to find useless Creation code-the Creation Method is not standard, some use new instantiation, and some use Creation Method to instantiate the variant: you do not need to set up a Creation Method for the configuration of each object. You can add parameters to reduce the number of Creation methods unless necessary. When the Creation Method is too large, it disperses the main responsibilities of the class, we should consider refactoring the related Creation Method into a Factory 6.2 move the created knowledge to the FactoryWhen the data and code used to instantiate a class are everywhere in multiple classes, you can explain the motivation for moving the created knowledge to a Factory: create spread-place the created responsibilities in the class that should not undertake the task of object creation, which is a type of solution spread, generally caused by previous design problems. Using a Factory class to encapsulate the creation logic and the instantiation options of the Customer Code, the customer can tell the Factory instance how to instantiate an object, and then use the same Factory instance to execute instantiation at runtime. The Factory does not need to be specifically implemented by a specific class. You can use an interface to define the Factory, and then let the existing class implement this interface. If the logic created in the Factory is too complex, it should be reconstructed into Abstract Factory. The customer code can configure the system to use a ConcreteFactory (a specific implementation of AbstractFactory) or the default ConcreteFactory. The advantages and disadvantages of Factory refactoring are sufficient only when the code design is indeed improved or cannot be instantiated directly: + merging creation logic and instantiation options + decoupling customer code from creation logic-if you can instantiate it directly, it will complicate the design. 6.3 Factory encapsulation class Multiple classes that implement unified interfaces are directly instantiated in the same package structure. You can declare the constructor of classes as non-public ones and use Factory to create their instance motives: You can use Factory to shield a group of sub-classes that customers do not need to care about into the package. This refactoring may be useful if a class shares a common public interface, shares the same superclass, and is in the same package structure. Advantages and disadvantages: + use the intent-oriented Creation Method to simplify the Creation of different types of instances + reduce the "conceptual weight" of the package by hiding classes that do not need to be made public + help strictly implement "interface-oriented programming, instead of implementation-oriented "-when you need to create a new type of instance, you must update the Creation Method-when the customer can only obtain the binary code of the Factory but cannot obtain the source code, customization of Factory will be restricted 6.4 Use Factory Method to introduce polymorphism CreationWhen classes in a hierarchy implement a similar method, but the object creation steps are different, you can create a unique superclass version motive that calls the factory method to process the instantiation method: factory method is the most common mode in OOP, because it provides methods for creating multiple objects, the code after using the factory method is usually easier to use the factory method than the value Assignment Method in the class to create a custom object: when the sibling subclass implements methods similar to the object creation steps, the advantages and disadvantages of the superclass and subclasses are similar except the object creation steps: + reduce repeated code generated by creating custom objects + effectively express the location where an object is created, and how to override the creation of objects + the class used to force the factory method must implement a unified type-unnecessary parameters may be passed to some implementers of the factory method. 6.5 Composite encapsulation with BuilderWhen constructing a composite is repetitive, complex, and error-prone, you can use builder to process the construction details to simplify the construction process. Motivation: constructing a composite is repetitive, complex, and error-prone. You can use builder to process the construction details to simplify the construction process. The Builder mode is good at handling heavy and complex construction steps. Intention of builder mode: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process. Advantages and disadvantages: + simplified Customer Code for building composite + reduced duplication and error-prone nature for creating composite + loose coupling between customer code and composite + allowed for encapsulated composite or complex objects create different representations-the interface may not clearly express its intent 6.6 inline SingletonWhen the code needs to access an object without the Global Entry of the object, you can move the singleton function to a class that saves and provides the object access entry. Delete Singleton. Motivation: Singleton purpose: ensure that a class has only one instance, it also provides a global access point to access it to maintain a balance between exposed objects and protected objects, which is crucial to maintaining system flexibility. Any global data is harmful until it is proved harmless. if Singleton is not implemented as Singleton, don't hesitate to inline it! Advantages and disadvantages: + makes object collaboration more obvious and clear + protects a single instance without special code-when it is difficult to pass object instances across many layers, it will make the design complicated. Chapter 1 simplifies the vast majority of the code we have written, and it will not be very simple from the very beginning. Algorithms are often complex because they support multiple changes. The logic for controlling the state transition is often more and more complex. 7.1 Combination MethodWhen you cannot quickly understand the logic of a method, you can convert the logic of the method into several steps at the same level that can describe the intent. Motivation: composed method is composed of calls to other methods. Good composed method code is at the same level of detail. Composed method generally does not introduce performance issues: + It clearly describes the functions implemented by a method and how to implement it. + It breaks down the method into a well-named behavior module at the same level of detail, this simplifies the method-too many small methods may be generated-it may make debugging difficult, because the logic of the program is dispersed in many small methods. The composed method guiding principle is that the composed method is very small. Generally, there are about five lines, and few more than 10 lines Delete duplicate and dead code. Aside from obvious and subtle code duplication, Remove unused code to reduce the amount of code in the method to express intent. Clearly name the variables, methods, and parameters in the program so that they clearly express the intent. Simplified. Convert the Code to make it as simple as possible. Use details at a unified level. When dividing a method into a group of behaviors, ensure that these behaviors are similar to the details. 7.2 replace conditional logic with StrategyWhen the conditional logic in the method controls which variant of the calculation should be executed, create a Strategy for each variant and enable the method to delegate the calculation to the Strategy instance. Motivation: -- generates a series of classes for each variant of the algorithm and assembles the main class with an instance of Strategy, the complex condition logic delegated by the main class to the Strategy instance at runtime is one of the most frequently-seen advantages and disadvantages of increasing complexity: + The algorithm is made clear and easy to understand by reducing or removing the conditional logic + the class is simplified by moving the algorithm variants to the class hierarchy + one algorithm can be used to replace another algorithm at runtime -When an application is based on an inherited solution or" Simplified conditional expressionsWhen refactoring is simpler, it will increase the complexity of the design-increase the complexity of how the algorithm acquires or receives contextual data. 7.3 move the decoration function to decoratorWhen the Code provides the decoration function to the class and core responsibilities, you can consider moving the decoration code to the Decorator, no matter how much you like a mode, do not use its advantages and disadvantages when necessary: + remove the decoration function from the class, this simplifies the class + effectively separates the core responsibilities of the class from the decorative functional area + removes repeated decorative logic in several related classes-changes the type of the decorated object-making the code more difficult to understand and debugging-when the Decorator combination has a negative impact, will increase the complexity of the Design 7.4 Replace the state change condition statement with stateWhen the conditional expressions that control the State transition of an object are too complex, consider the advantages and disadvantages of replacing the conditional statements with the State class that handles the Special State Transition: + reduces or removes the state change condition logic + simplifies the complex state change logic + provides a good bird's eye view of the state change logic-when the state change logic is easy to understand, will increase the complexity of the Design 7.5 replace hidden tree with CompositeWhen a tree structure is implicitly formed using native notation, you can consider replacing the native notation with Composite. Advantages and Disadvantages: + encapsulating repeated commands, for example, formatting, adding, or deleting nodes + providing a general method for handling the growth of similar logic + simplifying the construction responsibilities of Customer Code-when constructing an implicit tree is simpler, the design complexity is increased. 7.6 Replace the conditional scheduler with commandWhen the condition logic is used to schedule requests and execute operations, a Command is created for each action. Store these commands in a collection and replace the conditional logic with the code for obtaining and executing the Command. Create a Command for each action, store these commands in a collection, and replace the advantages and disadvantages of the conditional logic with the code for obtaining and executing the Command: + provides a simple mechanism to execute different behaviors in a unified way + allows you to change the processed requests at runtime, and how to handle the request + requires only a few code implementations-when the conditional scheduling program is sufficient, it will increase the complexity of the design.

Chapter 1 generalization refers to the process of converting special code into common target code. Generalized code is often the result of refactoring. 8.1 form template methodWhen the two methods in the subclass perform similar steps in the same order, but the steps are not exactly the same. These steps are extracted into methods with the same signature to generalize the two methods, and then these generalized methods are moved up to form a Template Method. Advantages and disadvantages: + by moving the unchanged behavior to the superclass, remove repeated code in the subclass + simplify and effectively express the steps of a common algorithm + allow the subclass to easily customize an algorithm-when many methods must be implemented in the subclass to generate an algorithm, will increase the complexity of the Design 8.2 extract CompositeWhen multiple sub-classes in a class hierarchy implement the same Composite, you can extract the advantages and disadvantages of a class that implements the Composite: + removing repeated class storage logic and class processing logic + Effectively expressing the inheritance of class processing logic 8.3 replace one/more points with CompositeWhen classes use different codes to process a single object and multiple objects, Composite can generate code advantages and disadvantages that can process both a single object and multiple objects: + remove duplicate code associated with processing one or more objects + provide a unified method for processing one or more objects + support richer methods for processing multiple objects-possibly in composite construction requires a type-safe runtime check 8.4 notice of replacing hard encoding with observerWhen a subclass notifies an instance of another class through hard encoding, it can remove these subclasses and enable its superclasses to notify one or more classes that implement the Observer interface. Advantages and Disadvantages: + loose coupling of the topic and its observer access + support for one or more observers-when hard-coded notifications are sufficient, the design complexity will be increased-when a series notification appears, it will increase Code complexity-when the observer is not deleted from their topic, it may cause resource leakage. 8.5 unified adapter InterfaceWhen the Customer Code interacts with two classes, one of which has the preferred interface, you can use an Adapter to unify the interface motivation: when the following conditions are true, refactoring the Adapter is useful: the two classes do the same thing or are similar, but have different interfaces. If the class shares the same interface, the customer code is simpler, more direct, and more compact, and cannot easily change the interface of one of the classes because it is part of a third-party library, or it is part of a framework that has been widely used by other clients, or it cannot obtain the advantages and disadvantages of the source code: + enables the client code to interact with different classes through the same interface, this removes or reduces repeated code + enables Customer Code to interact with multiple objects through public interfaces, this simplifies the customer code + unifies the way the Customer Code interacts with different classes-when the class interface can be changed, it will increase the complexity of the Design 8.6 extract AdapterWhen a class is adapted to multiple versions of components, class libraries, APIs, or other entities, an Adapter can be extracted for each version of components, class libraries, APIs, or other entities to adapt to objects, facade is used to adapt to the entire system. It is usually used to interact with legacy systems. Advantages and Disadvantages: + isolate the differences between components, class libraries, or APIs of different versions + enable the class to adapt only to one version of the code + avoid frequent code modification-if an important behavior is not allowed in the Adapter if used, then the Customer Code will not be able to execute this important behavior 8.7 replace Implicit Language with InterpreterWhen many methods in a class are combined into an element of an implicit language, the class can be defined for the element of the implicit language. In this way, the advantages and disadvantages of an easy-to-understand expression can be formed through the combination of class instances: + better support for combinations of language elements than implicit languages + No need to parse new code to support new combinations of language elements + runtime configuration of permitted behavior-a custom language is generated and the customer is modified code overhead-if the language is complex, requires a lot of programming work-if the language itself is simple, it will increase the complexity of the design. Chapter 1 Protection 9.1 use a class replacement type codeThe field type cannot protect it from incorrect copying and illegal equality comparison. You can declare the field type as a class to limit the advantages and disadvantages of copying and equality comparison: + It is better to avoid illegal assignment and comparison-more code is required than unsafe types. 9.2 use Singleton to restrict instantiationWhen the Code creates multiple instances of an object and causes excessive memory usage and system performance degradation, you can replace multiple instances with Singleton to avoid immature code optimization, immature and optimized code is more difficult to refactor than unoptimized code. Before code optimization, you will find more advantages and disadvantages: + improved performance-easy access anywhere. In many cases, this may be a design drawback-This refactoring is ineffective when an object contains a state that cannot be shared. 9.3 introduce Null ObjectWhen the code processes repeated logic of null fields or variables everywhere, replace the null logic with a null object. Advantages and disadvantages of an object that provides correct null behavior: + avoid null errors without repeated null logic + simplify the code by minimizing null testing-when the system does not require a null test, it will increase the complexity of the design-if the programmer does not know the existence of a null object, it will generate additional null tests-make the maintenance complex, null objects with superclasses must override all newly inherited public methods.

Chapter 4 aggregation operations 10.1 move the aggregation operation to collecting ParameterThere is a large way to aggregate information into a local variable, You can aggregate the result into a Collecting Parameter, and pass it into the advantages and disadvantages of the extracted method: + it helps us to convert large methods into smaller and simpler methods-to make the result code run faster. 10.2 move the aggregation operation to visitorThere is a method from different classes AggregationInformation, which can be moved to a Visitor that can access each class to collect information. Advantages and disadvantages: + adjust multiple algorithms to apply to different object structures + classes in the same or different inheritance structures + call type-specific methods on different classes, no need for type conversion-when you can use a common interface to convert different classes into similar classes, it will increase the complexity of the code-the new writable class requires a new receiving method, A new access method is required for each Visitor-it may damage the encapsulation of the observer class.

Chapter 1 reconstruction 11.1 chain ConstructorWhen there are many constructor that contain repeated code, you can link the constructor to get the least code repetition. 11.2 unified interfaceWhen you need a superclass or interface with the same interface as its subclass, you can find all the common methods contained in the subclass but not included in the superclass, copy these methods to the superclass, and modify each method, empty behavior. 11.3 extract ParametersWhen a method or constructor assigns a field a value to a locally instantiated value, the right side of the value assignment statement can be extracted to a parameter, the parameters provided by the customer code are used to assign values to fields.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.