Presentation is loading. Please wait.

Presentation is loading. Please wait.

From Building Blocks to Projects

Similar presentations


Presentation on theme: "From Building Blocks to Projects"— Presentation transcript:

1 From Building Blocks to Projects
Major topics Design and implementation of classes Using javadoc Contracts and invariants The canonical form of classes Unit testing and use of JUnit Project build and use of Ant As your java programs become more extensive and later when you go work in industry, you will better appreciate the approaches presented in this chapter

2 Getter and Setter Methods
DO NOT make fields public; use getter/setter methods What does final mean in a parameter list?

3 Polar Representation for a Point
A point can be uniquely determined by an angle and a distance from the origin What are the relationships between these values? How can this be stated as an invariant?

4 The Class PolarPoint

5 Separate Implementations from Interface
As you know from data structures, two common implementations for a list are using an array or using a linked structure Name some accessors for a list Name some modifiers for a list

6 A List Interface – Brief Form
How could classes for a linked list and an array be defined to provide implementations?

7 Inner Classes How would a node class in a linked list be defined if you use C++? Java provides an alternative implementation using inner classes

8 Basic Javadoc Documentation
Some most common tags As a minimum every class should have author & version and every method should have parameters and return, as appropriate

9 Contracts and Invariants
Some other javadoc tags (not implemented by Sun) @pre -- the preconditions go here – @post the postconditions go here – Logical implications: ==> and <=> @nochange, just what it says Some more complex notation @forall x : Expression //universal quantifier @exists x : Expression //existential quantifier [m .. n] a range of integers The following detailed interface illustrates this documentation for contracts

