What is the maximum restriction to improve code reusability? Overcome the reusability limitations of traditional object-oriented programming methods

Source: Internet
Author: User

Reuse is a myth, which seems to be becoming a consensus of programmers. However, Reuse may be difficult to implement, because traditional object-oriented programming methods have some shortcomings in reusability. This section describes three steps to form a different method that supports reuse.

Step 1: Remove a function from a class instance
Because the class inheritance mechanism lacks accuracy, it is not an ideal mechanism for code reuse. That is to say, to reuse a single method of a class, you must inherit other methods and data members of the class. Code that is cumbersome and unnecessary to reuse this method is complicated. The dependency of the inherited class on its parent class introduces extra complexity: Changes to the parent class will affect the subclass. When you change either of the parent classes or child classes, it is hard to remember which methods are covered (or which methods are not covered), and it is unclear whether the corresponding parent class method should be called.

Any method for executing a single conceptual task should be independent and should be used as the preferred method for reuse. To achieve this, we must return to procedural programming, removing code from the class instance method and moving it into the global visibility process. To improve the reusability of such processes, you should write such methods as writing static practical methods: each process only uses its own input parameters and/or calls other global visible processes to complete its work, and should not use any non-local variables. The reduction of this external dependency reduces the complexity of using this process and facilitates reuse of it elsewhere. Of course, even code that is not intended to be reused will benefit from this structure, because its structure is always quite clear.

In Java, methods cannot exist without classes. However, you can take relevant steps to make the method a public-visible static method of a single class. For example, you can use a class like the following:

Class Polygon {
.
.
Public int getPerimeter (){...}
Public boolean isConvex (){...}
Public boolean containsPoint (Point p ){...}
.
.
}


And change it to a format similar to the following:

Class Polygon {
.
.
Public int getPerimeter () {return pPolygon. computePerimeter (this );}
Public boolean isConvex () {return pPolygon. isConvex (this );}
Public boolean containsPoint (Point p) {return pPolygon. containsPoint (this, p );}
.
.
}


PPolygon is as follows:

Class pPolygon {
Static public int computePerimeter (Polygon polygon ){...}
Static public boolean isConvex (Polygon polygon ){...}
Static public boolean containsPoint (Polygon polygon, Point p ){...}
}


The class name pPolygon indicates that the encapsulation process of the class is mainly related to the object of the type Polygon. The p before the class name indicates that the unique purpose of the class is to organize public and visible static processes. However, in Java, class names start with lowercase letters, and classes like pPolygon do not provide normal class functions. This means that it does not represent a class of objects; it is only an organizational entity required by the language.

All the effects of the changes in the above example are that the client code does not have to inherit Polygon to reuse its functions. Currently, this function is provided in the pPolygon class in process units. The client code only uses the functions required by the client, without worrying about the functions that it does not need.

This does not mean that classes will not play a positive role in the new procedural programming style. On the contrary, classes need to execute necessary grouping tasks and encapsulate the data members of the objects they represent. In addition, the class achieves excellent reusability by implementing the polymorphism of multiple interfaces. See the instructions in step 2. However, you should classify methods that obtain reusability and polymorphism through class inheritance into lower-priority technologies because the inclusion of functionality in instance methods is not the best choice for reusability.

