Practice Session 5 Java: Packages Collection Classes Iterators Generics Default Methods Anonymous Classes Generic Methods Lambdas Design by Contract JUnit.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Design By Contract Using JMSAssert.
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
1 CSE 403 Design by Contract Reading: Pragmatic Programmer Ch. 4, Object-Oriented Design and Patterns, Ch. 3 (Horstmann) These lecture slides are copyright.
Practice Session 5 Java: Packages Collection Classes Iterators Generics Design by Contract Test Driven Development JUnit.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Java Review Interface, Casting, Generics, Iterator.
Inheritance Inheritance Reserved word protected Reserved word super
Road Map Introduction to object oriented programming. Classes
1 Software Testing and Quality Assurance Lecture 23 – JUnit Tutorial.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
JUnit, Revisited 17-Apr-17.
22-Jun-15 JUnit. 2 Test suites Obviously you have to test your code to get it working in the first place You can do ad hoc testing (running whatever tests.
24-Jun-15 JUnit. 2 Test suites Obviously you have to test your code to get it working in the first place You can do ad hoc testing (running whatever tests.
24-Jun-15 JUnit. 2 Test suites Obviously you have to test your code to get it working in the first place You can do ad hoc testing (running whatever tests.
1 Introduction to: Design by Contract Fall 2005 OOPD John Anthony.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
12-Jul-15 Lists in Java Part of the Collections Framework.
Stacks, Queues, and Deques
OOP Languages: Java vs C++
Ranga Rodrigo. Class is central to object oriented programming.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
111 Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract,
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
A tool for test-driven development
18-1 Queues Data Structures and Design with Java and JUnit © Rick Mercer.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Lab 6 Stack ADT. OVERVIEW The stack is one example of a constrained linear data structure. In a stack, the elements are ordered from most recently added.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Classes, Interfaces and Packages
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Topic: Classes and Objects
Chapter 6 CS 3370 – C++ Functions.
Chapter 6: The Stack Abstract Data Type
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Type Safety, Generics, Lambdas, Class Object
Test Driven Development
CSE 403 JUnit Reading: These lecture slides are copyright (C) Marty Stepp, They may not be rehosted, sold, or modified without expressed permission.
Generics, Lambdas, Reflections
Object Comparisons and Arrays
Test Driven Development
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
TCSS 360, Spring 2005 Lecture Notes
Corresponds with Chapter 5
Generics, Lambdas and Reflection
Presentation transcript:

Practice Session 5 Java: Packages Collection Classes Iterators Generics Default Methods Anonymous Classes Generic Methods Lambdas Design by Contract JUnit

Java Packages What is Package? – Way to group related class(es) and interface(s) into one unit – Package is basically a folder. Benefits? – Code organization All classes/interfaces related to one topic, are put under same package name. – Allows us to resolve conflicts between class names By splitting the same name classes into two different packages. – Controlling class visibility protected classes are visible to other classes inside the package only Not visible to other packages, when imported.

Java Packages Declaration: – Declared at beginning of class file. – Syntax: package PackageName; Example: Folder: Package MyTest – Sub-folder: Package Outs1 File: Class Print1.java File: Class Print2java – Sub-folder: Package Outs2 File: Class Print1.java MyTest Outs1 Print1.java Print2.java Print1.java Outs2

Java Packages How to use them? – Use of absolute path of class: Example: MyTest.Outs1.Print1 p1; – Using import keyword: Import class: import MyTest.Outs1.Print1; Import all classes under package: import MyTest.Outs1.*; Object declaration: Print1 p1;

Java Collection What is it? – A (huge)package of classes: import java.util.Collection; – Contains useful data structures: LinkedList Stack ArrayList Vector TreeSet PriorityQueue And much more… Full API:

Collection Iterator All java.util.Collection data structures return an iterator to their elements. Iterator commands: – boolean hasNext() Returns true if there is a next element – Object next() Returns the next object element/advances the iterator – void remove() Optional operator / not all iterators implement it Removes the element returned by next

Using the Iterator Example: – Print all Collection object elements: Code: static void printAll (Collection coll) { Iterator iter = coll.iterator( ); //returns iterator while (iter.hasNext( )) { //checks if has next System.out.println(iter.next( ) ); //returns object } }

Default Methods – Java 1.8 Feature Default methods enable us to add new functionalities to interfaces without breaking the classes that implement that interface. Allows us to implement methods directly in the interface! We add default keyword before the access modifier of the method we wish to implement. This implementation will be the default implementation for all classes implementing this interface, and did not override it. Default methods tutorial:

Default Method - Example Implementation of isEmpty() wil act as the default implementation for all implementing classes, as long as the class does not overwrite the implementation. If the same default method is implemented in two different interfaces, and our class extends both interfaces, we must overwrite the default method. interface Stack { void push(E something); E pop(); int size(); boolean isEmpty(); } interface Stack { void push(E something); E pop(); int size(); default boolean isEmpty(){ return (size())==0); }

Generics What are they? – Generic data structures are data structures that allows the use of any object type. – Explicitly declare what object type the data structure is going to use upon declaration, to help finding errors at compilation time. How? – java.util.Collection.Stack stk; Examples: – A Stack that holds Integer objects. java.util.Stack intStack; – A LinkedList holding Student objects: java.util.Collection.LinkedList studentList; Generics Information:

Generics Example Stack stackOfCows = new Stack () Stack stackOfInteger = new Stack () Cow cow = new Cow() stackOfCows.push(cow); stackOfInteger.push(cow);

Generic Methods – Java 1.8 Feature public class Cow { private int age; private int weight; public Cow(int age, int weight) { this.age = age; this.weight = weight; } public int getAge() { return age; } public int getWeight() { return weight; } Given an array of Cow objects what is the maximal object? Is it the heaviest cow? Maybe the oldest? It depends on how you want to compare the cows!

Generic Methods In addition to generic classes and interfaces Java also supports generic methods. Assume that we want to create a utility method for finding the largest item in an array, like before we can have arrays of Integers, Cows, and more. Let’s define a generic method!

Generic Methods Implementation Note the in front of the method signature which parametrize the method. public static T max(T[] array, Comparator comparator) { if (array.length == 0) throw new IllegalArgumentException("empty array"); int maxIndex=0; for (int i=1; i<array.length; i++) if (comparator.compare(array[maxIndex], array[i]) < 0) maxIndex = i; return array[maxIndex]; }

Using Generic Methods public static class CowComparatorByAge implements Comparator { public int compare(Cow o1, Cow o2) { return o1.getAge() - o2.getAge(); } public static class CowComparatorByWeight implements Comparator { public int compare(Cow o1, Cow o2) { return o1.getWeight() - o2.getWeight(); } public static void main(String[] args) { Cow[] cows = {new Cow(7,50), new Cow(9,200), new Cow(3,100)}; System.out.println(max(ints, new CowComparatorByWeight ()).getWeight()); // 200 System.out.println(max(cows, new CowComparatorByAge()).getAge()); // 9 }

Anonymous Classes Anonymous classes enable you to make your code more concise. מתומצת They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class once.

Anonymous Class Example In the previous example we implemented two classes: – CowComparatorByWeight – CowComparatorByAge And we have used them once! A good place to use anonymous classes here. public static void main(String[] args) { Cow[] cows = {new Cow(7,50), new Cow(9,200), new Cow(3,100)}; System.out.println(max(cows, new Comparator (){ public int compare(Cow o1, Cow o2) { return o1.getAge() - o2.getAge(); } }).getAge()); // prints 9 System.out.println(max(cows, new Comparator (){ public int compare(Cow o1, Cow o2) { return o1.getWeight() - o2.getWeight(); } }).getWeight()); // prints 200 }

Lambdas – Java 1.8 Feature Using anonymous classes to implement interfaces of one method only is an overkill. The syntax of such a class is not user friendly. Using lambdas, we can use lambdas instead of anonymous classes which provides easy to implement as well as to readable syntax. Full material:

Lambda Advantages Allows writing a method in the same place to be used. Especially useful in places where a method is being used only once, and the method definition is short. Saves the effort of declaring and writing a separate method to the containing class. (arg1, arg2...) -> { body } (type1 arg1, type2 arg2...) -> { body }

Examples (int a, int b) -> { return a + b; } () -> System.out.println("Hello World"); (String s) -> { System.out.println(s); } () -> 42 () -> { return }; Guide:

Cows Example – Using Lambda public static void main(String[] args) { Cow[] cows = {new Cow(7,50), new Cow(9,200), new Cow(3,100)}; System.out.println(max(cows, (Cow o1, Cow o2) -> { return o1.getAge() - o2.getAge(); }).getAge()); System.out.println(max(cows, (Cow o1, Cow o2) -> { return o1.getWeight() - o2.getWeight(); }).getWeight()); } public static void main(String[] args) { Cow[] cows = {new Cow(7,50), new Cow(9,200), new Cow(3,100)}; System.out.println(max(cows, new Comparator (){ public int compare(Cow o1, Cow o2) { return o1.getAge() - o2.getAge(); } }).getAge()); // prints 9 System.out.println(max(cows, new Comparator (){ public int compare(Cow o1, Cow o2) { return o1.getWeight() - o2.getWeight(); } }).getWeight()); // prints 200 } Anonymous Classes: Lambda:

Design by Contract(DBC) What? – An approach for designing software. – Expresses contract between specification and implementation. – An agreement between two parties: client and supplier. Why? – Trustworthy documentation. – Strong support for debugging. – Facilitate code reuse. Condition Types in DbC: – Preconditions Things that must be true before invoking a method No conditions on after invocation. – Postconditions Things that must be true after invoking a method No conditions on before invocation – Invariants things that must be true before and after any method is invoked Must be true immediately after construction.

Design by Contract Example public interface MyCollection { /** * Remove obj from the collection * !( obj == null ) * !contains( obj ) */ public void remove( Object obj ); Precondition disallows null argument. Postcondition varifies that method removes ALL occurrences of obj /** size() >= 0 */ public interface Queue { Assures queue size >= 0 always!

Design by Contract Principles Separate queries from commands Separate basic queries from derived queries. For each derived query, write a postcondition that specifies what result will be returned, in terms of one or more basic queries. For each command, write a postcondition that specifies the value of every basic query. For every query and command, decide on a suitable precondition. Write invariants to define unchanging properties of objects.

PRINCIPLE 1: separate commands and queries public int size(); public Object head(); public boolean isEmpty(); public void add( Object o ); public void remove(); //just a command - no result Commands Queries

PRINCIPLE 2: separate basic queries and derived queries public boolean isEmpty(); -- we can derive isEmpty() from size() public int size(); public Object head(); Basic queries Derived queries The choice of basic queries can change as we develop contracts

PRINCIPLE 3: specify derived queries in terms of basic queries /** * Is the queue empty? * return == ( size() == 0 ) */ public boolean isEmpty(); -- if we know the value of size(), we also know -- the value of isEmpty()

PRINCIPLE 4: specify postcondition for commands in terms of basic queries /** * The first element in the queue * size() >= 1 return == elements().get(0) */ public Object head(); postcondition uses basic query.get() for its implementation

PRINCIPLE 5: add preconditions where appropriate /** * The first element in the queue * size() >= 1 */ public Object head(); It wouldn’t make the software better to pretend that an empty queue has a head element.

PRINCIPLE 6: specify invariant properties /** size() >= 0 */ public interface Queue { Aim for properties that: - help readers build correct conceptual model

Junit - Assert methods Each assert method has parameters like these: message, expected-value, actual-value – assertTrue(String message, Boolean test) – assertFalse(String message, Boolean test) – assertNull(String message, Object object) – assertNotNull(String message, Object object) – assertEquals(String message, Object expected, Object actual) (uses equals method) – assertSame(String message, Object expected, Object actual) (uses == operator) – assertNotSame(String message, Object expected, Object actual) Assert methods dealing with floating point numbers get an additional argument, a tolerance. (for rounding) Each assert method has an equivalent version that does not take a message – however, this use is not recommended because: – messages helps documents the tests – messages provide additional information when reading failure logs

setUp/tearDown setUp()/tearDown() – Functions which will run before and after each test. – Example usage: setUp(): creating new objects tearDown(): clearing data, resetting data. – If self destruction is good enough, there is no need to implement it. setUpBeforeClass()/tearDownBeforeClass() – functions which will run exactly once before and after all the tests. – Can be used to initialize objects which will be used throughout the tests. – Changes done in first test, can be used as input data for the upcoming one.

Call order of the functions

JUnit tests for Counter class public class CounterTest { Counter counter1; public CounterTest() { } // default protected void setUp() { // creates a (simple) test fixture counter1 = new Counter(); public void testIncrement() { assertTrue(counter1.increment() == 1); assertTrue(counter1.increment() == 2); public void testDecrement() { assertTrue(counter1.decrement() == -1); } } Note that each test begins with a brand new counter This means you don’t have to worry about the order in which the tests are run

Junit - Example Interface: package spl.util; /** * All objects are of type T. Contents are ordered in Last-In-First-Out order. */ public interface Stack { /** * add the object at the top of the stack. (This is a command.) obj * any non null T object to be added to the stack none. this.isEmpty()==false this.pop(); obj */ void push(T obj);

/** * remove the top object from the stack and returns it. the topmost object on the stack Exception in case the stack is empty this.isEmpty()== false; none. */ T pop() throws Exception; /** True if the Stack is empty, or False if the Stack contains at * least one Object}. none. none. */ boolean isEmpty(); }

Create Class StackImpl package spl.util; public class StackImpl implements Stack { public void push(T obj) { } public T pop() throws Exception { return null; } public boolean isEmpty() { return false; }

Creating a Test Case package spl.util; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StackImplTest { Stack public void setUp() throws Exception { this.stack = new StackImpl (); public void tearDown() throws Exception { } Before -> run before each test After-> run after each test

@Test public void testPush() { fail("Not yet implemented"); public void testPop() { fail("Not yet implemented"); public void testIsEmpty() { assertEquals(true, stack.isEmpty()); } What happens when we run the tests? All 3 tests fail: -testPush and testPop because the methods are not implemented. -testIsEmpty since isEmpty returns false, even though the stack is empty.

Add implementation to isEmpty() to pass the tests. Implement other tests and add the implementation of the methods they test to pass them. Change the interface to include public void remove() and public T top() in addition to pop(), and implement pop() using remove and top, to separate queries from commands. And so on….