Download presentation
Presentation is loading. Please wait.
1
Component-Based Software Engineering
Components and Interfaces - Part 2 Paul Krause
2
Lecture 3 - Interfaces Contents Interfaces as Contracts
Interfaces vs. Abstract Classes A Digression on “Casting” making lawyers human Specifying Pre- and Post-conditions Using assertions to check Conditions
3
Components and Interfaces
B1 B2 A requires certain functionality to fulfil its obligations. B1 and/or B2 provide that functionality. An interface mediates between clients and providers.
4
Interfaces as contracts
Can view an interface specification as a “contract” between the client and a provider So the interface specification must state: What the client needs to do What a provider can rely on What a provider must promise in return What the client can rely on
5
Pre- and Post-Conditions
Pre-conditions: What the client must establish before calling the operation The provider can rely on this condition being true whenever the operation is called Post-conditions: What the provider must establish before returning to the client The client can rely on this condition being true whenever the call to the operation returns
6
Interfaces Sometimes we may find two or more different subclasses share some common behaviour In this case, they are not strictly “kinds of” some common parent Rather, they “behave like” some common pattern (under certain circumstances) We say that they both implement a common interface
7
A “Cashier” Interface «interface» Cashier withdraw deposit Person
Machine Employee ATM
8
Java interfaces Note: public interface Cashier {
public void deposit(int id, double amount); public boolean withdraw(int id, double amount); } Note: An interface is pure specification - it contains no implementation
9
Lecture 3 - Interfaces Contents Interfaces as Contracts
Interfaces vs. Abstract Classes A Digression on “Casting” making lawyers human Specifying Pre- and Post-conditions Using assertions to check Conditions
10
cf Abstract Classes
11
Abstract Class vs. Interface
public abstract class EllipticalShape { public abstract double area( ); public abstract double circumference( ); } public interface Cashier { public void deposit(int id, double amount); public boolean withdraw(int id, double amount);
12
What are the differences?
Abstract Class Can include class and instance fields May include concrete implementations of methods A concrete class can only extend a single abstract class Interface Can only include static final fields All methods must be abstract declarations - no implementation A class can implement multiple interfaces
13
Why use interfaces? Design Guideline:
“When the functionality supported by a class can be implemented in different ways, it is advisable to separate the interface from the implementation” Xiaoping Jia Object-Oriented Software Development Using Java
14
invokes notifications in
Chili PizzaExpress EventObject source getSource() toString() «interface» OrderListener pizzaStatus(evt) PizzaEvent fires passed to Bakery addOrderListener() removeOrderListener() sendMessage(PizzaEvent) Customer run( ) iNumber iSliceNumber registers with 0..* invokes notifications in 0..*
15
Class Bakery private void sendMessage(PizzaEvent anEvent) { Vector v;
synchronised(this) { v = (Vector) iCustomers.clone( ); } for (int i=0; i<v.size( ); i++) { OrderListener ol = (OrderListener)v.elementAt(i); ol.pizzaStatus(anEvent);
16
General Idiom To send an event to a Customer, the Bakery needs to know: the name of the method to invoke in a Customer the type of the Event to send when invoking the respective method this information is contained in the OrderListener interface that is all the Bakery needs to know
17
Lecture 3 - Interfaces Contents Interfaces as Contracts
Interfaces vs. Abstract Classes A Digression on “Casting” making lawyers human Specifying Pre- and Post-conditions Using assertions to check Conditions
18
A Diversion on “Casting”
In the last example, we were only interested in the “OrderListener” behaviour of Customers: OrderListener ol = (OrderListener)v.elementAt(i); We “cast” an element of the Vector v This is a way of converting one type to another, subject to certain rules
19
Casting between Data Types
Suppose I wish to add a double precision value to an integer, and just keep the integer value of the answer: double x = 24.2; int y = 1; int z = (int) (x - y); We have explicitly cast (“converted”) the result of the calculation into an integer
20
Rules for Data Types An explicit cast is needed when converting from a “larger” (more information) type to a “smaller” one (e.g. double to int) This is not needed when casting to a larger type - the compiler will do it for you
21
Rules for Casting Objects
An instance of a class may only be cast into subclasses or superclasses in its inheritance hierarchy Human h; Lawyer l; l = new Lawyer( ); h = (Human) l; You can use an instance of a class, anywhere an instance of one of its superclasses is expected
22
OrderListener ol = (OrderListener)v.elementAt(i);
W.r.t. Interfaces You can cast an object to an interface type if (and only if) the class of that object implements the interface This will give full access to the services provided by the interface,e.g.: OrderListener ol = (OrderListener)v.elementAt(i);
23
Lecture 3 - Interfaces Contents Interfaces as Contracts
Interfaces vs. Abstract Classes A Digression on “Casting” making lawyers human Specifying Pre- and Post-conditions Using assertions to check Conditions
24
Back to interfaces? Design Guideline:
“When the functionality supported by a class can be implemented in different ways, it is advisable to separate the interface from the implementation” Xiaoping Jia And we can cast an object into its interface type if we only want to access its services
25
List as an example public interface List { public int size( );
public boolean isEmpty( ); public Object element(int i); public Object head( ); public Object last( ); public void insert(Object item, int i); public void insertHead(Object item); public void insertLast(Object item); // more… }
26
Implementations of List
We can have several different implementations of the List interface: public class LinkedList implements List { <body of Linked List here> } or: public class DynamicArray implements List { <body of DynamicArray here>
27
Interfaces as Contracts
Interfaces specify the types of their associated methods, but say nothing about their behaviour We can improve on that!
28
Pre- and Post-Conditions
Pre-conditions: What the client must establish before calling the operation The provider can rely on this condition being true whenever the operation is called Post-conditions: What the provider must establish before returning to the client The client can rely on this condition being true whenever the call to the operation returns
29
Stage 1: Documentation Use and as special tags for preconditions and postconditions: /** * @pre precondition * @post postcondition */ public void method1 { // … }
30
A boring example /** * Returns the number of elements in a list *
true @nochange */ public int size( );
31
A more interesting example
/** * Returns the i-th element in the list * i >= 0 && i < size( ) @nochange */ public Object element(int i);
32
Other logical expressions
==> logical implication <==> logical equivalence @forall x : Expression Universally quantified expression @exists x : Expression [m … n] Integer range from m to n
33
A nasty example /** * Inserts a new element into a list at the i-th position * item != null && i >= 0 && i <= size( ) size( ) == size( + 1 * k : [0 .. size( ) - * (k < i ==> == element(k)) && * (k == i ==> == element(k)) && * (k > i ==> == element(k) */ public void insert(Object item, int i);
34
An exercise Use this method to specify the interface to a method that inserts a new element to the head of a list
35
Solution /** * Inserts a new element at the head of a list *
item != null size( ) == size( + 1 == element(0) k : [1 .. size( ) - 1] @ == element(k) */ public void insertHead(Object item);
36
How does this help? As this stands, the comments provide guidance only
They prescribe what should be done, but are agnostic about whether a specific implementation satisfies them We can, however, provide run-time checks through the use of Assertions
37
Lecture 3 - Interfaces Contents Interfaces as Contracts
Interfaces vs. Abstract Classes A Digression on “Casting” making lawyers human Specifying Pre- and Post-conditions Using assertions to check Conditions
38
Assertions are? Boolean conditions that are inserted into a program at strategic points We expect them to be true when the flow of control reaches each respective point If an assertion is true, it has no effect and the flow of control continues If an assertion is false, then execution stops at that point and an AssertionError is thrown
39
Where do you put them? Assertions on the preconditions of a method should be placed immediately on entry to the method Assertions on postconditions should be placed just prior to the return statement But remember that any references to the pre-state of variables must be instantiated upon entry to the method
40
LinkedList implements List
/** item != null && i >= 0 && i <= size( ) size( ) == size( + 1 */ public void insert(Object item, int i) { assert item != null && i >= 0 && i <= size( ); int size_pre = size( ); // // < body of method here … > int size_post = size( ); assert size_post == size_pre + 1; }
41
Extra points to note Need JDK 1.4 or higher, and compile using:
javac -source 1.4 Class.java In order to fully assert the postconditions, we usually need to clone an instance of a class before we modify it Use of assertions derived from preconditions is known as Defensive Programming Use of assertions derived from postconditions is also valuable in testing and debugging
42
Summary We have discussed the use of interfaces when there may be multiple ways of implementing certain functionality Including statements of pre- and post-conditions in the comment lines for each method declaration makes a richer specification Including the pre- and post-conditions in the implementation of each interface adds a further level of rigour (but has limited support in Java at present)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.