What is interface programming?

Source: Internet
Author: User
Oriented Interface Programming(Classic. Reprinted)

Eliminate inheritance and orientation in a rushInterface ProgrammingThese two major problems are not an easy task, especially considering the level of understanding. Frankly speaking, this is another article about "stir-fried rice", but it is really hard to stir-fry it.

Therefore, after reading this article, you can accept (reject) My point of view critically, even though my point of view also comes from others' points of view.

Inheritance is an important concept in object-oriented systems. If Java language features are taken into account, there are two types of inheritance: interface inheritance and implementation inheritance. This is only a technical problem. Even if C ++ does not have the interface concept, its virtual base class is actually equivalent to the interface. For beginners of OO, they really want a lot of inheritance in their programs, because it looks very OO. However, misuse of inheritance can cause many problems, even though we sometimes have to use inheritance to solve the problem.

Compared with interface inheritance, implementing inheritance requires more problems, which leads to more Coupling Problems. But interface inheritance is also problematic, which is a problem of inheritance itself. Many issues of inheritance are due to its own implementation. Therefore, we will focus on the issue of inheritance implementation.

For example (this example is too old ). I want to implement a Stack class. I take it for granted that the Stack class inherits from the ArrayList class (you can also think that I really want to be OO or out-of-nature lazy ); now we have new requirements and need to implement a thread-safe Stack. I have defined a ConcurrentStack class that inherits from the Stack and overwrites some code in the Stack.

Because the Stack inherits from the ArrayList, the Stack has to expose all the public methods of the ArrayList, even if some of them may not be required for it; or even worse, some of these methods may change the status of the Stack, Which is unaware of these changes, which may cause logical errors of the Stack.

If I want to add a new method to the arraylist, this method may logically destroy its derived class Stack and concurrentstack. Therefore, when adding methods (modifying Code) to the base class (parent class), you must check whether these modifications affect the derived class, you have to make further modifications to the derived class. If the inheritance system of a class is not completed by one person, or the Code of another person is modified, it is likely that inheritance produces imperceptible bugs.

There are still some problems. We sometimes see such a base class. Some of its methods only throw an exception, which means that if the derived class supports this method, it will be overwritten, otherwise, an exception is thrown like a parent class, indicating that this method is not supported. We can also see a variant of it. The methods of the parent class are abstract, but not all subclasses support this method. Unsupported methods indicate their positions by throwing an exception. This approach is unfriendly and insecure. They can only be caught at runtime, and many methods of network leakage exceptions may suddenly appear one day, making people feel overwhelmed.

The most important cause of the above problem is the coupling between the base class and the derived class. It is often just a small change to the base class, but it has to refactor all their derived classes. This is the notorious "fragile base class" problem. Because the relationship between classes exists, coupling is inevitable and even necessary. However, when designing Oo, if there is a strong coupling between the base class and the derived class, we have to think about it. Do we need to inherit it? Will there be other more elegant alternatives? If you have to study it, you will see the principle in many books: if the relationship between two classes is IS-A, then use inheritance; if the relationship between the two classes is has-a, use delegate. Most of the time this principle applies, but IS-A cannot be used as an absolute reason to use inheritance. Sometimes, to eliminate coupling issues, delegates and other methods are used to better encapsulate implementation details. Inheritance sometimes exposes too much information externally and downward. In the gof design pattern, there are many patterns to eliminate inheritance.

An important principle about when to adopt inheritance is to determine whether the methods can be shared. For example, DAO can define the common CRUD method in an abstract DAO. The specific DAO is derived from this abstract class. Strictly speaking, abstract DAO and derived DAO implementations do not have a is-A relationship. We just made this technical choice to avoid repeated method definitions and implementations. It can be said that the principle of using interfaces or abstract classes is that if the methods of multiple Derived classes do not share the same content, the interface is used as an abstraction. If the methods of multiple Derived classes contain a common place, abstract classes are used as the abstract class. If this principle does not apply to interface inheritance, it will implement inheritance accordingly (the base class is more of an abstract class ).

OrientationInterface Programming. Among the many agile methodsInterface ProgrammingIt is always repeatedly emphasized by masters. OrientedInterface ProgrammingIn fact, it is oriented to abstract programming and isolates abstract concepts from specific implementations. This principle enables us to have a higher level of abstract model. In the face of changing needs, it is much easier to modify the code as long as the abstract model is well done. ButInterface ProgrammingIt does not mean that an interface must correspond to a class. Too many unnecessary interfaces may bring more workload and maintenance difficulties.

