CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
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.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
ITEC200 Week02 Program Correctness and Efficiency.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
OOP #10: Correctness Fritz Henglein. Wrap-up: Types A type is a collection of objects with common behavior (operations and properties). (Abstract) types.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Chapter 10 Classes Continued
Presentation Outline What is JUnit? Why Use JUnit? JUnit Features Design of JUnit Downloading JUnit Writing Tests – TestCase – TestSuite Organizing The.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Computer Science 340 Software Design & Testing Design By Contract.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Object-Oriented Software Testing. C-S 5462 Object-Oriented Software Testing Research confirms that testing methods proposed for procedural approach are.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
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.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
111 Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract,
Utilities (Part 2) Implementing static features 1.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
A tool for test-driven development
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
JUnit A framework which provides hooks for easy testing of your Java code, as it's built Note: The examples from these slides can be found in ~kschmidt/public_html/CS265/Labs/Java/Junit.
1  lecture slides online
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
1 CSC 216 Lecture 3. 2 Unit Testing  The most basic kind of testing is called unit testing  Why is it called “unit” testing?  When should tests be.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
PROGRAMMING TESTING B MODULE 2: SOFTWARE SYSTEMS 22 NOVEMBER 2013.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Introduction to Exceptions in Java CS201, SW Development Methods.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
Chapter 2: Error Handling, Software Testing and Program Efficiency
Introduction to Classes and Objects
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Defining Classes and Methods
CSE 143 Java Exceptions 1/18/2019.
Joel Adams and Jeremy Frens Calvin College
CMSC 202 Exceptions.
Presentation transcript:

CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia Lee is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. Based on a work at Permissions beyond the scope of this license may be available at LeeCreative Commons Attribution-NonCommercial 4.0 International Licensehttp://peerinstruction4cs.org

Reading Quiz! 1) Which of the following would qualify as a mutator method? A. A method that does not return a value but changes the state of an object. B. A method that returns a value without changing the state of the object.

Reading Quiz! 2) Which of the following would NOT be part of the an ADT specification? I. What operations are supported on the data type. II. The language that it should be implemented in. III. The values that the data type might take. IV. How the data type should be implemented. Options: A. I and IV B. I and III C. II and III D. II and IV

Reading Quiz! 3) Testing a class based on the ADT specification, without knowing the implementation is called: A. Test driven development B. Black-box testing C. White-box testing D. Unit testing

Reading Quiz! 4) Which of the following demonstrates a Composition design pattern? A. A class ArrayList implementing the List interface. B. A class Queue using a LinkedList object internally, to store and retrieve items. C. A class Circle extending a class Shape.

Inheritance vs. Composition Design patterns using UML

Collections  A collection is an ADT that contains data elements, and provides operations on them There are different ways that elements can be “collected”:  Set  List  Sorted list  … All collections implement the interface Collection

Java Generics  Key to Java’s Collections are generics  Generics answer the question: “what is the collection a collection of?”  If this question isn’t enforced with generics, there can be runtime errors when the what comes out of the collection is not what you expected  Set means a set of things that are of type E.

Which choice is the most reasonable model of our bag of presents? A. public class Present implements Collection B. public class Bag implements Present C. public class Present implements Bag D. public class Bag implements Collection E. Other/none/more than one

Placing limits on what kind of thing our collection can store  This is a kid, so we ONLY want the bag to hold presents that are:  Wrapable (can be wrapped in paper)  Implements a “ wrap() ” method  Playable (can be played with)  Implements a “ play() ” method  How can we represent these requirements in Java?

Java Interfaces ADTs in the Java language

Actual Google interview question (given to a UCSD student)  Given an interface called Set with the functions union, intersect and subtract, implement that interface in a class. 12

