Protocol (object-oriented programming)
From Wikipedia, the free encyclopedia
The factual accuracy of this article is disputed. Please see the relevant discussion on the talk page. (March 2008) |
It has been suggested that Concept (generic programming) be merged into this article or section. (Discuss) |
In object-oriented programming, a protocol or interface is what or how unrelated objects use to communicate with each other. These are definitions of methods and values which the objects agree upon in order to cooperate.
For example, in Java (where protocols are termed interfaces), there is the Comparable interface specifies a method compareTo() which implementing classes should implement. So, this means that a separate sorting method, for example, can sort any object which implements the Comparable interface, without having to know anything about the inner nature of the class (except that two of these objects can be compared by means of compareTo()).
The protocol is a description of:
- the messages that are understood by the object,
- the arguments that these messages may be supplied with, and
- the types of results that these messages return.
- the invariants that are preserved despite modifications to the state of the object
- the exceptional situations that will be required to be handled by clients to the object
If the objects are fully encapsulated then the protocol will describe the only way in which objects may be accessed by other objects.
Some programming languages directly support protocols or interfaces (Objective-C, Java, C#, D, Ada, Logtalk). Older languages may also have features that can support the interface concept, such as abstract base classes with pure virtual functions in C++, or object-oriented features in Perl.
Note that functional programming and distributed programming languages have a concept which is also called a protocol, but whose meaning is subtly different (i.e. a specification of allowed exchanges of messages, emphasis on exchanges, not on messages). This difference is due to somewhat different assumptions of functional programming and object-oriented programming paradigms. In particular, the following are also considered as part of a protocol in these languages:
- The allowed sequences of messages,
- Restrictions placed on either participant in the communication,
- Expected effects that will occur as the message is handled.