Compared with inheritance, the concept of polymorphism in OO is more important. An interface can correspond to multiple implementation classes. For method parameters and class fields declared as interface types, they are easier to expand and stable than implementation classes, which is also the advantage of polymorphism. If I define a method void doSomething (ArrayList list) using an implementation class as a method parameter, but if the leader someday thinks that ArrayList is not as useful as a lateral list, I will have to refactor the method to void doSomething (writable list) and modify the parameter type in all the places where this method is called (unfortunately, I used the ArrayList list = new ArrayList () method to create even objects, which greatly increased my modification workload ). If the leader thinks that using list to store data is not as good as set, I Will refactor the method again, but this time I become smarter. I define the method as void doSomething (Set set ), change the object creation method to Set set = new HashSet (). But this is still not enough. What should I do if the leader asks to change set back to list? Therefore, I should refactor the method to void doSomething (Collection collection Collection). The Collection has the highest degree of abstraction, making it easier to replace the specific implementation class. Even if List or Set features are required, I can perform a downward type conversion to solve the problem, although this is not safe.

OrientedInterface ProgrammingThe most important value is to hide implementations and encapsulate abstract implementation details without opening them to the outside. encapsulation is especially important for hierarchical design and Framework Design in Java EE. However, even if an interface is used for programming, We need to map the interface with the implementation, which leads to the issue of how to create an object. In the creation design mode, Singleton, factory method (template method), Abstract Factory and other modes are good solutions. Currently, the popular control reversal (also called dependency injection) mode connects abstraction and implementation in declarative manner, which reduces monotonous factory classes and makes unit tests easier.

Make a summary. Although I try my best to refute the bad inheritance and advocate the good interface, This is not absolute. Misuse of inheritance and interface can cause problems. Many of my friends who develop Java EE complain about the implementation method of a class in the DAO and Service interfaces, although they seem to have become one of the best practices in the industry. The elimination of interfaces may make the program more "thin", but "thin" must be "good", depending on the specific circumstances of the project. For the best practices of inheritance and interfaces, you still need to accumulate and summarize your own experience.

 

 

Yi Ma Pingchuan 19:58:54
An interface is an abstraction of a class.
Yi Ma Pingchuan 20:00:47
If I tell you directlyInterface Programming, You certainly do not understand, or it is difficult to understand, because the interface itself is very abstract, Now I will give you an example
Yi Ma Pingchuan 20:01:38
The power outlet is the interface
Yi Ma Pingchuan 20:01:45
For example
Yi Ma Pingchuan 20:02:01
Two-hole socket
Yi Ma Pingchuan 20:02:04
With three holes
Yi Ma Pingchuan 20:02:18
Different plugs require different sockets
Yi Ma Pingchuan 20:02:36
The interface describes the available plug range.
Yi Ma Pingchuan 20:03:04
There is a socket with three holes, but it can be inserted with either three holes or two holes. Do you know?
Yi Ma Pingchuan 20:03:43
So, we can say that this socket is well designed.
Yi Ma Pingchuan 20:03:57
Because it can be applied to a wider range
Dust 20:05:10
Well.
 
Yi Ma Pingchuan 20:04:20
Of course, this range cannot exceed the power outlet concept
Yi Ma Pingchuan 20:04:55
It is not suitable for Pen insertion or pen writing.
Yi Ma Pingchuan 20:05:45
If the power outlet can not only be used with two-hole and three-hole plugs, but also with a pen, we can say for sure that this interface is too poorly designed.
 
Yi Ma Pingchuan 20:06:41
Because the interface (outlet) should be designed to abstract a certain type of things
 
