Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^10) CHAPTER 1 ■ ABSTRACT CLASSES, INTERFACES, AND PROGRAMMING BY CONTRACT
Development teams frequently program by contract because of the many workflow improve-
ments this technique brings. By defining the interaction of classes before any implementation
begins, the team members know exactly what their objects must do; it is then fairly trivial to
implement the required methods. When the interface is fully implemented, testing of the class
will be conducted using only the rules defined in the interface.
In the car example you’ve seen in previous sections, the ISpeedInfo interface could be
considered a contract, as it is the only point of API interaction of which either class, Car or
Street, needs to be aware. The Street class will test for this contract before accepting the
object for interaction. One developer could then be assigned to create a Car class and another
to create a Street class, and the two would not need to collaborate on the implementation
beyond the IStreetInfo interface.
In Chapter 7, we will revisit this concept of programming by contract in the context of
application plug-ins.
Just the Facts
Abstract classes are classes that are declared with the abstract keyword. They allow you to defer
declaring a method’s implementation by marking it as abstract. To declare a method as abstract,
you simply omit the body, including all braces, and terminate the line with a semicolon.
Abstract classes cannot be directly instantiated—they must be derived. If a class inherits
from an abstract class, it must also be declared abstract when it does not implement all the
abstract methods in the base class.
Interfaces are like abstract classes in that you can declare method prototypes without
method bodies. They differ from abstract classes in that they must not declare any methods
with method bodies. They also have different usage syntax. Instead of extending from an inter-
face, you use the implements keyword to put in force an interface’s rules on a class.
In some cases, you will want to determine if a class is of a certain type or if it implements a
specific interface. The instanceof operator is particularly useful for this task. The instanceof
operator checks three things: if an instance is of a specific type, if an instance derives from a
specific type, and if an instance or any of its ancestors implement a specific interface.
Some languages have the ability to derive from multiple base classes, which is called multiple
inheritance. PHP does not support multiple inheritance. Instead, it gives you the ability to
declare multiple interfaces per class.
The ability of interfaces to declare rules that classes must follow is extremely useful. The
programming by contract technique uses this capability to enhance encapsulation and opti-
mize workflow.
McArthur_819-9C01.fm Page 10 Tuesday, December 18, 2007 7:38 AM

Free download pdf