Refactoring 36 (1-6)

Source: Internet
Author: User
Tags constant definition

Refactoring is actually very simple. Its purpose is to make the program easier to understand, more maintainability, and more reasonable structure. Refactoring should be an essential part of code writing. For example, a better name for a function and splitting a large function into several small functions are all refactoring. The typical restructured books include Martin flower's refactoring-improving the design of existing code, and Joshua kerievsky's refactoring and pattern. the so-called 36th in this series is the most frequently used refactoring strategy and coding principles over the years. I have summarized it myself and mentioned it in the book. I hope it will help you.

 Measure 1: objectization of the parameter list

The parameters of a public function should be kept unchanged as much as possible, because they are called in many places. After modifying a parameter, You need to modify its calling location. In addition, the parameter list should not be too long, keep the number within 5 as much as possible. The long parameter list increases the difficulty of calling the function. For public functions with many parameters or frequently changing parameters, it is better to introduce the parameter object, that is, the function has only one parameter, which is the parameter object, specific parameters are declared in this object. Introducing parameter objects for functions has the following benefits:

1. To maintain the immutability of the function interface, you only need to modify the member variables in the parameter object to modify the function parameters.

2. Easy to call. The caller no longer needs to care about the order of parameters.

The following code snippet is a declaration for adding user functions:

 

public long insertUser(String name,int age,String email,String address,String phone,String birthDay)

 

Each time a user's field is added or deleted, the insertuser parameter list must be modified. The caller also needs to modify the list of insertuser parameters, which are hard to remember when many parameters exist.

The following is the form after the parameter object is introduced:

 

public class UserParam{  public String name;  public int age;  public String email;  public String address;  public String phone;  public String birthDay;}public long insertUser(UserParam user);

 

Second, conditional operators assign values instead of if else.

You can assign values to variables based on conditions in either of the following ways:

 

int value;if(condition)  value = 1;else  value = 2;

 

The other is through conditional operators:

 

int value = condition ? 1 : 2;

 

The second method is obviously better than the first method, but many people love the first method, probably because if-else is used to it.

 

Third: Saving System Resources

Even when writing code, we should also develop a "frugal" habit. Do not waste the resources provided by the system. For those objects that occupy space and affect performance, it should not be created or initialized until it is actually used. Therefore, in the function implementation that provides these objects, try to use the following form:

 

// Public class databaseconnectionholder {private connection conn; public connection getconnection () {If (conn = NULL) {conn = new connection (); Conn. init () ;}return conn ;}}

 

In addition, we can introduce a caching mechanism (such as an object pool) to make full use of system resources. For more information, see the Design Pattern not mentioned in the gof book (5): Object pool.

 Fourth: Introduce abstract versions for interfaces

When declaring a new interface, it cannot be guaranteed that the interface will not be modified. It may be modified frequently. Each time you modify the interface, you must modify the corresponding implementation class, if an interface is part of a public library, the interface modification cost is high. All programs using this interface need to be modified and compiled again ..., you can solve this problem by introducing an abstract version to the interface. For example, you can add an abstract class for the following interface:

 

public interface Widget{  public void draw();  public void layout();  public void invalidate();  public void show();}

 

public abstract class AbstractWidget implements Widget{  public abstract void draw();  public void layout(){};  public void invalidate(){};  public void show(){};}

 

In this way, the widget implementation class can be inherited directly from javasactwidget. If you want to modify the widget interface, you only need to modify javasactwidget, which has no effect on other implementation classes.

 

Fifth: eliminate magic count

New programmers generally write numbers that represent the type or state directly in the processing logic. The author of the code can understand the meaning of the number, but other people may not understand this code. Even if the author of the code looks at this part of the code for a while, it may forget the meaning of the number. In addition, it is very tedious to modify the value of the magic number, it is very likely that there will be some omissions, so the best way is to completely eliminate all the magic numbers in the program, through constant definition, enumeration and other methods to avoid the emergence of magic numbers.

 

Sixth: Use assertions and exceptions to ensure the correctness of the implementation

The purpose of assertion is to inform other programmers of the rules that must be observed somewhere in the Code. It is a method in the debug version to ensure the correctness of the program implementation. In the officially released version, assertions do not work. In Java, you need to add a compilation option to enable assertions. However, exceptions can be thrown to achieve the same purpose, which is more dangerous than assertions, it is because a crash occurs in the official release of the program, but sometimes the crash is better than the strange behavior of the program, for example:

// Indicates the public class collection of the set {// add elements to the set public void addelement (Element E ){}; // obtain the public void getelement (INT index) {};} element at the specified position ){};} // indicates the public class readonlycollection extends collection of the read-only set {// Add the element to the set public void addelement (Element E) {Throw new unsupportedoperationexception ("read-only set, element ") not allowed to be added;} // obtain the element public void getelement (INT index) at the specified position ){};}

To call the readonlycolletion derived class, you must follow the rules: you cannot call addelement; otherwise, an exception will be thrown to kill the program!

 

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.