ࡱ>  #"!5h(` CP/ 0|DTimes New Romanhh< 0DTempus Sans ITChh< 0R DGeorgiaans ITChh< 00DBook AntiquaTChh< 0@DArial NarrowTChh< 0"Gf.  @n?" dd@  @@``   h#& ` 9P!3PGQQGHGG*6333.%Dmk0"*#6$%&   '  #0' /% 2    = >@ D H 0e0e    A A5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E||S" f)))@ʚ; #.ʚ; g4SdSdp 0ppp0 <4!d!d4w 0h<<4dddd4w 0h<g4UdUd8 0J p p <4BdBd4w 0h<0___PPT10 ppZ___PPT9<4? tGrundlggende programmering p fleksibel uddannelse, F2001O =V3OOP F2005 Lecture 7 Interfaces & Design by Contract44!3)Kasper sterbye IT University Copenhagen 4*!#|Today's schedulePDesign by Contract why the term contract what design issue is captured, and why bother what is a pre-condition what is a post-condition what is a class invariant How to do this in Java. you cannot, only in documentation experimental java s exist Assert in Java loop invariants design by contractb<#< #Design by contractbConsider the service offered by the Danish postal service: For 4.50 dkr, they will deliver a letter to the address printed on the front of the envelope, if the letter is posted in Denmark, if it is less than 23x17x0.5 cm. If it is handed in before a given time of the day, there are a next day delivery guarantee. The advantage for me is that I know how much postage to put on a standard letter, I know when to post it, and when I should expect it to arrive. The advantage for the postal service is to receive 4.50, not to have obligations for late delivery, and not to have obligations for odd size letters.ccD  class DanishMailBox { & /*pre: l is within size restrictions & current time is before postingDeadline post: letter l is delivered at address next day */ public void sendStandardLetter(Letter l){& } public Time postingDeadline(){& } & } P TH  Iterator contract I( An iterator is an object which will provide sequential access to a collection. The java.util.Iterator<E> interface has the following methods : boolean hasNext() E next() void remove() hasNext returns true if the iterator is not empty. next returns the head, and moves to tail. remove removes the head from the underlying collection  or throws an UnsupportedOperationException v)S#)H* Iterator contract II4 LAn empty pre-condition means that the method can always be called. Notice, it is the responsibility of the caller to make sure that next() and peek() is not called when the list is empty. Notice, we will assume that the iterator does not change as a result of a call to cloneMe(), since nothing is stated to indicate such behaviourMM,*7 public interface Iterator { /* pre: none * post: return true if the iterator is not empty. */ boolean hasNext(); /* pre: hasNext() * post: return head of old.iterator & this is old.tail. */ Object next(); /* pre: next has been called & remove has not already been called & remove is supported by this iterator * post: removes the last element returned by next*/ void remove(); }B. N An array iterator .This iterator will iterate over the elements in an array which is given as argument to its constructor. The iterator can be used as: String[] names ={ Bill ,  Ben , Jack }; ArrayIterator itr = new ArrayIterator(names); while ( itr.hasNext() ) System.out.println( itr.next() ); But, will this actually print out the right elements? To examine this, we need to compare the implementation of each method to the contract to see if the ArrayIterator satisfies the Iterator contract, and not just defines methods with the right signature,`9   A public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   )$%-  Class invariantsBut, we cannot see if the body does the right thing in isolation from the class itself. What is the the value of index, and what is theArray? A class invariant is a postulate on the fields of a class. The postulate is supposed to be true after each method has finished, and after the constructor has finished. It is the programmers responsibility to make certain that the invariant is maintained. If we assume that the invariant is as in the drawing, then hasNext() is correct.& 2,? /* pre: none * post: return true if the iterator is not empty. */ public boolean hasNext(){ return index < theArray.length; }$]#PP)$Array Iterator, next and constructorBReg. next. We assume the invariant is true, and hasNext() is true, that is the iterator is not empty. Thus, we know that index refers to head, which is what we return. But we also increments index by one, which is what is needed to make sure that the iterator now is its tail. Reg. the constructor The precondition ensures that we will not attempt to iterate null. if objects has elements in it, then index=0 is the head of the iterator if objects it empty, then length is 0, and index is not less than 0, hence the iterator is empty. In both situations the invariant is true.CCb0P6 /* pre: hasNext() * post: return head of iterator; this is old.tail. */ public Object next(){ return theArray[index++]; } /* pre: objects != null * post: invariant */ public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } P76     Invariants and encapsulationPlease observe the wording used when arguing for the pre/post conditions. They all say,  If the invariant is true, then so and so and so and so, therefore the invariant is still true . But what if the invariant is not true? This is why it in general is a good idea to make fields private. If the index field was made public, then we could not be sure the invariant was valid, as someone might had changed it from the outside. Also notice that one should be very careful with  setter methods for variables mentioned in the invariant. A setter for the index would be as bad as making it publicXX= public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   *$%-  An invariant on Persons and Cars7Consider the exercise on Persons and Car from lecture 2. There was three rules: Each car is owned by exactly one person, that is, no car is without an owner, and no car is owned by more than one person. If a person owns a car, that car is owned by that person, and vice versa. A Person can own at most one car 2PZ" ZP bpublic class Car { /* inv: owner != null, & owner.myCar == this private Person owner; /* pre: p.myCar == null post: p.myCar = this. */ public Car(Person p){ owner = p; owner.setCar(this); } /* pre: p.myCar == null post: p.myCar == this */ public void setOwner(Person p){ owner.setCar(null); owner = p owner.setCar(this);. } }TXZ0Z(Z0ZZc- *2 !#An invariant on Persons and Cars IIThe class Person is simpler.  class Person{ /* inv: if myCar != null then myCar.owner = this. private Car myCar; Person(){}; /* pre: myCar == null, c.owner = this post: inv */ public void setCar(Car c){ myCar = c; } }B  (   %Pre conditions and exception handlingHAn important property of pre-conditions is to establish under what conditions a method will work. void sort(int[] a) Is it acceptable to all with a null reference? An empty array? An array of length larger than 5.000.000 elements? It is the responsibility of the client to ensure that the method s pre-condition is true. The contract avoids that both the client and the object performs a test if the argument is null. &c/h5 /* pre: a not null, a not empty post: a sorted */ void sort(int[] a){ try{ & a extraordinary good & sorting algorith goes here }catch(Exception ex){ if (a == null || a.length = 0) throw new PreConditionVoilation(); } }><3P Java assertions9Java has a mechanism called assertions. assert boolean-condition; This statement will throw an exception if the boolean condition is not true. However, you must tickle java a bit to do so. javac -source 1.4 myfile.java to compile it java -enableassertions myfile to execute and actually test the assertions J:)|-t1;H . Assert statements can be inserted in the beginning of a method to check pre-conditions Assert statements can be inserted just before return, to check post conditions Assert statements can be inserted at the end (just before each return) to check that the class invariant is true. Design by contract is supported in Eiffel. Assertions lack: Systematic support for class invariants Support for  old variables Support for combination of pre and post conditions when using inheritance *VV Interfaces |An interface I declares a set of methods which a class must implement in order to be of type I. Interfaces are an important mechanism for achieving low coupling. Declare your variables (especially fields and parameters) of interface type. This will make your code more robust to changes in the other code You cannot depend on any specific class You cannot depend on any fields Important: The advantage of using interfaces is not for the programmer of  Other code , but in your code. Important: It is the programmer of  Other code which implement interfaces for you to use.61H1H>Abstract classes-An abstract class is a class which has been designed to be used as a superclass. Often an abstract class implements an interface, but leaves out a few details for you to fill in. Your code still use the interface, rather than your class. The abstract class provides useful implementation of interface 2z{- `As before, the programmer of other code has designed the interface, and also the abstract class.aa`#The for loop of Java  As of java 5.o is it possible to write loops of the form: for( T v: i) & do stuff with v Normally, the for loop is used to go through all elements in a collection, but it is far more general. What the for loop really unfolds to is: Iterator<T> it = i.iterator(); while(it.hasNext()){ v = it.next(); & do stuff with v } : Z: Zt             This means that the type of i must have an iterator method. This is ensured by i implementing the Iterable interface. The iterator method returns an iterator which returns elements of type T. To let your own classes work with the for loop, several things need to be in place: You must define an iterator You must create an iterator method that returns an iterator You must impement the Iterable interfrace*+  0                     $!Reading a file using the for loop " Hfor( String s: new IterableReader( aReader ) ) System.out.println( s ); class IterableReader implements Iterable{ private Reader reader; IterableReader(Reader r){ reader = r; } public Iterator iterator(){ return new MyIterator( reader ); } } class MyIterator implements Iterator{ // Inv: br is tail & nextLineToBeReturned is head private BufferedReader br; private String nextLineToBeReturned; private MyIterator(Reader r){ br = new BufferedReader( r ); readALine(); } IPIH               ,                                        private void readALine(){ try{ nextLineToBeReturned = br.readLine(); }catch(IOException uups){ nextLineToBeReturned = null; } } public boolean hasNext(){ return nextLineToBeReturned != null; } public String next(){ String ret = nextLineToBeReturned; readALine(); return ret; } public void remove(){ throw new UnsupportedOperationException(); } }PD               $      @      T    /! !"#%+,   0` ` ̙33` 333MMM` ff3333f` f` f` 3>?" dd@ )))|?" ddx@f h" X H8 n?" dd@   @@``PR     ` p>  >     %0 ~(    6 "  T Click to edit Master title style! !$  0 "@4  RClick to edit Master text styles Second level Third level Fourth level Fifth level!     S  0 "   @*  0 " `  B*Z H5 # "N\ `    "` B ! HDfԔ?"  B "B HDfԔ?"` B # HDfԔ?"``2 $ Hff?"Hx2 % Hff?"5H  0@޽h ? ̙33 SmalITClHeader 0 x@ (     Nff .  > l*  bb  Nxff 3 .  n*  bbd  c $ ?h  4  N0ff 8 g  RClick to edit Master text styles Second level Third level Fourth level Fifth level!     S  Tff r   l*  bb   TBff r3   n*  bbH  0ηo~ ? ̙3380___PPT10.X%l xp0(    Niff .   T*  bb  Ntsff 3 .  V*  bb  T`ff r   T*  bb  Tff r3   V*  bbH  0ηo~ ? ̙3380___PPT10.X%'  0  0(  x  c $>p > x  c $>   > H  0@޽h ? ̙33  0 P$(  r  S h)B  B r  S @*B@4 B H  0@޽h ? ̙33|  0 ,$`\(  \r \ S |"B  B  \ S |P@" 4 B  \ S  R@ 4   H \ 0@޽h ? ̙33   0  z pd (  dr d S B  B  d S @,"     d N?"  d N?"  d N?"  d N?" @  d N?"@`  d N?"`  d N?"  d N?"  d N?" d H0b?"n  :head(2 d H?"`p4 :tail(2r d T?"  d 0/B 0 4  hAn iterator is empty if it will not be able to produce any more elements. The next element which it will produce is called its head, and all the remaining is its tail. Note, given an iterator itr, itr.tail is an iterator which will return the same elements as itr, except for itr.head. ffkffffyf( hXH8H d 0@޽h ? ̙33   0 : 2 x(  xr x S 4MB  B  x S UB@"   B  x S ]B@ 4 B   x N?"   x N?"   x N?"   x N?" 0   x N?" 0P   x N?" Pp   x N?" p   x N?"   x N?"  x H_B?"l ^@ :head(2 x H,dB?" ` :tail(2r x T?"  H x 0@޽h ? ̙33~  0 .&l(  lr l S 4mB  B  l S pvB@" 4 B   l S TB@ 4 B  H l 0@޽h ? ̙33   0 g _ t (  t t T))?"`` @ r t S B  B  t S B@" 4 B  t S B@ 0 B   t N?"@ 0  t N?"@ 0  t N?"@ 0  t N?"@ @0   t N?"@@`0   t N?"@`0   t N?"@0   t N?"@0   t N?"@0  t T0=?"G 0 VtheArray  ~B t HD?"P t TB?"d 9indexl t TB?"|   bif index &  H t 0@޽h ? ̙33o   0   " (  r  S B  B   S TB@" 4 B   S B@ 4 B   8 ` @ @  ` @  T))?"` @ @  N?"   N?"   N?"    N?"  @   N?"@ `   N?"`    N?"    N?"   N?"   TB?" ' 0  VtheArray  B  HD?"0    TN=?"p D  9indext  TB?" \d bif index &  H  0@޽h ? ̙33z # 0 *"(  r  S #     S L*@" 4    S ,@ 4  RH  0@޽h ? ̙33F  ! 0    ~ (  r  S q     S 4t@" i  *8xHPX  S V>      Nԏ ?"C  @:Car (f  N ?"   Howner: Person  flB  6D?" pp   N ?"S    C:Person (f   N ?"   _ myCar: Car   flB   6D?"     0e0e    BCDEF A5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E||((Pd@  S"3 0 K (   0e0e    B`CDE(F A5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E|| `$hP0p @   S" ` H  0@޽h ? ̙33\  + 0    @ (  @x @ c $6    @ c $9@" i  *8xHPX @ c $L     @ N ?"C  @:Car (f @ N ?"   Howner: Person  flB @ 6D?" pp  @ Nȭ ?"S    C:Person (f  @ N ?"   _ myCar: Car   flB  @ 6D?"   @  0e0e    BCDEF 5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E||((Pd@  S"3 0 K .  @  0e0e    B`CDE(F 5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E|| `$hP0p @   S" ` H @ 0@޽h ? ̙33|  0 ,$|(  |r | S     | S Ȳ@" 4   | S @ 4   H | 0@޽h ? ̙33 " 0 0((  r  S >  >   S pu>@" 4 >    S t>@ 4 >  0H  0@޽h ? ̙33 % 0 bZp (  r  S ̥   r  S ̥@" 4    Bi>G\Hb4?"  a Your code ( f   N?"0`0 @ BXΥG\Hb4?" @` b Other code ( f ~B  HD?"p``p   Tӥ?"`4G a interface ( f    Hץf?"   8It is typically the programmer of  Other code who have designed the interface to be used in  Your code . (k  lfjH  0@޽h ?/  ̙33~   0 . & ` (  r  S D   r  S @" 4    S  4    BإG\Hb4?"  c Your code ( f   N?"yy @ BG\Hb4?" b Other code ( f ~B  HD?"   T8?"I  a interface ( f    T ?"p`  fAbstract class(f~B  @ HD?" p   Tp?"IP b your class ( f ~B   HD?"PH  0@޽h ?/  ̙33  0 0( L(  Lr L S X1  1  L S ,5@" 4     L S 8@ 4   qH L 0@޽h ? ̙3380___PPT10./&p U , 0 .&@X(  Xr X S     X S X@" 4    X S X@ 4   xB X BD?"M xB X BD?"c M c H X 0@޽h ? ̙3380___PPT10.:&i& 0 0*(  ^  S  h   B  c $B 8 g  B   H  0ηo~ ? ̙33 0 @P*(  P^ P S  h    P c $L9 8 g     H P 0ηo~ ? ̙33 0 P`f(  `^ ` S  h    ` c $`B 8 g   \HThe pre condition is what must be true before we start the method, the post condition is what must be true after the method has been executed. It is the responsibility of the caller of the method to make sure the pre-condition is met, it is the responsibility of the called object to make sure that the post condition is met. H ` 0ηo~ ? ̙33  0 qi`h(  h^ h S  h   c h c $PM 8 g   uThe Iterator in java.util is one of the many examples of bad design in Java (there are more examples of good design though). It is not considered good design to throw the UnsupportedOperationException. Instead, the designers should have defined two interfaces. One named SimpleIterator, which has only the methods hasNext and next. And an other RemovableIterator, which extends SimpleIterator with the remove method: interface SimpleIterator{ boolean hasNext() E next() } interface RemoveableIterator extends SimpleIterator{ void remove() } This way a (collection) class can decide which kind of Iterator it wants to implement. l7[ 7 [ G# IH h 0ηo~ ? ̙33  0 SKp(  p^ p S  h   E p c $[ 8 g   The point of this, and the next slide is to introduce the notion of a class invariant. The reason we need this concept is that we cannot reason about the individual methods in isolation from the objects the methods works on. The invariant helps to state something about the relationship between the fields of the object, and the purpose of the object, so we can argue in that each method does indeed do the right thing. H p 0ηo~ ? ̙33  0 p.(  ^  S  h     c $hk 8 g   $In the paper by Bertrand Meyer, Meyer uses the programming language Eiffel, which he has designed himself. The Eiffel language has constructs in the language itself to deal with pre and post conditions. In Java there is no such constructs and we can only write them in the comment of the methods. There is often a need to refer in the post condition to the state of the class as it was before the operation. In the next() method, we say that this is the old.tail, which means that the iterator now is the tail of what it was before the next() call. There exists several experimental tools for Java which extends the Java language with support for design by contract. Try  design by contract java on Google if you want to try the real thing.:$H  0ηo~ ? ̙33  0 _W(  ^  S  h   Q  c $z 8 g   gThe rule of class invariants is that it is a postulate must be true after each method call and after the constructor has finished. Therefore it must also be true at the beginning of each method call. The invariant cannot be assumed to be true before the constructor has finished. If we assume the invariant to be true before we call the hasNext() method, we know that either index=theArray.length, in which case the iterator is empty. Thus, we test to see which of the two cases we are in, and if it is not empty, we return true. bR%0 lH  0ηo~ ? ̙332  0 (  ^  S  h     c $ 8 g   xI use a dirty trick in the next method. Normally we use the increment operator  x++ as a statement to add one to a variable x. But really, x++ is an expression, which returns the value of x, and then increments x. If you look at this code fragment: int x=8; System.out.println(x++); System.out.println(++x); It will print 8, 10. After the first print, x will have the value 9, but will print the value it had before it was incremented. In the second print, we first increment x, then print its new value. x++ is called post-increment, and ++x is called pre-increment, see Java Precisely at page 30, section 11.2. So, return theArray[index++] corresponds to the longer Object o = theArray[index]; index++; return 0; It is often much easier to reason about the invariant being true after the constructor is executed if one does not use initializers. $X5 t@* H  0ηo~ ? ̙330  0 (  ^  S       c $0Ů 8 g   vDOn this topic a resign for a better explanation. Please read from page 49 and the rest of Bertrand Meyer s paper, the use of exceptions is very nicely described. H  0ηo~ ? ̙33 0 PH(  ^  S  h   B  c $ 8 g   The invariant states that the owner is not null, and that the myCar field of the owner refers back to this. That reflects the picture. Constructor: A Person cannot own more than one car. We must assume (precondition) that the person given as parameter to the constructor is one who does not own a car. post condition states that the person p owns the car afterwards. owner = p, makes the reference from the car to the person p. owner.setCar( p ) makes the reference back again (See next slide). setOwner: We must again assume that the new owner p does not already own a car (precondition). We start by detaching the old owner of the car from this car, so the old owner does not own the car nay more. We then set the reference from car to person, and the reference from person to car. The class Person is simpler, it has the following form class Person{ /* inv: if myCar != null, myCar.owner = this. private Car myCar; Person(){}; /* pre: myCar == null, c.owner = this post: inv */ public void setCar(Car c){ myCar = c; } }>k 8k 9  H  0ηo~ ? ̙33 0 qi(  ^  S  h   c  c $: 8 g   Assertions are described in Java precisely. Assertions are much better than nothing! So while I am not impressed with the assert mechanism, it is clearly better than not using it. The three points of critique remains however.H  0ηo~ ? ̙33 0  ;(  ^  S  h     c $G 8 g   1 At a very high level of abstraction, one can say that one purpose of the encapsulation is to ensure that the invariant of the class can be ensured. There MUST NOT be public methods which break the invariant, as it is then not possible to know what the program does.  H  0ηo~ ? ̙33 0  *(  ^  S  h     c $TV 8 g     H  0ηo~ ? ̙33! 0 DV(  Dd D c $ h    D s *1 8 g   @The invariant of Person has to take into account two situations, one where the myCar reference is null, and an other where it is not. Notice the precondition of setCar. It assumes that this person does not already own a car, and it assumes that the car c already refers to this person. These two conditions are exactly matched in the call from the method setOwner in class Car. In the C++ programming language there is a special encapsulation mechanism called  friends . Rather than letting setCar be a public method, we could have declared it to be a friend of Car. This way the method could only be called from Car objects. The friend mechanism is very useful for invariant encapsulation which go across several objects as is the case here.PONH D 0ηo~ ? ̙33$ 0 h(  hX h C  h    h S ȫ  8 g   The for loop in the beginning will print out all the lines in aReader. The major part of the slide is the class MyIterator, which will iterate each line in the reader it gets as argument to its constructor. The implementation strategy of MyIterator is very common. The problem is the following: With an iterator, you first ask if there are any more elements (using hasNext()), and if there is, you go get it (using next()). With a Reader, you just try to read, and if there were no elements you get a null or -1 response. So, to turn a Reader into an iterator, we have to try to read before we answer if there are any elements. Hence, we need to keep the read line waiting for a call to next(). >  ,   u   7  6       H h 0ηo~ ? ̙3380___PPT10.C&U r =h t!C{|gmٛ>G_ M0f @p )#0& e'0 0$51h(` CP/ 0|DTimes New Romanhh< 0DTempus Sans ITChh< 0R DGeorgiaans ITChh< 00DBook AntiquaTChh< Times New RomanTempus Sans ITCGeorgia Book Antiqua Arial NarrowSmalITClHeader/OPI Lecture 19 Interfaces & Design by ContractToday's scheduleDesign by contractIterator contract IIterator contract IIAn array iteratorClass invariants%Array Iterator, next and constructorInvariants and encapsulation!An invariant on Persons and Cars$An invariant on Persons and Cars II&Pre conditions and exception handling0DBook AntiquaTCPP3(P̋@DArial NarrowTCPP3(P̋"gf.  @n?" dd@  @@``   & ` NarrowTChh< 0"Gf.  @n?" dd@  @@``   x&& ` 9P!3PGQQGHGG*6333.%Dmk0"*#6$%&   '  #0' /% 2    = >@ D HIJK 0e0e    A A5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E||S" f)))@ʚ; #.ʚ; g4SdSdp 0ppp0 <4!d!d4w 0h<<4dddd4w 0h<g4UdUd8 0p p <4BdBd4w 0h<0___PPT10 ppZ___PPT9<4? tGrundlggende programmering p fleksibel uddannelse, F2001O =Z3OOP F2005 Lecture 7 Interfaces & Design by Contract44!3)Kasper sterbye IT University Copenhagen 4*!#|Today's schedulePDesign by Contract why the term contract what design issue is captured, and why bother what is a pre-condition what is a post-condition what is a class invariant How to do this in Java. you cannot, only in documentation experimental java s exist Assert in Java loop invariants design by contractb<#< #Design by contractbConsider the service offered by the Danish postal service: For 4.50 dkr, they will deliver a letter to the address printed on the front of the envelope, if the letter is posted in Denmark, if it is less than 23x17x0.5 cm. If it is handed in before a given time of the day, there are a next day delivery guarantee. The advantage for me is that I know how much postage to put on a standard letter, I know when to post it, and when I should expect it to arrive. The advantage for the postal service is to receive 4.50, not to have obligations for late delivery, and not to have obligations for odd size letters.ccD  class DanishMailBox { & /*pre: l is within size restrictions & current time is before postingDeadline post: letter l is delivered at address next day */ public void sendStandardLetter(Letter l){& } public Time postingDeadline(){& } & } P TH  Iterator contract I( An iterator is an object which will provide sequential access to a collection. The java.util.Iterator<E> interface has the following methods : boolean hasNext() E next() void remove() hasNext returns true if the iterator is not empty. next returns the head, and moves to tail. remove removes the head from the underlying collection  or throws an UnsupportedOperationException v)S#)H* Iterator contract II4 LAn empty pre-condition means that the method can always be called. Notice, it is the responsibility of the caller to make sure that next() and peek() is not called when the list is empty. Notice, we will assume that the iterator does not change as a result of a call to cloneMe(), since nothing is stated to indicate such behaviourMM,*7 public interface Iterator { /* pre: none * post: return true if the iterator is not empty. */ boolean hasNext(); /* pre: hasNext() * post: return head of old.iterator & this is old.tail. */ Object next(); /* pre: next has been called & remove has not already been called & remove is supported by this iterator * post: removes the last element returned by next*/ void remove(); }B. N An array iterator .This iterator will iterate over the elements in an array which is given as argument to its constructor. The iterator can be used as: String[] names ={ Bill ,  Ben , Jack }; ArrayIterator itr = new ArrayIterator(names); while ( itr.hasNext() ) System.out.println( itr.next() ); But, will this actually print out the right elements? To examine this, we need to compare the implementation of each method to the contract to see if the ArrayIterator satisfies the Iterator contract, and not just defines methods with the right signature,`9   A public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   )$%-  Class invariantsBut, we cannot see if the body does the right thing in isolation from the class itself. What is the the value of index, and what is theArray? A class invariant is a postulate on the fields of a class. The postulate is supposed to be true after each method has finished, and after the constructor has finished. It is the programmers responsibility to make certain that the invariant is maintained. If we assume that the invariant is as in the drawing, then hasNext() is correct.& 2,  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 9P!3PGQQGHGG*6333.%Dmk0"*#6DocumentSummaryInformation8+@ 0@DArial NarrowTChh< 0"Gf.  @n?" dd@  @@``   h#& ` 9P!3PGQQGHGG*6333.%Dmk0"*#6$%&   '  #0' /% 2    = >@ D H 0e0e    A A5% 8c8c     ?1 d0u0@Ty2 NP'p<'pA)BCD|E||S" f)))@ʚ; #.ʚ; g4SdSdp 0ppp0 <4!d!d4w 0h<<4dddd4w 0h<g4UdUd8 0p p <4BdBd4w 0h<0___PPT10 ppZ___PPT9<4? tGrundlggende programmering p fleksibel uddannelse, F2001O =V3OOP F2005 Lecture 7 Interfaces & Design by Contract44!3)Kasper sterbye IT University Copenhagen 4*!#|Today's schedulePDesign by Contract why the term contract what design issue is captured, and why bother what is a pre-condition what is a post-condition what is a class invariant How to do this in Java. you cannot, only in documentation experimental java s exist Assert in Java loop invariants design by contractb<#< #Design by contractbConsider the service offered by the Danish postal service: For 4.50 dkr, they will deliver a letter to the address printed on the front of the envelope, if the letter is posted in Denmark, if it is less than 23x17x0.5 cm. If it is handed in before a given time of the day, there are a next day delivery guarantee. The advantage for me is that I know how much postage to put on a standard letter, I know when to post it, and when I should expect it to arrive. The advantage for the postal service is to receive 4.50, not to have obligations for late delivery, and not to have obligations for odd size letters.ccD  class DanishMailBox { & /*pre: l is within size restrictions & current time is before postingDeadline post: letter l is delivered at address next day */ public void sendStandardLetter(Letter l){& } public Time postingDeadline(){& } & } P TH  Iterator contract I( An iterator is an object which will provide sequential access to a collection. The java.util.Iterator<E> interface has the following methods : boolean hasNext() E next() void remove() hasNext returns true if the iterator is not empty. next returns the head, and moves to tail. remove removes the head from the underlying collection  or throws an UnsupportedOperationException v)S#)H* Iterator contract II4 LAn empty pre-condition means that the method can always be called. Notice, it is the responsibility of the caller to make sure that next() and peek() is not called when the list is empty. Notice, we will assume that the iterator does not change as a result of a call to cloneMe(), since nothing is stated to indicate such behaviourMM,*7 public interface Iterator { /* pre: none * post: return true if the iterator is not empty. */ boolean hasNext(); /* pre: hasNext() * post: return head of old.iterator & this is old.tail. */ Object next(); /* pre: next has been called & remove has not already been called & remove is supported by this iterator * post: removes the last element returned by next*/ void remove(); }B. N An array iterator .This iterator will iterate over the elements in an array which is given as argument to its constructor. The iterator can be used as: String[] names ={ Bill ,  Ben , Jack }; ArrayIterator itr = new ArrayIterator(names); while ( itr.hasNext() ) System.out.println( itr.next() ); But, will this actually print out the right elements? To examine this, we need to compare the implementation of each method to the contract to see if the ArrayIterator satisfies the Iterator contract, and not just defines methods with the right signature,`9   A public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   )$%-  Class invariantsBut, we cannot see if the body does the right thing in isolation from the class itself. What is the the value of index, and what is theArray? A class invariant is a postulate on the fields of a class. The postulate is supposed to be true after each method has finished, and after the constructor has finished. It is the programmers responsibility to make certain that the invariant is maintained. If we assume that the invariant is as in the drawing, then hasNext() is correct.& 2,? /* pre: none * post: return true if the iterator is not empty. */ public boolean hasNext(){ return index < theArray.length; }$]#PP)$Array Iterator, next and constructorBReg. next. We assume the invariant is true, and hasNext() is true, that is the iterator is not empty. Thus, we know that index refers to head, which is what we return. But we also increments index by one, which is what is needed to make sure that the iterator now is its tail. Reg. the constructor The precondition ensures that we will not attempt to iterate null. if objects has elements in it, then index=0 is the head of the iterator if objects it empty, then length is 0, and index is not less than 0, hence the iterator is empty. In both situations the invariant is true.CCb0P6 /* pre: hasNext() * post: return head of iterator; this is old.tail. */ public Object next(){ return theArray[index++]; } /* pre: objects != null * post: invariant */ public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } P76     Invariants and encapsulationPlease observe the wording used when arguing for the pre/post conditions. They all say,  If the invariant is true, then so and so and so and so, therefore the invariant is still true . But what if the invariant is not true? This is why it in general is a good idea to make fields private. If the index field was made public, then we could not be sure the invariant was valid, as someone might had changed it from the outside. Also notice that one should be very careful with  setter methods for variables mentioned in the invariant. A setter for the index would be as bad as making it publicXX= public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   *$%-  An invariant on Persons and Cars7Consider the exercise on Persons and Car from lecture 2. There was three rules: Each car is owned by exactly one person, that is, no car is without an owner, and no car is owned by more than one person. If a person owns a car, that car is owned by that person, and vice versa. A Person can own at most one car 2PZ" ZP bpublic class Car { /* inv: owner != null, & owner.myCar == this private Person owner; /* pre: p.myCar == null post: p.myCar = this. */ public Car(Person p){ owner = p; owner.setCar(this); } /* pre: p.myCar == null post: p.myCar == this */ public void setOwner(Person p){ owner.setCar(null); owner = p owner.setCar(this);. } }TXZ0Z(Z0ZZc- *2 !#An invariant on Persons and Cars IIThe class Person is simpler.  class Person{ /* inv: if myCar != null then myCar.owner = this. private Car myCar; Person(){}; /* pre: myCar == null, c.owner = this post: inv */ public void setCar(Car c){ myCar = c; } }B  (   %Pre conditions and exception handlingHAn important property of pre-conditions is to establish under what conditions a method will work. void sort(int[] a) Is it acceptable to all with a null reference? An empty array? An array of length larger than 5.000.000 elements? It is the responsibility of the client to ensure that the method s pre-condition is true. The contract avoids that both the client and the object performs a test if the argument is null. &c/h5 /* pre: a not null, a not empty post: a sorted */ void sort(int[] a){ try{ & a extraordinary good & sorting algorith goes here }catch(Exception ex){ if (a == null || a.length = 0) throw new PreConditionVoilation(); } }><3P Java assertions9Java has a mechanism called assertions. assert boolean-condition; This statement will throw an exception if the boolean condition is not true. However, you must tickle java a bit to do so. javac -source 1.4 myfile.java to compile it java -enableassertions myfile to execute and actually test the assertions J:)|-t1;H . Assert statements can be inserted in the beginning of a method to check pre-conditions Assert statements can be inserted just before return, to check post conditions Assert statements can be inserted at the end (just before each return) to check that the class invariant is true. Design by contract is supported in Eiffel. Assertions lack: Systematic support for class invariants Support for  old variables Support for combination of pre and post conditions when using inheritance *VV Interfaces |An interface I declares a set of methods which a class must implement in order to be of type I. Interfaces are an important mechanism for achieving low coupling. Declare your variables (especially fields and parameters) of interface type. This will make your code more robust to changes in the other code You cannot depend on any specific class You cannot depend on any fields Important: The advantage of using interfaces is not for the programmer of  Other code , but in your code. Important: It is the programmer of  Other code which implement interfaces for you to use.61H1H>Abstract classes-An abstract class is a class which has been designed to be used as a superclass. Often an abstract class implements an interface, but leaves out a few details for you to fill in. Your code still use the interface, rather than your class. The abstract class provides useful implementation of interface 2z{- `As before, the programmer of other code has designed the interface, and also the abstract class.aa`#The for loop of Java  As of java 5.o is it possible to write loops of the form: for( T v: i) & do stuff with v Normally, the for loop is used to go through all elements in a collection, but it is far more general. What the for loop really unfolds to is: Iterator<T> it = i.iterator(); while(it.hasNext()){ v = it.next(); & do stuff with v } : Z: Zt             This means that the type of i must have an iterator method. This is ensured by i implementing the Iterable interface. The iterator method returns an iterator which returns elements of type T. To let your own classes work with the for loop, several things need to be in place: You must define an iterator You must create an iterator method that returns an iterator You must impement the Iterable interfrace*+  0                     $!Reading a file using the for loop " Hfor( String s: new IterableReader( aReader ) ) System.out.println( s ); class IterableReader implements Iterable{ private Reader reader; IterableReader(Reader r){ reader = r; } public Iterator iterator(){ return new MyIterator( reader ); } } class MyIterator implements Iterator{ // Inv: br is tail & nextLineToBeReturned is head private BufferedReader br; private String nextLineToBeReturned; private MyIterator(Reader r){ br = new BufferedReader( r ); readALine(); } IPI.               ,                                      private void readALine(){ try{ nextLineToBeReturned = br.readLine(); }catch(IOException uups){ nextLineToBeReturned = null; } } public boolean hasNext(){ return nextLineToBeReturned != null; } public String next(){ String ret = nextLineToBeReturned; readALine(); return ret; } public void remove(){ throw new UnsupportedOperationException(); } }PD               $      @      T    /! !"#%+,n $ 0   h~ (  hX h C  h     h S ȫ  8 g   : The for loop in the beginning will print out all the lines in aReader. The major part of the slide is the class MyIterator, which will iterate each line in the reader it gets as argument to its constructor. The implementation strategy of MyIterator is very common. The problem is the following: With an iterator, you first ask if there are any more elements (using hasNext()), and if there is, you go get it (using next()). With a Reader, you just try to read, and if there were no elements you get a null or -1 response. So, to turn a Reader into an iterator, we have to try to read before we answer if there are any elements. Hence, we need to keep the read line waiting for a call to next(). The private method readAline() is doing the bridging from Reader to Iterator style. It try to read a line, and if successful, stores the line so that it later can be returned by next(). If there is no line to be read, the buffered reader will return null, which in hasNext() is used as the test to see if there is a line to be returned. Notice in particular the next() method. The line to be returned has already been read (using readALine()). Next need to return  nextLineToBeReturned , and to move to the next line. An auxiliary variable ret is used to hold the return value while we move to the next line. *>  ,   u   7  6       (         } H h 0ηo~ ? ̙3380___PPT10.C&U r6$j6'1rl(` CP/ 0|DTimes New Romanhh< 0DTempus Sans ITChh< 0R DGeorgiaans ITChh< 00DBook AntiquaTChh< 0@DArial$%&   '  #0' /% 2    = >*_ (Carsten Schuermannp8 T`   ':OOP Spring 2004 Lecture 1 Objects, Classes and ReferencesKasper sterbyebC:\Documents and Settings\Kasper sterbye\Application Data\Microsoft\Templates\SmalITClHeader.pot Carsten Schuermannt261Microsoft PowerPointing@&l@2S]@[b GRPICTt  X6  p--$oo--'@Georgia-.  2 m1b."Systemp7-f--% --'f--%  --'f--% o--'f--$          --f--%          --'--$ --f--% --'@Book Antiqua-. )))2 (> OOP F2005.-@Book Antiqua-. )))2 0A Lecture 7.-@Book Antiqua-. )))62 8Interfaces & Design by Contract.-@Book Antiqua-. f2 DAKasper .-@Book Antiqua-. f 2 DOb.-@Book Antiqua-. f2 DQsterbye.-@Book Antiqua-. f+2 H>IT University Copenhagen.- ՜.+,0    ' A4 Paperl IT University Copenhagen s. ? /* pre: none * post: return true if the iterator is not empty. */ public boolean hasNext(){ return index < theArray.length; }$]#PP)$Array Iterator, next and constructorBReg. next. We assume the invariant is true, and hasNext() is true, that is the iterator is not empty. Thus, we know that index refers to head, which is what we return. But we also increments index by one, which is what is needed to make sure that the iterator now is its tail. Reg. the constructor The precondition ensures that we will not attempt to iterate null. if objects has elements in it, then index=0 is the head of the iterator if objects it empty, then length is 0, and index is not less than 0, hence the iterator is empty. In both situations the invariant@ D HIK 0e0e    A A5% 8c8c     ?1 is true.CCb0P6 /* pre: hasNext() * post: return head of iterator; this is old.tail. */ public Object next(){ return theArray[index++]; } /* pre: objects != null * post: invariant */ public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } P76     Invariants and encapsulationPlease observe the wording used when arguing for the pre/post conditions. They all say,  If the invariant is true, then so and so and so and so, therefore the invariant is still true . But what if the invariant is not true? This is why it in general is a good idea to make fields private. If the index field was made public, then we could not be sure the invariant was valid, as someone might had changed it from the outside. Also notice that one should be very careful with  setter methods for variables mentioned in the invariant. A setter for the index would be as bad as making it publicXX= public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   *$%-  An invariant on Persons and Cars7Consider the exercise on Persons and Car from lecture 2. There was three rules: Each car is owned by exactly one person, that is, no car is without an owner, and no car is owned by more than one person. If a person owns a car, that car is owned by that person, and vice versa. A Person can own at most one car 2PZ" ZP bpublic class Car { /* inv: owner != null, & owner.myCar == this private Person owner; /* pre: p.myCar == null post: p.myCar = this. */ public Car(Person p){ owner = p; owner.setCar(this); } /* pre: p.myCar == null post: p.myCar == this */ public void setOwner(Person p){ owner.setCar(null); owner = p owner.setCar(this);. } }TXZ0Z(Z0ZZc- *2 !#An invariant on Persons and Cars IIThe class Person is simpler.  class Person{ /* inv: if myCar != null then myCar.owner = this. private Car myCar; Person(){}; /* pre: myCar == null, c.owner = this post: inv */ public void setCar(Car c){ myCar = c; } }B  (   %Pre conditions and exception handlingHAn important property of pre-conditions is to establish under what conditions a method will work. void sort(int[] a) Is it acceptable to all with a null reference? An empty array? An array of length larger than 5.000.000 elements? It is the responsibility of the client to ensure that the method s pre-condition is true. The contract avoids that both the client and the object performs a test if the argument is null. &c/h5 /* pre: a not null, a not empty post: a sorted */ void sort(int[] a){ try{ & a extraordinary good & sorting algorith goes here }catch(Exception ex){ if (a == null || a.length = 0) throw new PreConditionVoilation(); } }><3P Java assertions9Java has a mechanism called assertions. assert boolean-condition; This statement will throw an exception if the boolean condition is not true. However, you must tickle java a bit to do so. javac -source 1.4 myfile.java to compile it java -enableassertions myfile to execute and actually test the assertions J:)|-t1;H . Assert statements can be inserted in the beginning of a method to check pre-conditions Assert statements can be inserted just before return, to check post conditions Assert statements can be inserted at the end (just before each return) to check that the class invariant is true. Design by contract is supported in Eiffel. Assertions lack: Systematic support for class invariants Support for  old variables Support for combination of pre and post conditions when using inheritance *VV Interfaces |An interface I declares a set of methods which a class must implement in order to be of type I. Interfaces are an important mechanism for achieving low coupling. Declare your variables (especially fields and parameters) of interface type. This will make your code more robust to changes in the other code You cannot depend on any specific class You cannot depend on any fields Important: The advantage of using interfaces is not for the programmer of  Other code , but in your code. Important: It is the programmer of  Other code which implement interfaces for you to use.61H1H>Abstract classes-An abstract class is a class which has been designed to be used as a superclass. Often an abstract class implements an interface, but leaves out a few details for you to fill in. Your code still use the interface, rather than your class. The abstract class provides useful implementation of interface 2z{- `As before, the programmer of other code has designed the interface, and also the abstract class.aa`#The for loop of Java  As of java 5.o is it possible to write loops of the form: for( T v: i) & do stuff with v Normally, the for loop is used to go through all elements in a collection, but it is far more general. What the for loop really unfolds to is: Iterator<T> it = i.iterator(); while(it.hasNext()){ v = it.next(); & do stuff with v } : Z: Zt             This means that the type of i must have an iterator method. This is ensured by i implementing the Iterable interface. The iterator method returns an iterator which returns elements of type T. To let your own classes work with the for loop, several things need to be in place: You must define an iterator You must create an iterator method that returns an iterator You must impement the Iterable interfrace*+  0                     $!Reading a file using the for loop " Hfor( String s: new IterableReader( aReader ) ) System.out.println( s ); class IterableReader implements Iterable{ private Reader reader; IterableReader(Reader r){ reader = r; } public Iterator iterator(){ return new MyIterator( reader ); } } class MyIterator implements Iterator{ // Inv: br is tail & nextLineToBeReturned is head private BufferedReader br; private String nextLineToBeReturned; private MyIterator(Reader r){ br = new BufferedReader( r ); readALine(); } IPI.               ,                                      private void readALine(){ try{ nextLineToBeReturned = br.readLine(); }catch(IOException uups){ nextLineToBeReturned = null; } } public boolean hasNext(){ return nextLineToBeReturned != null; } public String next(){ String ret = nextLineToBeReturned; readALine(); return ret; } public void remove(){ throw new UnsupportedOperationException(); } }PD               $      @      T    %The moral of the story  gInterfaces and Abstract classes are necessary for the division of labor between A) the programmers of frameworks B) the programmers who use the frameworks The B) programmers need to understand this to use frameworks efficiently Interfaces are the part of contracts that the compiler understands. Contracts are the part you as programmer has to understand. BQKQK h  Application programmers will rarely need to define interfaces and abstract classes, nor to define contracts. Application programmers will often need to implement interfaces or subclass abstract classes to integrate their code into the framework. Application programmers need to understand what pre and post conditions are for the methods called. Most programmers are application programmers.&~    /! !"#%+,-. - 0 0( L(  Lr L S X1  1  L S ,5@" 4     L S 8@ 4   qH L 0@޽h ? ̙3380___PPT10./&p U . 0 p(  pr p S \c   r p S (@" 4  r p S @ 4  H p 0@޽h ? ̙3380___PPT10.K&e# 0 l(  lX l C  h    l S X1 8 g     H l 0ηo~ ? ̙3380___PPT10.K& f% 0 t(  tX t C  h    t S 0 8 g     H t 0ηo~ ? ̙3380___PPT10.K&er c0Ka %?w"1/m(` CR/ 0|DTimes New RomanPP3(P̋DTempus Sans ITCPP3(P̋R DGeorgiaans ITCPP3(P̋Root EntrydO)+dbCurrent User2SummaryInformation(X8PowerPoint Document(.     &'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWYZ[\]^_`ab$%,-./0123456789:;Java assertions InterfacesAbstract classesThe for loop of Java"Reading a file using the for loopThe moral of the story  Fonts UsedDesign Template Slide Titles Titles*_"c`Carsten Schuermannterbyef--% --'f--%  -- d0u0@Ty2 NP'p<'pA)BCD|E||S" f)))@ʚ; #.ʚ; g4hdhdpHpz-ppp0 <4!d!d`gʚ;<4dddd`gʚ;g4UdUdpHpz(p p <4BdBd`gʚ;0___PPT10 ppX___PPT9:2h___PPT2001D<4Xp? tGrundlggende programmering p fleksibel uddannelse, F2001O =Z.OPI Lecture 19 Interfaces & Design by Contract//!.)Kasper sterbye IT University Copenhagen 4*!#|Today's schedulePDesign by Contract why the term contract what design issue is captured, and why bother what is a pre-condition what is a post-condition what is a class invariant How to do this in Java. you cannot, only in documentation experimental java s exist Assert in Java loop invariants design by contractb<#< #Design by contractbConsider the service offered by the Danish postal service: For 4.50 dkr, they will deliver a letter to the address printed on the front of the envelope, if the letter is posted in Denmark, if it is less than 23x17x0.5 cm. If it is handed in before a given time of the day, there are a next day delivery guarantee. The advantage for me is that I know how much postage to put on a standard letter, I know when to post it, and when I should expect it to arrive. The advantage for the postal service is to receive 4.50, not to have obligations for late delivery, and not to have obligations for odd size letters.ccD  class DanishMailBox { & /*pre: l is within size restrictions & current time is before postingDeadline post: letter l is delivered at address next day */ public void sendStandardLetter(Letter l){& } public Time postingDeadline(){& } & } P TH  Iterator contract I( An iterator is an object which will provide sequential access to a collection. The java.util.Iterator<E> interface has the following methods : boolean hasNext() E next() void remove() hasNext returns true if the iterator is not empty. next returns the head, and moves to tail. remove removes the head from the underlying collection  or throws an UnsupportedOperationException v)S#)H* Iterator contract II6 LAn empty pre-condition means that the method can always be called. Notice, it is the responsibility of the caller to make sure that next() and peek() is not called when the list is empty. Notice, we will assume that the iterator does not change as a result of a call to cloneMe(), since nothing is stated to indicate such behaviourMM,*7 public interface Iterator { /* pre: none * post: return true if the iterator is not empty. */ boolean hasNext(); /* pre: hasNext() * post: return head of old.iterator & this is old.tail. */ Object next(); /* pre: next has been called & remove has not already been called & remove is supported by this iterator * post: removes the last element returned by next*/ void remove(); }B. N An array iterator .This iterator will iterate over the elements in an array which is given as argument to its constructor. The iterator can be used as: String[] names ={ Bill ,  Ben , Jack }; ArrayIterator itr = new ArrayIterator(names); while ( itr.hasNext() ) System.out.println( itr.next() ); But, will this actually print out the right elements? To examine this, we need to compare the implementation of each method to the contract to see if the ArrayIterator satisfies the Iterator contract, and not just defines methods with the right signature,`9   A public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   )$%-  Class invariantsBut, we cannot see if the body does the right thing in isolation from the class itself. What is the the value of index, and what is theArray? A class invariant is a postulate on the fields of a class. The postulate is supposed to be true after each method has finished, and after the constructor has finished. It is the programmers responsibility to make certain that the invariant is maintained. If we assume that the invariant is as in the drawing, then hasNext() is correct.& 2,? /* pre: none * post: return true if the iterator is not empty. */ public boolean hasNext(){ return index < theArray.length; }$]#PP)$Array Iterator, next and constructorBReg. next. We assume the invariant is true, and hasNext() is true, that is the iterator is not empty. Thus, we know that index refers to head, which is what we return. But we also increments index by one, which is what is needed to make sure that the iterator now is its tail. Reg. the constructor The precondition ensures that we will not attempt to iterate null. if objects has elements in it, then index=0 is the head of the iterator if objects it empty, then length is 0, and index is not less than 0, hence the iterator is empty. In both situations the invariant is true.CCb0P6 /* pre: hasNext() * post: return head of iterator; this is old.tail. */ public Object next(){ return theArray[index++]; } /* pre: objects != null * post: invariant */ public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } P76     Invariants and encapsulationPlease observe the wording used when arguing for the pre/post conditions. They all say,  If the invariant is true, then so and so and so and so, therefore the invariant is still true . But what if the invariant is not true? This is why it in general is a good idea to make fields private. If the index field was made public, then we could not be sure the invariant was valid, as someone might had changed it from the outside. Also notice that one should be very careful with  setter methods for variables mentioned in the invariant. A setter for the index would be as bad as making it publicXX= public class ArrayIterator implements Iterator{ private final Object[] theArray; private int index; // index of next element public ArrayIterator(Object[] objects){ theArray = objects; index = 0; } public boolean hasNext(){ return index < theArray.length; } public Object next(){ return theArray[index++]; } public void remove(){ throw new UnsupportedOperationException(); } }   *$%-  An invariant on Persons and Cars7Consider the exercise on Persons and Car from lecture 2. There was three rules: Each car is owned by exactly one person, that is, no car is without an owner, and no car is owned by more than one person. If a person owns a car, that car is owned by that person, and vice versa. A Person can own at most one car 2PZ" ZP bpublic class Car { /* inv: owner != null, & owner.myCar == this private Person owner; /* pre: p.myCar == null post: p.myCar = this. */ public Car(Person p){ owner = p; owner.setCar(this); } /* pre: p.myCar == null post: p.myCar == this */ public void setOwner(Person p){ owner.setCar(null); owner = p owner.setCar(this);. } }TXZ0Z(Z0ZZc- *2 !#An invariant on Persons and Cars IIThe class Person is simpler. class Person{ /* inv: if myCar != null then myCar.owner = this. private Car myCar; Person(){}; /* pre: myCar == null, c.owner = this post: inv */ public void setCar(Car c){ myCar = c; } }B  (   %Pre conditions and exception handlingHAn important property of pre-conditions is to establish under what conditions a method will work. void sort(int[] a) Is it acceptable to all with a null reference? An empty array? An array of length larger than 5.000.000 elements? It is the responsibility of the client to ensure that the method s pre-condition is true. The contract avoids that both the client and the object performs a test if the argument is null. &c/h5 /* pre: a not null, a not empty post: a sorted */ void sort(int[] a){ try{ & a extraordinary good & sorting algorith goes here }catch(Exception ex){ if (a == null || a.length = 0) throw new PreConditionVoilation(); } }><3P Java assertions9Java has a mechanism called assertions. assert boolean-condition; This statement will throw an exception if the boolean condition is not true. However, you must tickle java a bit to do so. javac -source 1.4 myfile.java to compile it java -enableassertions myfile to execute and actually test the assertions J:)|-t1;H . Assert statements can be inserted in the beginning of a method to check pre-conditions Assert statements can be inserted just before return, to check post conditions Assert statements can be inserted at the end (just before each return) to check that the class invariant is true. Design by contract is supported in Eiffel. Assertions lack: Systematic support for class invariants Support for  old variables Support for combination of pre and post conditions when using inheritance *VV Interfaces |An interface I declares a set of methods which a class must implement in order to be of type I. Interfaces are an important mechanism for achieving low coupling. Declare your variables (especially fields and parameters) of interface type. This will make your code more robust to changes in the other code You cannot depend on any specific class You cannot depend on any fields Important: The advantage of using interfaces is not for the programmer of  Other code , but in your code. Important: It is the programmer of  Other code which implement interfaces for you to use.61H1H>Abstract classes-An abstract class is a class which has been designed to be used as a superclass. Often an abstract class implements an interface, but leaves out a few details for you to fill in. Your code still use the interface, rather than your class. The abstract class provides useful implementation of interface 2z{- `As before, the programmer of other code has designed the interface, and also the abstract class.aa`#The for loop of Java As of java 5.o is it possible to write loops of the form: for( T v: i) & do stuff with v Normally, the for loop is used to go through all elements in a collection, but it is far more general. What the for loop really unfolds to is: Iterator<T> it = i.iterator(); while(it.hasNext()){ v = it.next(); & do stuff with v } : Z: Z~             This means that the type of i must have an iterator method. This is ensured by i implementing the Iterable interface. The iterator method returns an iterator which returns elements of type T. To let your own classes work with the for loop, several things need to be in place: You must define an iterator You must create an iterator method that returns an iterator You must impement the Iterable interfrace*&+  0                     $!Reading a file using the for loop" Hfor( String s: new IterableReader( aReader ) ) System.out.println( s ); class IterableReader implements Iterable{ private Reader reader; IterableReader(Reader r){ reader = r; } public Iterator iterator(){ return new MyIterator( reader ); } } class MyIterator implements Iterator{ // Inv: br is tail & nextLineToBeReturned is head private BufferedReader br; private String nextLineToBeReturned; private MyIterator(Reader r){ br = new BufferedReader( r ); readALine(); } IPIZ               ,                                      private void readALine(){ try{ nextLineToBeReturned = br.readLine(); }catch(IOException uups){ nextLineToBeReturned = null; } } public boolean hasNext(){ return nextLineToBeReturned != null; } public String next(){ String ret = nextLineToBeReturned; readALine(); return ret; } public void remove(){ throw new UnsupportedOperationException(); } }P^               $      @      T    %The moral of the story  gInterfaces and Abstract classes are necessary for the division of labor between A) the programmers of frameworks B) the programmers who use the frameworks The B) programmers need to understand this to use frameworks efficiently Interfaces are the part of contracts that the compiler understands. Contracts are the part you as programmer has to understand. BQKQK h  Application programmers will rarely need to define interfaces and abstract classes, nor to define contracts. Application programmers will often need to implement interfaces or subclass abstract classes to integrate their code into the framework. Application programmers need to understand what pre and post conditions are for the methods called. Most programmers are application programmers.  /! !"#%+,-.  00(  x  c $0jp p x  c $j   p H  0@޽h ? ̙33r"" Oh+'0 hp8 T`   ':OOP Spring 2004 Lecture 1 Objects, Classes and ReferencesKasper sterbyebC:\Documents and Settings\Kasper sterbye\Application Data\Microsoft\Templates\SmalITClHeader.pot Carsten Schuermannt261Microsoft PowerPointing@&l@2S]@[b GRPICTJ} HH} }}HH  )ca$}}fffffffffff!f|r$ff ff~|11ffv{f~ffffffffffffffffffffffff)))f))))8 )))))f ))))) )))));))))))f))))))))))));))))f))))))))2)))f))))))ffff6)))))f))))))))))?)))))f))))))))))f))))))))f))))))))))))))))o)))))))))))))f))))))))))))))))))))))))))f) ))))))))))f) ))))))))))) ))))))))))ffffi))))))))))f))))))))))))))))))))))))))))))))f)))))))))))))))))))))))))))))))))))))))))))))f))))))))))))))))))))))))))))))))))))))))))J)))))))))))))))))))))) ))))))))))))) ))))))))))f)))))))))))))))))))))) ))))))))))))) )))))))))))))))))))))))))))))))) ))))))))))))) )))))))))),)))))))))))))))))))))))))) ))))))))))f)))))))))))))))))))))))))) )))))))))))))))))))))))))))))))))))) ))))))))))/)))f))))))))))f))))))ffffffff3fffffWfffffffff]ffffffffffffffHfffffffcffffffffff2fffffffffffffffffffffffffffffffffffffffffffffffi