10 tips for refactoring

Source: Internet
Author: User
There are many refactoring methods. Relatively speaking, the coverage of an article cannot be mentioned. LZ can only propose some methods that are frequently used at ordinary times, if you are interested in some of the more advanced techniques, you can find some specialized books. In addition, because LZ is developed in JAVA, some refactoring tips may work with JAVA

There are many refactoring methods. Relatively speaking, the coverage of an article cannot be mentioned. LZ can only propose some methods that are frequently used at ordinary times, if you are interested in some of the more advanced techniques, you can find some specialized books. In addition, because LZ is developed in JAVA, some refactoring tips may work with JAVA

There are many refactoring methods. Relatively speaking, the coverage of an article cannot be mentioned. LZ can only propose some methods that are frequently used at ordinary times, if you are interested in some of the more advanced techniques, you can find some specialized books.

In addition, because LZ is developed in JAVA, some refactoring tips may be closely related to the JAVA language or the object-oriented language. However, most of the skills are process-oriented, or object-oriented languages can all be common to each other.

Let's take a look at the ranking of practical refactoring techniques.

No. 1: duplicate code extraction

Repeated Code is one of the most effective methods of refactoring. The reason for this refactoring does not need to be said. It has many obvious advantages, such as greatly reducing the total amount of code, convenient maintenance, and more clear and easy-to-read code.

It focuses on finding repeated code that completes a sub-function in the Code. Do not hesitate to move it to the appropriate method and place it in the appropriate class.

Small instance