10 The List Interface - 1 package mylist; public interface List { /**
* Returns the number of elements in the list. * true @nochange */ public int size(); * Returns true if and only if the list is empty. * <=> size() > 0 public boolean isEmpty(); * Returns the i-th element in the list. i >= 0 && i < size() public Object element(int i); The List Interface - 1

11 The List Interface - 2 /** * Returns the first element in the list. *
!isEmpty() * == element(0) @nochange */ public Object head(); * Returns the last element in the list. * == element(size() - 1) public Object last(); * Inserts a new element into the list at the i-th position. item != null && i >= 0 && i <= size() size() == + 1 * k : [0 .. size() - * (k < i ==> == element(k)) && * (k == i ==> == element(k)) && * (k > i ==> element(k - == element(k) public void insert(Object item, int i); The List Interface - 2

12 The List Interface - 3 /**
* Inserts a new element at the head of the list. item != null size() == + 1 == element(0) * k : [1 .. size() - element(k - == element(k) */ public void insertHead(Object item); * Inserts a new element at the end of the list. == element(size() - 1) * k : [0 .. size() - == element(k) public void insertLast(Object item); * Remove the element at the i-th position. size() > 0 i >= 0 && i < size() * = size() == - 1 * k : [0 .. size() - * (k < i ==> == element(k)) && * (k >= i ==> element(k + == element(k)) public Object remove(int i); The List Interface - 3

13 The List Interface - 4 /** * Remove the element at the head. *
size() > 0 * = * k : [1 .. size() - element(k + == element(k) */ public Object removeHead(); * Remove the element at the end. * = element(size() - * k : [0 .. size() - == element(k) public Object removeLast(); }

14 Invariants What is an invariant? An example for a doubly linked list
Objects are manipulated and change state, but some properties are always true whatever the state A well-formed state is when all invariants are true An example for a doubly linked list

15 Implementation /** * The invaraiant of the linked list implementation.
*/ protected boolean _wellformed() { int n = 0; for (Node p = head; p != null; p = p.next) { n++; if (p.prev != null) { if (p.prev.next != p) return false; } else { if (head != p) return false; } if (p.next != null) { if (p.next.prev != p) return false; if (tail != p) return false; return n == count;

16 Preserving Invariants
Document the invariant with tag that names the invariant method

17 Assertions Syntax: assert Assertion;
Assertions are commonly applied to preconditions, postconditions, and invariants public Object head() { assert !isEmpty(); // precondition Object result = (head != null ? head.item : null); assert result == element(0); // postcondition return result; }

18 Detailed Example - 1 public void insert(Object item, int i) {
assert item != null && i >= 0 && i <= size(); // assert the pre-condition assert _wellformed(); // assert the invaraint // the object in pre-state, used in the post-conditions int size_pre = size(); LinkedList this_pre = null; try { this_pre = (LinkedList) clone(); } catch (CloneNotSupportedException e) {} // begin insertion if (i <= 0) { insertHead(item); } else if (i >= count) { insertLast(item); } else { // i > 0 && i < count; Node n = head; for (int j = 0; n != null && j < i - 1; j++) { n = n.next; } Node node = new Node(); node.item = item; node.next = n.next; node.prev = n; node.next.prev = node; n.next = node; count++; } // end insertion Detailed Example - 1

19 Detailed Example – 2 // assert the post-condition
int size_post = size(); assert size_post == size_pre + 1; // the quantified experssion is translated into a for-loop boolean insertOK = true; for (int k = 0; insertOK && k < size(); k++) { if (k < i) { insertOK = (this_pre.element(k) == element(k)); } else if (k == i) { insertOK = (item == element(k)); } else { insertOK = (this_pre.element(k - 1) == element(k)); } assert insertOK; // assert the invariant assert _wellformed();

20 Design By Contract Contracts are specified by preconditions and postconditions Each method should have a contract

21 Design of a Canonical Class
Every class in Java is an Object; this means you may override some higher level methods

22 No Argument Constructor
Normal creation of classes The class and its constructors are known The new is used to create an instance Dynamic creation of classes at runtime In some applications, particularly when processing is distributed between machines, the class itself may not be known until runtime The JVM can still create instances of the class provided a no argument constructor is provided This ability to load classes and create instances at runtime is a very powerful feature in Java

23 Object Equality Conditions to be satisfied by an equals( ) method
public boolean equals(Object other) { if (this == other) return true; if (other instanceof C) { C otherObj = (C) other; -- compare each field and return false if not equal – return true; } else return false; }

24 Group Work Given a linked list implementation of a list structures, how would you override the equals method?

25 Equals for the Linked List
public boolean equals(Object other) { if (other != null && other instanceof LinkedList) { LinkedList otherlist = (LinkedList) other; if (this.size() == otherlist.size()) { Node thisnode = this.head; Node othernode = otherlist.head; while (thisnode != null && othernode != null) { if (!thisnode.item.equals(othernode.item)) return false; thisnode = thisnode.next; othernode = othernode.next; } return true; Equals for the Linked List

26 Overriding hashcode If equals is overriden, hashcode should also be overriden A hashcode for two equal objects must return the same value; here is the hashcode for LinkedList

27 Calculating a Hashcode
Common ways to combine hash values

28 Cloning Objects – 1

29 Cloning Objects - 2 Which structure would result from the previous cloning method?

30 Using Clones With Assertions
Create a copy of the original object before insert LinkedList this_pre = null; try { this_pre = (LinkedList) clone(); } catch (CloneNotSupportedException e) {} At the end, check that the insertion was correct boolean insertOK = true; for (int k = 0; insertOK && k < size(); k++) { if (k < i) { insertOK = (this_pre.element(k) == element(k)); } else if (k == i) { insertOK = (item == element(k)); } else { insertOK = (this_pre.element(k - 1) == element(k)); } assert insertOK;

31 Implementing toString
The toString method is defined for every object For complex objects, the default is to print the class name The programmer can override the toString method to make a more detailed printout of information How would you override toString for a linked list?

32 toString for LinkedList
public String toString() { StringBuffer s = new StringBuffer(); int i = 0; for (Node n = head; n != null; n = n.next, i++) { s.append("[" + i + "] = " + n.item + "\n"); } return s.toString();

33 Implementing Serialization
What is serialization? Transform an object to and from a byte stream Important if the object is to be sent over a network to a remote site or to be stored in a file If an object is to be serialized, the class should implement the java.io.Seralizable interface to custom define the methods writeObject( ) and readObject( ) Java provides a default implementation for objects This implementation is adequate for our LinkedList example

34 Class Organization What do each of these category names mean?

35 Levels of Testing In this chapter we concentrate on unit testing
We show a simple test first Then we show a more complex test We introduce JUnit, a unit testing tool We introduce Ant, a build tool for java that, in addition to compilation, can run all JUnit tests

36 Testing Your Programs Testing can be hierarchical from the unit level up to the program level as components are integrated As a minimum, unit testing should include Using these criteria, how would you design a testing strategy for the linked list class

37 A Simple Test - 1 package test; import mylist.*;
public class LinkedListTest1 { public static void main(String args[]) throws CloneNotSupportedException { LinkedList l = new LinkedList(); l.insertHead(new Integer(1)); l.insertHead(new Integer(2)); l.insertLast(new Integer(3)); l.insertLast(new Integer(4)); l.insert(new Integer(5), 3); l.insert(new Integer(6), 3); l.insert(new Integer(7), 3); System.out.println("First pass"); System.out.println(l); l.removeHead(); l.removeLast(); l.remove(2);

38 A Simple Test - 2 System.out.println("Second pass");
System.out.println(l); LinkedList l2 = (LinkedList) l.clone(); System.out.println("Cloned list"); System.out.println(l2); l2.removeHead(); System.out.println("Original list"); }

39 Designing a Better Test
What is wrong with the previous test? How would you improve it?

40 A Better Test - 1 package test; import mylist.*;
public class LinkedListTest2 { protected static int[][] results = { { 2, 1, 3, 7, 6, 5, 4 }, // result after insertion { 1, 3, 6, 5 }, // result after removal { 1, 3, 6, 5 }, // the cloned list { 1, 3, 6, 5 }, // the original list after removing head from cloned list { 3, 6, 5 }, // the cloned list after removing head from the cloned list }; public static void main(String args[]) throws CloneNotSupportedException { boolean testPassed = true; LinkedList l = new LinkedList(); l.insertHead(new Integer(1)); l.insertHead(new Integer(2)); l.insertLast(new Integer(3)); l.insertLast(new Integer(4)); l.insert(new Integer(5), 3); l.insert(new Integer(6), 3); l.insert(new Integer(7), 3); System.out.println("First pass"); System.out.println(l); if (!TestUtil.match(l, TestUtil.toIntegerArray(results[0]))) { System.out.println("Result mismatch"); testPassed = false;}

41 A Better Test - 2 l.removeHead(); l.removeLast(); l.remove(2);
System.out.println("Second pass"); System.out.println(l); if (!TestUtil.match(l, TestUtil.toIntegerArray(results[1]))) { System.out.println("Result mismatch"); testPassed = false; } LinkedList l2 = (LinkedList) l.clone(); System.out.println("Cloned list"); System.out.println(l2); if (!TestUtil.match(l2, TestUtil.toIntegerArray(results[2]))) { l2.removeHead(); System.out.println("Original list"); if (!TestUtil.match(l, TestUtil.toIntegerArray(results[3]))) {

42 A Better Test - 3 System.out.println("Cloned list");
System.out.println(l2); if (!TestUtil.match(l2, TestUtil.toIntegerArray(results[4]))) { System.out.println("Result mismatch"); testPassed = false; } if (testPassed) { System.out.println("Test passed."); } else { System.out.println("Test failed.");

43 Test Utilities - 1 package test; import mylist.*;
public class TestUtil { /** * An auxiliary method that tests whether the contents of a list match the * contents of an array of objects. * It returns true if the list and the array are of the same length and each * object in the list equals to the object in the array at the same position. */ public static boolean match(List list, Object[] array) { boolean result = false; if (list != null && array != null) { int n = list.size(); if (n == array.length) { for (int i = 0; i < n; i++) { Object item = list.element(i); if (item != null) { if (!item.equals(array[i])) { return false; } } else { if (array[i] != null) { return false; } } result = true; } else if (list == null && array == null) { return result;

44 Test Utilities – 2 /** * An auxiliary method that converts an array of integer values to an array of integer objects */ public static Object[] toIntegerArray(int[] intArray) { if (intArray != null) { int n = intArray.length; Object[] resultArray = new Object[n]; for (int i = 0; i < n; i++) { resultArray[i] = new Integer(intArray[i]); } return resultArray; } else { return null;

45 JUnit Testing Tool As implied by the name, JUnit tests are performed at the unit level; what does this mean? Documentation about JUnit can be found at Similar unit testing is provided for other languages, including C++ Ant, a build tool we will discuss shortly, also supports JUnit This means you can specify in Ant that it should run all your JUnit tests

46 JUnit Test - 1 package unittest; import junit.framework.*;
import mylist.*; import test.TestUtil; public class LinkedListUnitTest extends TestCase { public LinkedListUnitTest(String name) { super(name); } public void testInsert() { LinkedList l = new LinkedList(); l.insertHead(new Integer(1)); l.insertHead(new Integer(2)); l.insertLast(new Integer(3)); l.insertLast(new Integer(4)); l.insert(new Integer(5), 3); l.insert(new Integer(6), 3); l.insert(new Integer(7), 3); assertTrue(TestUtil.match(l, TestUtil.toIntegerArray(new int[] {2, 1, 3, 7, 6, 5, 4 }))); public void testRemove() { for (int i = 1; i <= 7; i++) { l.insertLast(new Integer(i)); l.removeHead(); l.removeLast(); l.remove(2); assertTrue(TestUtil.match(l, TestUtil.toIntegerArray(new int[] {2, 3, 5, 6})));

47 JUnit Test - 2 public void testClone() throws CloneNotSupportedException { LinkedList l1 = new LinkedList(); for (int i = 1; i <= 7; i++) { l1.insertLast(new Integer(i)); } int[] ia1 = {1, 2, 3, 4, 5, 6, 7}; int[] ia2 = {2, 3, 4, 5, 6, 7}; LinkedList l2 = (LinkedList) l1.clone(); assertTrue("Clone is not identity", l2 != l1); assertTrue("Clone equals to original", l1.equals(l2)); assertTrue("Match 1", TestUtil.match(l1, TestUtil.toIntegerArray(ia1))); assertTrue("Match 2", TestUtil.match(l2, TestUtil.toIntegerArray(ia1))); l2.removeHead(); assertTrue("Match 3", TestUtil.match(l1, TestUtil.toIntegerArray(ia1))); assertTrue("Match 4", TestUtil.match(l2, TestUtil.toIntegerArray(ia2))); assertTrue("Not equal", !l1.equals(l2)); public static Test suite() { return new TestSuite(LinkedListUnitTest.class);

48 JUnit Test Runner There is also a GUI interface to JUnit is you prefer such an interface

49 Ant – A Build Tool Ant directives are stored in a XML file
<project name = “project-name” default = “default-target-name” > … property definitions … … target definitions … </project> <property name=“prop-name” value=“prop-value”/> //names are unique example <property name=“junit” value=“… path to junit tests …” /> <target name = “target-name” depends = “list of dependencies” … task definitions … </target> <target name = “compile” depends = “init” <javac srcdir = “${src}” destdir = “${classes}” includes = “${mylist/*}” source = “1.4” />

50 Common Tasks and Targets
Running: ant target-name Ant is available from jakarta.apache.org Common Tasks Typical Targets


Download ppt "From Building Blocks to Projects"

Similar presentations


Ads by Google