About code repeating the most famous word is Kent Beck's overce and only overce, that is, any piece of software operation - no matter a algorithm, a constant collection, document for reading or other things - should only appear once . The software repeats will at least lead to the following questions: · One version will expire · The responsibility of the code will spread around, causing the code to understand • When you modify the code, you need to repeat a lot of places, you will miss it, you will miss you. Can not perform performance optimization
My previous boss once used me to bruise his ability to program: "He only wants to copy a template code, and a new module can be completed." I am surprised that this programmer thinks clearly and also doubts that such procedures can be maintained outside him, I think it may even be done. The generation of duplicate code is a variety of reasons, the above example is one, I often see that the programmer copies a few lines or a whole code from here, then less modifications, it will become a new Code. The reason here is that the programmer can complete the code reuse through very little effort, but we can take a look at the seven software development principles proposed by DavidHooker: 1. First Principle: Pattern: Thereason) A software system exists The reason is to provide value for its users. All your decisions depends on this. In specifying a system requirement, write a short system function, ask yourself before determining the hardware platform and development process, "Do you add value to the system?" If the answer is "Yes", do it. If it is "no", don't do it. This principle is the principle of other principles. 2. The second principle (simple, stupid!) KISS (Pattern: KeepitsImple) software is not a deody-written process. When doing any design, you must consider a lot of factors. All designs should be as simple as possible, but don't be more simple than this. The system thus produced is to understand and easily maintained. This is not to say a lot of significant features, because this simplicity should be abandoned. There are still many more elegant designs to be simpler, but it doesn't mean "Quick and Dirty.". In fact, simple is achieved by many thinking and once repeated modifications. The report of these efforts is more easily maintained, and the code is incorrect. (See if it is violated) 3. Third principles: Pattern: Maintainthevision clear vision is the basis for a software project success. Without such a vision, the project development finally turned into a bad design to make a patch every day. Brooks said: The integrity of the concept is the most important issue in system design. Stroustrup also said: There is a clean internal structure to build a foundation of understanding, identify, maintainable, testing systems. Booch summarizes: Only when you have a clear feeling of the system, you may find universal abstraction and mechanisms. Developing this versatility ultimately leads the system easier, so smaller, more reliable if you constantly copy, paste, modify the code, and ultimately you will fall into a big mushroom, you will never have a clear system. Awareness. 4. Fourth Principle: Your manufactured, the Pattern: WhatYouProducetheyConsume software system is not used in vacuum. Others will use, maintain, document your system. This depends on the understanding of your system. Therefore, what you design, what you realize should be able to let others understand. To remember, what you write is not only for your computer, you want to remember, the code will give people. (Kent Beck) If it is flooded everywhere, how others can identify similar and different, how to understand the relationship between these codes. 5. The fifth principles: a successful life of a successful software in the future, Pattern BuildfortAyDesignFortomorrow. You must be able to make the software adapt to this and that change. So, don't design it to the dead angle at the beginning. Please always ask yourself "if this, then ..?" This problem, you have to take into account a variety of possibilities, and not light is a provincial thing.
Copy and paste it. 6. Sixth Principle: To reuse the planned software model is one of the reuse. Constant duplicate code is obviously not such a plan. See CommentsIx 7. Seventh principle: thinking! Before adopting any action, you will first make a clear, complete consideration, so that better results can be produced. If you consider, but still generate an error, then this effort is also worth it. It is easier to understand and master when you study or study similar questions. These principles tell us that it is easy to copy, paste and modify the code, which is easy to understand, maintain, and reuse the code. But please do not take extremes. I have always thought that a good software system is the result of various factors, which is how you grasp a problem. Another main reason for repeating code is to do too much. XP has a basic principle called you area get it, it is said that "I only realize what you really need, never realize what you expect." If you go to realize what you think in the future, it is not necessarily what you really need later. You may not understand what you want to achieve in the current environment. You will waste a lot of time to construct this, don't know if you have a possible possibility. At the same time, it may generate duplication of code when you really implement it.
Martin Fowler has many of its Refactoring books to handle code repetition, including: 1. There are the same expressions in the two methods of the same class, using extract method, then everyone calls the method; 2. There is the same expression between the two brothers, so use the Extract method in these two subclasses, followed by PULL UP Field, moved to common hyperscogence 3. If the structure is similar, not exactly the same, separately separate the same part and the different parts with Extract Method. Then use Form Template Method. 4. If the method uses different algorithms to do the same thing, then Substitute Algorithm 5 is used. If there is a duplication code in two inseparable classes, use the extract class in a class and then use the Class object in other classes as an element. and many more.
Duplicate code requires refactoring is no doubt, the key is how you find a duplicate code, if all duplicate code is a deadline repetition, then the problem is easy to solve. However, complex factors developed by software may tend to perform duplicate code as similarities rather than complete repetition. These similarities may be seen without a eye. Instead, there is a need to pass through other refactory steps and certain foresight. Another problem is to exclude the granularity of the duplication, only the duplicate code is valuable to exclude, or even a small 2,3 sentence duplicate code should be excluded. The basic method of repeating code exclusion is to build a separate method. If many methods in the system are small, the expenditures of mutual calls will increase, and it also increases the overhead of maintenance. However, these overhead is worth it. The method is to cover the minimum particle size, the smaller the particle size covered, and the range and Chengdu can be more integrated. But don't take extremes on this issue, only when a method can be named with INTENT REVEALING NAME (revealing the intent name), a code is worthy of a method, not how much it is considered.
Martin Fowler describes a lot of examples in his Refactoring, and Kent Beck is more foundally in SMALLTALK BEST PractICE PATTERN, which is implied under these refactoing. Below is an actual example, from Martin Fowler design column on ACM: Class Invoice ... string asciistatement () {stringbuffer result = new stringbuffer (); result.append ("Bill for" Customer "/ n "); Itrator it = items.iterator (); while (it.hasnext ()) {lineItem Each = (lineItem) it.next (); Result.Append (" / t " Each.Product () " / T / T " EACH.Amount () " / n ");} Result.Append (" Total Owed: " Total " / N "); return fruit.toString ();} string htmlStatement () {StringBuffer Result = new stringbuffer (); Result.Append ("Bill for" Customer "
"); Result.append (" "); itrator it = items.Itemrator (); whose (it.hasnext ()) {lineItem EACH = (lineItem) it.next (); Result.Append (" Each. Product () " " "" "result.Append (" Total Owed: " Total "
"); Return Result.toString ();}} ASCISTATEMENT and HTMLStatement have similar infrastructure, but their actual steps are different. They all completed three things: 1. Print the invoice head 2. Cycle each item, And print 3. Print the similarity of this structure and intent of this structure and intent to usually use Composed Method (which is Martin Fowler Extract Method):
interface Printer {String header (Invoice iv); String item (LineItem line); String footer (Invoice iv);} static class AsciiPrinter implements Printer {public String header (Invoice iv) {return "Bill for" iv.customer " / N ";} public string item (lineItem line) {return" / t " line.product () " / t / t " line.amount () " / n ";} public string footer (Invoice IV) ) {RETURN "Total Owed:" }}}} h h h 则. Class Invoice ... Public String Statement (Printer Pr) {StringBuffer Result = New StringBuffer (); Result. Append (pr.Header (this)); item it = items.ITerator (); whose (it.hasnext ()) {lineItem Each = (lineItem) it.next (); result.append (pr.Item (EACH) } result.append (pr.footer (this)); returnrate.tostring ();} class invoice ... public string asciistatement2 () {Return Statement (new asciiprinter ());} Now, Statement contains a general purpose The structure and repeatability have been excluded. More importantly, you can implement other Printer, XXXPrinter, which can easily expand the system. BTW, Martin Fowler uses the Dispatch Interpretation mode here. Statement conceals the internal details, it hides the internal data and representation, when it requires Printer to do something, it is responsible for decoding the internal data structure, then turn a message Pass it to Printer.
See: Martin Fowler: Refactoring: Improve The Design Of Existing Code Kent Beck: Smalltalk Best Pratice Pattern ACM: Martin Fowler Design Column: Reduce Repetation Kent Beck: Extreme Programming Explained