Yi Ma Pingchuan 20:07:39
In addition, after the interface (socket) is implemented, the class (plug) implementing the interface must comply with the interface definition (matching the socket and plug-in ),
Yi Ma Pingchuan 20:07:52
And must be fully compliant
Yi Ma Pingchuan 20:08:02
None at all.
Yi Ma Pingchuan 20:08:19
Therefore, all the methods defined in the write interface must be used to implement an interface class.
Yi Ma Pingchuan 20:09:08
If you think this method does not need to be implemented, leave it blank.
Yi Ma Pingchuan 20:09:13
But it must be rewritten.
Yi Ma Pingchuan 20:09:53
The interface only defines the prototype of the method, that is, the parameter and method name and return value. The class of the integrated interface needs to implement it.
Yi Ma Pingchuan 20:10:51
Let me look at this sentence:
Yi Ma Pingchuan 20:08:18
In addition, after the interface (socket) is implemented, the class (plug) implementing the interface must comply with the interface definition (matching the socket and plug-in ),
Yi Ma Pingchuan 20:11:55
In fact, you will find that, after the outlet is produced, if the plug of an electric appliance does not match the outlet, you will not be able to use it.
Yi Ma Pingchuan 20:16:28
In fact, when you design an interface, it is hard to think about how to design it, even though you know what the class integrating this interface is like.
Yi Ma Pingchuan 20:17:27
Just like if you open a factory to produce plug-in boards, it is difficult for you to produce usable plug boards when you do not know the electrical appliance or how the electrical plug is designed.
Yi Ma Pingchuan 20:18:03
So how to design the plug-in board? Or how to design interfaces?
Yi Ma Pingchuan 20:18:39
Let's take a look at how the plug-in board manufacturer produces it.
Yi Ma Pingchuan 20:19:50
One day, when someone made an electric appliance with four holes, it would be useless.
Yi Ma Pingchuan 20:21:12
At this time, the plug-in board manufacturer to produce a plug-in board, can be applied to most of the current electrical appliances, but also for future electrical appliances, he found a mechanism
Yi Ma Pingchuan 20:21:43
Organizations specify rules and formulate agreements.
Yi Ma Pingchuan 20:22:28
The organization called the heads of most important electrical appliance manufacturers and held a meeting with the plug-in board owner.
Yi Ma Pingchuan 20:22:44
Everyone decided on an agreement for the common benefit.
Yi Ma Pingchuan 20:24:15
The agreement is as follows: the electrical plug produced by the electrical appliance manufacturer later can only produce three holes, but to be compatible with the existing electrical appliances on the market, it can also produce two holes, but try to produce three holes. In addition, the size of the hole and the distance between them are clearly defined.
Yi Ma Pingchuan 20:25:00
The plug-in board manufacturer's plug-in board can only have two and three holes, and the size and distance between the holes must also be produced according to the protocol.
Yi Ma Pingchuan 20:25:10
So the problem is solved,
Yi Ma Pingchuan 20:25:53
The plug-in board manufacturer's boss is very clever. He found that he could produce plug-ins that can be inserted with two or three holes, so he sold the plug-in board and made a fortune.
Yi Ma Pingchuan 20:26:47
An excellent interface design has brought him great benefits, but he is very smart. He hasn't forgotten that everything is blank if there is no standard agreement.
Yi Ma Pingchuan 20:30:00
I 'd like to add a few more words, or you will still be hard to understand.
Yi Ma Pingchuan 20:31:32
When you want to design an interface, you 'd better first write a few classes that will inherit these interfaces, write a few classes with only a framework but no actual content, and look at the commonalities between them, find the point where the interface is written, just as if you were in a meeting with the electric appliance boss.
Yi Ma Pingchuan 20:32:56
When writing an interface, you need to describe the interface before, describe the applicability of the interface, and the precautions for inheriting the interface. This is like asking the organization to develop protocol specifications.
Yi Ma Pingchuan 20:34:12
With this, your interface will not be used incorrectly when it is used. When writing a class that inherits this interface, it will also completely match the interface according to the specifications.
Yi Ma Pingchuan 20:36:07
In the last sentence, even if you understand every sentence I said tonight, you still won't write the interface, because you need to practice it to get the truth. The last sentence is a famous saying. I am talking about nothing (after you have learned to write interfaces ).

 

When I write an interface for the first time, the first feeling is that the write interface is the same as the write interface. Define an interface and immediately write the implementation class! In fact, at this time, I used the process-oriented idea to write a program, and then hung up with a goat's head. How can I say there be an interface too!

Today, I saw my experiences with interfaces written by a dude. I really feel the same way!

Do not use interfaces for interfaces. When you think about yourself improperly as a programmer, you can think about the ideas of employing people. You will not write programs, we will not consider the implementation of details! At this time, the question you are concerned about is abstract. Do you think this is not in line with the object-oriented principle? When Zhang Sanfeng taught him that he had to forget all his tricks. Before defining interfaces, he forgot that he was a programmer!
 
Of course, there cannot be 100% abstractions. In the end, you still need to go back to the implementation details, but at this time you have learned to be a secret of Taiji!

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.