Actual Google interview question (given to a UCSD student)  Given an interface called Set with the functions union, intersect and subtract, implement that interface in a class.  What would our implementation start with? A. public class Set { B. public class MySet extends Set { C. public class FancySet implements Set { D. Other/none/more than one 13

UML Class Diagram: Implementation  LinkedList and ArrayList “is-a” List  List is a datatype, but you cannot create a List by new List()  To create a List, you must create an instance of a class that implements the List interface > List add(Object) size() ArrayListLinkedList

Back to the presents example: How can we represent the Playable and Wrapable requirements in Java? 1. Create interfaces Playable (has a method void play()) and a method Wrapable (has a method void wrap()) 2. Now how do we use those interfaces to impose the requirements on Present? > Wrapable wrap() Present > Playable play() > Wrapable wrap() Present > Playable play() A. B. C. Other/ none/ more than one D. I don’t understand this!!

Back to the presents example: How can we represent the Playable and Wrapable requirements in Java? 1. Create interfaces Playable and Wrapable 2. Create a class* Present that implements Wrapable and Playable. 3. Create classes for different kinds of presents, all of which extend* Present 4. Now objects of those classes can be stored in the Bag collection! > Wrapable wrap() Present > Playable play() Doll ToyCar NerfGun

Interfaces and Implementation A class implementing an interface defines an “is a” relationship between the class and the interface – A LinkedList “is a” List – A class inherits method signatures from interfaces it implements An interface can extend one or more other interfaces – A Set “is-a” Collection – An interface inherits method signatures from interfaces it extends

Some Interfaces in JCF

Some Classes Implementing Interfaces in JCF

Software Testing Black box and clear box

 In CSE 12 we will take a test-driven development approach, with unit testing  Test-driven development means: first writing tests, and then writing the software that will be tested Test-driven Development

Black-box Testing  You don’t know (or you pretend you don’t know) how something is implemented  You test only based on inputs and outputs Clear-box Testing  (Also known as “white-box testing”)  If you can look inside the black box and see how a method is implemented, you can do more detailed testing

Designing clear-box tests  How many test cases would you need to do thorough clear-box testing on this code? public void mysteryMethod(int x){ someMethod(); if (x < 5){ methodCall(); } else { otherMethod(); } anotherOne(); } A. 1 test case B. 2 test cases C. 3 test cases D. > 3 test cases

Discussion  What do you think are advantages and disadvantages to each?  When might you do black-box testing?  When might you do clear-box testing?

Software Testing Java’s JUnit system

Unit testing Whether you are doing black-box or clear-box testing, you should test every important unit of a software system What is a unit? In object-oriented programming, usually a software unit is taken to be a single method So: we should test every method of every class in the software JUnit is a widely used framework for unit testing of Java software…

Unit testing with the swingui of Junit 3.8.1: all tests passed The green bar of happiness; all tests passed! Names of the testing methods corresponding to the test cases you prepared. A green check mark means the test passed. 27

When one or more tests fail The red bar of sadness; some tests failed Names of the testing methods in your test suite. A red X means the test failed. Stack trace telling what was expected, what was generated and where the test failed; very handy!

JUnit basics  To do unit testing in the Junit framework:  Define a subclass of junit.framework.TestCase  Optional:  Define instance variables that store the state of the “test fixture”, i.e. the objects that will be tested  Initialize the fixture state by overriding the setUp() instance method  Clean-up the fixture state after a test by overriding the tearDown() instance method  Define public void no-argument methods with names that start with test. Each “testXXX” method should be written to test a particular aspect of the test fixture  Define a main() method to run your TestCase class as a program 29

import junit.framework.*; public class RectangleTester extends TestCase { private Rectangle r1, r2; // test fixtures TestCase and test fixtures  Define a subclass of junit.framework.TestCase  Define instance variables that store the state of the “test fixture”, i.e. the objects that will be tested To inherit the testing and test run methods we will need

setUp() and tearDown() /* Called AUTOMATICALLY before each testXXX() method is run */ protected void setUp() { r1 = new Rectangle(); r2 = new Rectangle(2.0,3.0); } /* Called AUTOMATICALLY after each testXXX() method is run */ protected void tearDown() { r1 = null; r2 = null; } setup(); testXXX(); teardown(); This is the sequence of calls the JUnit framework does for you automatically for each test method testXXX() that is invoked. Make sure each test method starts with a clean copy of the test fixture.

Coding a test case as a “testXXX” method /** Test case 2.1: verify that default constructor sets default instance variable values correctly */ public void testDefaultInstance() { assertEquals(1.0,r1.getLength()); assertEquals(1.0,r1.getHeight()); } /** Test case 2.6: verify that mutator for length throws * exception on illegal input. */ public void testMutatorIllegalInput() { try { r1.setLength(0); // 0 is illegal, should throw fail(); } catch (IllegalArgumentException e) { // test passes } Remember: setUp() will be called prior to each test method getting called, creating test object r1 anew for each test

Running your TestCase class /** Run RectangleTester as a gui application */ public static void main(String args[]) { junit.swingui.TestRunner.main(new String[] {“RectangleTester”}); } To run a class as a program, the class must have a public static void main() method. Here are two ways to define it in the Junit framework, depending on whether you want a GUI or text version: /** Run RectangleTester as a text console application */ public static void main(String args[]) { junit.textui.TestRunner.main(new String[] {“RectangleTester”}); } 33

More JUnit basics  Test fixture instance variables are optional: you can do the same thing with local variables inside the test methods  If you are not using test fixture instance variables, you do not need to define setUp() and tearDown() either  When you run your TestCase class as a program, each “testXXX” method is called automatically…  If a Junit assertion fails when a testXXX method runs, that test fail s  If testXXX method throws an exception, that is considered an error, not a test failure!  If a testXXX method returns normally, that test pass es 34

JUnit assertion methods  The JUnit framework provides many useful assertion methods to use in your testXXX() methods assertEquals(x,y) // fail if x is not equal to y assertTrue(b) // fail if b has boolean value false assertFalse(b) // fail if b has boolean value true assertSame(x,y) // fail if x and y point to different objects assertNotSame(x,y) // fail if x and y point to the same object assertNull(x) // fail if x is not null assertNotNull(x) // fail if x is null fail() // always fails  All these assertion methods are overloaded with a version that takes an additional first argument of type String, a message which will be printed out in some contexts 35

Specifying an ADT  An ADT specifies the possible values instances of the ADT can have, and specifies the operations the ADT provides on those values  In more detail, an ADT specification should generally include these: ADT name: The name of the data type. ADT description: A brief summary description of the type. ADT invariants: Assertions that must always be true of any instance of this type. ADT attributes: Aspects of the state of an instance of the type, as observable by a client ADT operations: The behavior of an instance of the type, as observable by a client. 36

Specifying operations of an ADT Specifying ADT operations is particularly important: these operations constitute the API, and are the primary way that users of the ADT interact with its instances. For each ADT operation, you should specify: responsibilities : A brief summary of what the operation does. pre-conditions : What must be true on entry to the operation if the operation is to execute successfully. This may include assumptions about the state of the object, assumptions about the parameters passed in, etc. An operation's pre- conditions must be consistent with all of the ADT's invariants. post-conditions : What the operation guarantees to be true when it returns, if the pre-conditions were true when the operation was called. An operation's post-conditions must be consistent with all of the ADT’s invariants. returns : The value, if any, returned by the operation. exceptions : A description of the exceptions the operation may throw. 37

Programming by contract  A precise and complete specification of an ADT operation is a contract for the operation  It lays out the responsibilities of the provider (the method) and the client (any caller of the method)  If both sides meets their responsibilities, the operation will work  The contract is a guide both for the implementer and the users of the method  Writing these specifications first, then implementing them, is sometimes called programming by contract 38

Pre- and Post-conditions Think of method preconditions as the method saying: “I require this.” Think of method postconditions as the method saying: “I ensure this.” If the preconditions are satisfied when the method is called, then the method guarantees that the postconditions will be satisfied when the method returns. If the preconditions are not satisfied -- that is, if the client does not meet its end of the contract -- then the method does not guarantee anything! 39

Checkpoint  What is the relationship between ADT or class invariants and an operation’s pre- and post-conditions?  How do pre- and post-conditions relate to writing a test for the operation?  Can you write a test for what the operation does when its pre-conditions are not met? 40

Example ADT specification: Rectangle  Description  A rectangle is a four-sided shape in which opposite sides are parallel and equal in size. The size of a side must be greater than 0. A rectangle has four right angles.  Invariants  Opposite sides are of equal size.  Length and height must be greater than 0.  Attributes  DEFAULT_SIZE a constant, the default size for the dimensions  length size of the “top” and “bottom” sides  height size of the “left” and “right” sides  surface area the surface area of the rectangle  perimeter the perimeter of this rectangle 41

Review of Java Exceptions  Exceptions are a way of signaling that something exceptional has happened at runtime  When an “exceptional condition” occurs, an exception object is created storing information about the nature of the exception (kind, where it occurred, etc.), and then this exception object is thrown  The JVM looks back through the chain of method calls for a block of code to catch and handle the exception  If there isn't a catch block for the exception, your program will be killed, and some diagnostic info printed to the terminal 42

remember, this means extends 43

Kinds of exceptions  Checked exceptions –  Descended from class Throwable, but not descended from RuntimeException or Error.  The compiler will check that you either catch or rethrow checked exceptions  Unchecked exceptions –  Descended from RuntimeException or from Error  The compiler does not check to see that you catch or explictly rethrow these exceptions (though of course you can catch or declare them if you want) 44

Creating and Throwing an Exception  Though it is not strictly required by the Programming-by-Contract paradigm, a method can check to see if its own preconditions are met  If it finds that its preconditions are not met, what should it do?  Creating and throwing an exception, instead of attempting to complete the operation or returning a value, is often a good design decision  If so, this should be documented as part of the specification of the method  Example: setLength() method in a Rectangle class… 45

Creating and Throwing an Exception Two ways to specify the setLength() operation… setLength( newLength ) pre-condition: newLength > 0 responsibilities: sets length to newLength post-condition: rectangle’s length field is set to newLength returns: nothing Becomes: setLength( newLength ) pre-condition: newLength > 0 responsibilities: sets length to newLength post-condition: rectangle’s length field is set to newLength returns: nothing throws:IllegalArgumentException if precondition is not met 46

Implementing setLength /** * Set the length dimension of this Rectangle. theLength the new length of this Rectangle ; * must be > 0 IllegalArgumentException if theLength is <= 0. */ public void setLength( double theLength ) { if ( theLength <= 0 ) throw new IllegalArgumentException(“Illegal Rectangle length (“ + theLength + “): must be > 0 “); this.length = theLength; } Create an exception object the way you create any other kind of object, with new. Throw the exception with the reserved word throw. Document that the method throws an exception 47

Next time o Test plans, test cases, and more about JUnit o The Collection and List Interfaces in the JCF o Iterators and the Iterator Pattern o Developing a test plan for a Collection or List class Reading: Gray, Ch 4 and Ch 5 48