Reconstruction 36 (31-36)

Source: Internet
Author: User

31st: Empty unused objects

In C ++, after an object is destroyed, you must set the pointer to null. Otherwise, a wild pointer will appear. It is best to write it as below. After the delete operation, it is immediately set to null,

delete pObject;pObject = NULL;

In Java, when an object is no longer needed, it is better to set it to null, which is conducive to garbage collection.

 

32nd: good at using interfaces

1. Callback Interface

In C language, callback functions can be implemented through function pointers. Java has no pointer concept and can use interfaces to achieve the same purpose. For example:

  public interface Callback{     public void onChanged();  }  public void execute(Callback callback){     ...     callback.onChanged();     ...  }

 

2. Mark Interface

This type of interface does not contain the declaration of the function, that is, the interface is empty. It is mainly used to make the class that implements this interface indicate that it has a certain feature and plays a marking role, for example, the following interface:

Public interface millionaire {} public class member extends user implements millionaire {...} public Boolean check (User user) {If (User instanceof millionaire) // This is a millionaire, and let it pass return true directly ;...}

 

3. Dependency Injection Interface
This interface is generally used in the factory method to selectively inject object references or data to the object to be created. For example:

Public interface dataaware {public void setdata (data);} public interface databaseconnectionaware {public void setconnection (connection conn);} // public class userservice extends Service implements dataaware, databaseconnectionaware {public void setdata (data); Public void setconnection (connection conn);} // create a service object public service createservice (INT type) {Service = NULL; if (type = user) {service = new userservice (); If (Service instanceof dataaware) // if it wants data, it injects the Data Object (dataaware) Service ). setdata (data); If (Service instanceof databaseconnectionaware) // if it wants to connect to the database, inject the connection object (databaseconnectionaware) Service ). setconnection (conn); return service ;}

 

 

4. Constant Interface

All constants are defined in the interface. In this way, all related classes can implement this interface, which is equivalent to defining these constants in these classes, while other classes can reference these constants through the constant interface.

 

33rd: simplifying class relationships

If the relationship between classes is complex, it is likely that the object-oriented design is not well done. Generally, two classes have a two-way call relationship, which means they are not clear enough about their responsibilities. For example, one class (a) frequently calls a function of another class (B, in addition, a also transmits member variables as parameters to B. In most cases, the function should be defined in a to cut off the relationship between the two. In addition, there are many classes in the system that are interested in status changes or events of some classes, such as adding a new user or changing the network status, it is best to use various message mechanisms to achieve decoupling between them, such as the observer mode and the publish and subscribe mode. For more information about publishing and subscription modes, see the design patterns not mentioned in the gof book (7): publish-subscribe

 

34th: Replace the similar conditional with Polymorphism

When the processing logic of some functions in a class is very similar and different actions are taken based on a state value or a type value, the class needs to be split into multiple classes, for example, there is a class that represents the shape:

Public class shape {private int type; Public void draw () {If (type = 0) // if it is a rectangular drawrect (); else if (type = 1) // if it is a circular drawcircle (); else if (type = 2) // if it is a straight line drawline ();} public Boolean ispointin (float X, float y) {If (type = 0) // if it is a rectangle return ispointinrect (x, y); else if (type = 1) // if it is a circular return ispointincircle (X, y); else if (type = 2) // return ispointinline (); Return false ;}}

These two member functions contain similar processing logic and are processed based on the Type value. In this case, we should make full use of the polymorphism in the object-oriented model, the following is the form of splitting into multiple classes:

 

public abstract class Shape{    public abstract void draw();    public abstract boolean isPointIn(x,y);}public class Circleextends Shape{    public void draw(){       drawCircle();    }    public abstract boolean isPointIn(x,y){       isPointInCircle(x,y);    }}public class Rect extends Shape{    public void draw(){        drawRec();    }    public abstract boolean isPointIn(x,y){        isPointInRect(x,y);    }}public class Line extends Shape{    public void draw(){       drawLine();    }    public abstract boolean isPointIn(x,y){       isPointInLine(x,y);    }}

 

 

35th plan: reasonably layered, separated interface display and business processing logic

Low code coupling is one of the key factors to ensure Software maintainability. layering is a common method to achieve low code coupling and can also achieve effective division of labor. For example, in enterprise-level web development, generally, the following layers are divided:
1. Data access layer, which allows you to add, delete, modify, and query databases. It is generally implemented using the ORM framework, such as Hibernate and LINQ.
2. the business service layer completes all business processing logic
3. The request control layer processes client requests, delivers services to the service layer for processing, and returns the processing results in some form (HTML, JSON, etc.) to the client.
There will also be similar layers in the implementation of local applications. For example, the document-View Structure in MFC is also the separation of interface display and business processing logic. Therefore, in the code, avoid cross-referencing between interface objects and business objects, especially in systems with multiple interface rendering methods.

 

36th: Determine the parameter Validity

Function parameter validity judgment is an important part of function implementation, especially as a public member function of the class's external interface, for example, to determine whether the object in the parameter is null and whether the parameter value is valid, these tasks should be completed at the beginning of function implementation, when a parameter is found invalid, an exception can be directly returned, an exception can be thrown, or the default value of the parameter is provided. Do not use non-code methods (such as call conventions) to ensure the validity of the parameter, assertions do not completely guarantee that the parameters used for function execution are valid unless all public functions can be executed during program release. Therefore, parameter validity judgment is an essential part of function implementation.

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.