This maximizes code reusability and overcomes the shortcomings of traditional object-oriented programming methods in reusability.

Source: Internet
Author: User
Tags what interface
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 ){...}
Static public Boolean isconvex (polygon ){...}
Static public Boolean containspoint (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. This often happens when you want to treat a parameter as a function pointer in C. For example, suppose there is a process like this:

Static public void sort (list, sortcomparison comp ){...}

This process compares all objects in the list by using the given comparison object comp, so as to sort the given list. All requirements of sort for comp are to call a single method for comparison. Therefore, sortcomparison should be an interface that contains only one method:

Public interface sortcomparison {
Boolean comesbefore (Object A, object B );
}

The unique purpose of this interface is to provide sort with a way to access the functions required to complete its work. Therefore, sortcomparison should not be reused elsewhere.

Summary
The above three steps aim to improve the existing code written in a more traditional object-oriented method. By combining these three steps with object-oriented programming, you can build a new method. You can use this new method to compile future code, writing code in this way will improve the reusability and cohesion of methods, and reduce the coupling and complexity of methods.

Obviously, you should not perform these steps on code that is not suitable for reuse. This type of code usually exists in the program's presentation layer. Creating code on the user interface of the program and binding the input event to the control code for completing the actual operation are two examples that cannot be reused, because their functions differ greatly from those of the program, it is impossible to achieve reusability.

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.