Class BadExample {public void someMethod1 () {// code System. out. println ("duplicate code");/* duplicate code block * // code} public void someMethod2 () {// code System. out. println ("duplicate code");/* duplicate code block * // code}/* --------------------- split line ---------------------- */class GoodExample {public void someMethod1 () {// code someMethod3 (); // code} public void someMethod2 () {// code someMethod3 (); // code} public void someMethod3 () {System. out. println ("repeated Code");/* repeated code blocks */}}

No. 2: segmentation of lengthy methods

Concerning the separation of lengthy methods, in fact, sometimes there is an inseparable relationship with the extraction of repeated code, often in the process of refining repeated code, the division of a super-long method is completed without knowing it. If some lengthy methods are retained after you extract most of the repetitive code, you need to calm down and handle these lengthy methods.

This is worth noting. Because most of the sub-functions in a large method are divided, we need to give each sub-function a proper method name, this is important. It can be said that the ability to give a good name to a method sometimes reflects the general level of a programmer.

Small instance

Class BadExample {public void someMethod () {// function [1] // function [2] // function [3]}/* ----------------------- split line ------------------------ */class GoodExample {public void someMethod () {function1 (); function2 (); function3 ();} private void function1 () {// function [1]} private void function2 () {// function [2]} private void function3 () {// function [3]}

No. 3: optimization of nested condition branches (1)

A large number of nested condition branches are very frustrating code. We should try our best to avoid such code. Although the structured principle has always been to say that a function can only have one exit, but under such a large number of nested condition branches, let us forget this so-called rule.

There is a professional term called Wei statement, which can treat this horrible nested Condition Statement. Its core idea is to put situations that do not meet certain conditions in front of the method and jump out of the method in time to avoid affecting the subsequent judgment. The code after this operation looks very clear. The LZ below will give you a classic example. You can judge which of the two methods makes you look clearer.

Small instance

Class BadExample {public void someMethod (Object A, Object B) {if (! = Null) {if (B! = Null) {// code [1]} else {// code [3]} else {// code [2] }}/ * --------------------- split line ---------------------- */class GoodExample {public void someMethod (Object, object B) {if (A = null) {// code [2] return;} if (B = null) {// code [3] return ;} // code [1]}

No. 4: optimization of nested condition branches (2)

The nested condition branch mentioned here is a little different from the previous one. It cannot be optimized using the Wei statement, but should be a combination of condition branches to achieve code clarity. From these two points, we can see that the nested condition branch should be avoided in encoding as much as possible, which will greatly reduce the readability of the Code.

The following is a typical example of yuanyou.

Small instance

Class BadExample {public void someMethod (Object A, Object B) {if (! = Null) {if (B! = Null) {// code }}}/* --------------------- split line ------------------------ */class GoodExample {public void someMethod (Object A, Object B) {if (! = Null & B! = Null) {// code }}}

No. 5: remove one-time temporary variables

We often use disposable chopsticks in our daily life, which is undoubtedly the destruction of trees. However, in a program, a one-time temporary variable is not only a small damage to the performance, but also a flaw in the code readability. Therefore, we need to perform some one-time temporary variables for surgery.

Small instance

Class BadExample {private int I; public int someMethod () {int temp = getVariable (); return temp * 100;} public int getVariable () {return I ;}} /* --------------------- split line -------------------- */class GoodExample {private int I; public int someMethod () {return getVariable () * 100;} public int getVariable () {return I ;}}

No. 6: remove the list of too long parameters

For some methods that pass a large number of parameters, it is unacceptable for programmers who pursue clean code. We can try to encapsulate these parameters into an object and pass them to the method to remove the list of too long parameters. In most cases, when you try to find such an object, it often exists, so in most cases, we do not need to do extra work.

Small instance

Class BadExample {public void someMethod (int I, int j, int k, int l, int m, int n) {// code}/* ----------------------- split line ---------------------- */class GoodExample {public void someMethod (Data data) {// code} class Data {private int I; private int j; private int k; private int l; private int m; private int n;

// Getter & setter}

No. 7: extract constants in a class or inheritance system

The purpose of this refactoring is to eliminate some magic numbers or string constants. Needless to say, it will confuse the program's intentions. For the elimination of constants of string and other types, the advantage is the convenience of maintenance. Because we only need to modify a constant to complete all the code that uses the constant in the program.

By the way, the most common and similar case is the extraction of INPUT, LIST, SUCCESS, and other constants in the Action base class.

Small instance

Class BadExample {public void someMethod1 () {send ("your operation has been successful! ");} Public void someMethod2 () {send (" Your operation is successful! ");} Public void someMethod3 () {send (" Your operation is successful! ");} Private void send (String message) {// code}/* ----------------------- split line ---------------------- */class GoodExample {protected static final String SUCCESS_MESSAGE =" your operation has been successful! "; Public void someMethod1 () {send (SUCCESS_MESSAGE);} public void someMethod2 () {send (SUCCESS_MESSAGE);} public void someMethod3 () {send (SUCCESS_MESSAGE );} private void send (String message) {// code }}

No. 8: Let the class provide the method that should be provided

Many times, we often operate most of the attributes of a class to get the final result we want. In this case, we should let this class do what it should do, rather than let us do it for it. Most of the time, this process will eventually become the source of repeated code.

Small instance

Class BadExample {public int someMethod (Data data) {int I = data. getI (); int j = data. getJ (); int k = data. getK (); return I * j * k;} public static class Data {private int I; private int j; private int k; public Data (int I, int j, int k) {super (); this. I = I; this. j = j; this. k = k;} public int getI () {return I;} public int getJ () {return j;} public int getK () {return k ;}}} /* --------------------- split line -------------------- */class GoodExample {public int someMethod (Data data) {return data. getResult () ;}public static class Data {private int I; private int j; private int k; public Data (int I, int j, int k) {super (); this. I = I; this. j = j; this. k = k;} public int getI () {return I;} public int getJ () {return j;} public int getK () {return k;} public int getResult () {return I * j * k ;}}}

No. 9: sharding lengthy classes

This technique is actually a very practical technique, but it is ranked behind by LZ because it is relatively difficult. For this technique, it is difficult for LZ to give a small example that is simple and easy to explain, as it is not just a small means.

Most of the time, we should focus on the attributes of a class. The split two batches of attributes can be logically separated. in the Code, the use of these two batches of attributes is also concentrated in some methods. If some attributes exist in the two batches of Split Methods at the same time, you can solve this dependency by passing parameters.

Splitting a class is a relatively large project. After all, a class is often used by many classes in the program. Therefore, This refactoring is very difficult and must be cautious, perform sufficient tests.

No. 10: extract repeated attributes and methods from the inheritance system to the parent class

This technique requires sufficient judgment most of the time. In many cases, it is actually a process of moving towards the template method model. Its instance LZ cannot be provided here because its small instance is meaningless, except that its subclass has the same attributes or methods, delete the repeated attributes or methods of sub-classes and place them in the parent class.

Usually this type of refactoring is not a small project, so this refactoring is similar to the ninth type, and requires sufficient caution and testing. This technique can be used only when you confirm that the attributes or methods extracted to the parent class are common to sub-classes.

Conclusion

As LZ is currently working to maintain a relatively old project, almost all of the above 10 methods have been tried one by one. Fortunately, the results are good.

Due to the fact that the last two methods are too closely related to the actual situation, LZ cannot provide simple instances. However, the last two methods are not commonly used refactoring methods, so they are acceptable. It doesn't matter if you are not often used. You still need to know this. In addition, LZ also needs to say that the above example is just a simple demonstration of the method. In actual application, the structure of the Code may be strange, but it never changes. Therefore, as long as we grasp the core of each technique, it is not difficult to pass through the chaos.

Now, this little sharing is over. I hope you will encourage LZ if you think you have some gains. By the way, you can also let more people see it. In this case, every project code we take over may not be very bad. It is also a new path for project maintainers like LZ.

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.