The four-person best-selling book Design Patterns briefly mentions a technology that is only slightly different from this technology. The Strategy model in this book advocates the use of a common interface to encapsulate each generation of related algorithms so that client code can swap these algorithms. Because an algorithm is usually written into one or several independent processes, this encapsulation emphasizes reusing the process of executing a single task (that is, an algorithm, it does not emphasize the reuse of objects that contain code and data and execute multiple tasks. This step also embodies the same basic idea.

However, using an interface to encapsulate an algorithm means that the algorithm is written as an object to implement this interface. This means that we are still bound to the process of coupling with data and other methods for encapsulating objects, making reuse complex. It is also a problem that these objects must be instantiated each time an algorithm is used, which will reduce program performance. Fortunately, Design Patterns provides a solution to solve these two problems. When writing a Strategy object, you can use the Flyweight mode so that each object has only one well-known shared instance (this instance handles execution issues ), in this way, each shared object will not maintain the state between two accesses (therefore, this object does not contain any member variables, thus solving many coupling problems ). The generated Flyweight-Strategy Mode highly integrates the encapsulated technology in this step into a globally available stateless process.

Step 2: Convert the input parameter type of the non-basic data type to the interface type
Using the interface parameter type rather than using class inheritance to exploit polymorphism is the real basis for reusability in object-oriented programming methods, just as Allen Holub in "Build User Interfaces for Object-Oriented Systems, as described in Part 2.

"... Reusability is achieved through writing interfaces, rather than writing classes. If all parameters of a method are referenced by some known interfaces that are implemented by classes you have never heard, this method can be used to operate the objects of classes that do not exist during code writing. Technically, the reusable method is not the object passed to the method ."
Apply the Holub statement to the result of step 1. Once a function block can be used as a globally visible independent process, you can convert each of its class-level input parameter types to interface types, so as to further improve its reusability. In this way, the object of any class implementing this interface type meets the requirements of this parameter, not just the requirements of the original class. This process can be potentially used for more object types.

For example, assume that you have a globally visible static method:

Static public boolean contains (Rectangle rect, int x, int y ){...}


This method is used to determine whether a given rectangle contains a given position. Here you should change the rect parameter type from class type Rectangle to interface type, as shown below:

Static public boolean contains (Rectangular rect, int x, int y ){...}


Rectangular cocould be the following interface:

Public interface Rectangular {
Rectangle getBounds ();
}


Now, objects that can be described as Rectangular classes (which can implement the Rectangular Interface) can be passed as rect parameters to pRectangular. contains (). We increase the reusability of the method by relaxing the constraints on the parameters of the passed method.

However, in the preceding example, when the getBounds method of the Rectangle interface returns a Rectangle, you may not know the actual advantages of using the Rectangular interface. That is to say, if we know that the object we want to pass in returns the Rectangle when it is requested, why do we need to pass in the interface type instead of the Rectangle type? The most important reason is the set. Assume there is a method like this:

Static public boolean areAnyOverlapping (Collection rects ){...}


This method is used to determine whether rectangular objects in a given set overlap. Next, in the method body, if you cannot convert an object to an interface type such as Rectangular when processing each object in the Set in sequence, how can you access the rectangle of that object? The only choice is to convert the object to a specific class type (we know that there is a method in this class that can provide rectangle), which means that the method must know in advance what type of operation it wants, therefore, only these types can be used for reuse. This is the first problem to be avoided in this step!

Step 3: select an input parameter interface type with low coupling
In step 2, what interface type should be selected to replace the given class type? The answer is: Any interface that fully describes the process's requirements for parameters and is least cumbersome. The smaller the interface that the parameter object needs to implement, the larger the chance that any specific class can implement this interface -- the more classes the object can use as this parameter. It is easy to see that if you have the following method:

Static public boolean areOverlapping (Window window1, Window window2 ){...}


This method is used to determine whether two (assuming rectangular) Windows overlap. If this method requires only two of its parameters to provide their respective rectangular coordinates, it is better to simplify the types of these two parameters to reflect this fact:

Static public boolean areOverlapping (Rectangular rect1, Rectangular rect2 ){...}


The above Code assumes that the preceding Window object can also implement Rectangular. Now you can reuse the functions contained in the first method of any rectangular object.

You may have had this experience many times, that is, the available interfaces that fully specify the parameter requirements include too many unnecessary methods. In this case, you should define a new public interface in the global namespace so that other methods that may face the same dilemma can reuse this interface.

You may have had this experience many times, that is, it is best to create a unique interface to specify the requirements of a single process for a parameter. The interface you created is only used for that parameter. When you want

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.