Reading Report-art of code modification (I)

Source: Internet
Author: User

Labels: coding design Reconstruction

The art of code modification, English name 《Working extends tively with legacy code,The word "art" cannot be used in Chinese translation. It is worthy of the word "art" (of course, this is not the meaning of the translator ). The third part of the book, whether it is an example or an explanation, is a bit confusing. It is far worse than refactoring-improving existing code design. The essence of this book lies in the first and second parts.

How to Learn this book, as the bottom-layer coders, as a developer who has been repairing and supplementing others' code for a long time, I can only give the following suggestions: you can think of it as a guide on how to create custom functions-in a sense, many times we introduce testing. Actually, we add a custom function called "test. In addition, this seems to prove the Chinese name of the book, "The Art of code modification ".

 

I don't want to talk about anything else. That's it.

Since we want to regard this book as a guide to how to create custom functions, we should first look at the second part of this book, "The Technology for modifying code.

1. Reduce the Risk of Modification

  • A good code editing tool.
    I will not consider any great opportunity that makes binary data superb. For ordinary ape like me, I have not been able to eat the z112, not to mention the Z113, And I have limited IQ. You can only use tools to make up for it. We are basically using source insight. The Chinese encoding of this tool is not supported, and the search and completion commands are not strong.
  • Edit a single target.
    This is also repeatedly emphasized in the refactoring book. My personal experience here is to follow it honestly. When it comes to perfection, the time for progress will come. Don't think that you have learned a high volume and a theory of relativity, and you can just play with classical mechanics.

2. You need to modify a large number of identical codes.

I am almost paranoid about modifying the same code, probably because of the following two sentences:

  • When you enthusiastically eliminate duplicates in the code, you will be surprised to find that the design will come out on your own.
  • Eliminating duplication is a powerful way to temper the design. It not only makes the design more flexible, but also makes code modification faster and easier.

Here we add the same code, not necessarily the same code. Sometimes identical code appears, just because of a coincidence. In many cases, the most common problem is repeated code with a similar structure and logic.

 

3. Time is tight and must be modified

No matter whether the time is short or not, as a self-protection instinct, generally, try to concentrate the modified code into a separate class or method during modification, the implementation is similar to a switch, which can be simple enable or disable.

However, if there is plenty of time, we should reconstruct it as measurable. My own feeling is that sometimes this kind of self-protection instinct is too strong and sometimes it may be malformed, the code written in this way may be the safest, but not the most elegant. Like many greedy algorithms, they are not always optimal, but often "excellent"

Here is an example of the original book.

The original code executes the postdate () object for each object in the list entries, and then adds the management pool of the transactionbundle.

  public void postEntries(List<Entry> entries) {        for (Iterator<Entry> it =entries.iterator(); it.hasNext(); ) {            Entry entry = (Entry)it.next();            entry.postDate();        }        transactionBundle.getListManager().add(entries);}


There is a new requirement. The requirement description is as follows: (the requirement description is actually very important. different descriptions may unconsciously affect the implementation of programmers)

Not all objects in the entries List need to execute postdate () and add it to the management pool of transactionbundle. Only objects in the management pool of transactionbundle need to perform the postdate () operation. Only those entry objects that have performed postdate () need to be added to the management pool of transactionbundle.

According to the requirements described above, if you are one of the 99.9% people, it will generally be implemented as follows:

Public voidpostentries (list <entry> entries) {// records which objects in entries have performed postdate () List <entry> entriestoadd = newexpiration list <entry> (); for (iterator <entry> it = entries. iterator (); it. hasnext ();) {entry = (entry) it. next (); // only entry objects that are not in the transactionbundle management pool need to execute postdate () if (! Transactionbundle. getlistmanager (). hasentry (entry) {entry. postdate (); entriestoadd. add (entry) ;}}// add the entry objects that execute postdate to the transactionbundle management pool. getlistmanager (). add (entriestoadd );}


Undoubtedly, such modifications are very invasive. Once an error occurs, it is difficult to identify whether it is an existing defect or a change-the cause of the error can be analyzed only after a thorough understanding of the Code's change logic. This is not good.

In essence, this requirement is to first find the entry objects that are not in the management pool, and then execute the postdate () and add () operations. Therefore, the "New Method" technique can be applied here to introduce a slightly invasive modification.

Public voidpostentries (list <entry> entries) {// first remove the list of entry objects already in the transactionbundle management pool <entry> entriestoadd = uniqueentries (entries ); for (iterator <entry> it = entriestoadd. iterator (); it. hasnext ();) {entry = (entry) it. next (); entry. postdate ();} transactionbundle. getlistmanager (). add (entriestoadd );}

// Remove the entry object private list <entry> uniqueentries (list <entry> entries) {// return entries; // if an error occurs, you can directly return. // The benefit of the new method is code isolation. You can quickly locate whether to modify the introduced problem or whether the original code has a buglist <entry> result = new writable list <entry> (); for (iterator <entry> it = entries. iterator (); it. hasnext ();) {entry = (entry) it. next (); If (! Transactionbundle. getlistmanager (). hasentry (entry) {result. Add (entry) ;}} return result ;}


Of course, you can also introduce external methods.

The first step of the method is to rename the original method and introduce the external method. The external method name is the original method name. This step is basically correct.

//rename "postEntries(List<Entry> entries)" aspostEntriesDirectlyprivate voidpostEntriesDirectly(List<Entry> entries) {        for (Iterator<Entry> it =entries.iterator(); it.hasNext(); ) {            Entry entry = (Entry)it.next();            entry.postDate();        }        transactionBundle.getListManager().add(entries);}   // new wrapper method use signature "public voidpostEntries(List<Entry> entries)"public voidpostEntries(List<Entry> entries) {       postEntriesDirectly(entries);}


Next, adjust the implementation of the overwriting method. Here, it is basically the same as the new method.

// New wrapper method use signature "Public voidpostentries (list <entry> entries)" Public voidpostentries (list <entry> entries) {// first remove the list of entry objects already in the transactionbundle management pool <entry> entriestoadd = uniqueentries (entries); postentriesdirectly (entriestoadd );}


If you are used to thinking about using the weak intrusive modification method, the next two methods will naturally be obtained. The difference between the method and the new method is that the method retains the original method (only the method name has been modified ).
If necessary, you can also generate new classes and overwrite classes. The principles are similar.

In the end, if the initial requirement is described as follows:

Check whether the entry object in the entries list is in the management pool. The postdate () operation is executed only when it does not exist and added to the management pool.

After this description, it will be more natural to think of the following two methods.
Therefore, the requirement description is critical. But no one will do this for us. Everything depends on ourselves. Everything starts with requirement analysis.

Reading Report-art of code modification (I)

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.