CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: 15.2 - 15.3 slides created by Marty Stepp and Hélène Martin

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
1 Various Methods of Populating Arrays Randomly generated integers.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Building Java Programs Appendix B
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
CSE 143 Lecture 4: testing and complexity reading:
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
CSE 143 Lecture 3 Inheritance slides created by Marty Stepp
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Building Java Programs Chapter 15 Implementing a Collection Class: ArrayIntList Copyright (c) Pearson All rights reserved.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
CHAPTER 5 ArrayLists.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSE 143 Lecture 6 Inheritance; binary search reading: 9.1, ; 13.1 slides created by Marty Stepp
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
EE 422C Day 2 Java, Eclipse. Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
CSE 143 Lecture 4 Exceptions and ArrayList slides created by Marty Stepp
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
slides adapted from Marty Stepp and Hélène Martin
Building Java Programs Chapter 13 Lecture 13-1: binary search and complexity reading:
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
CSE 143 Lecture 1 Arrays (review) slides created by Marty Stepp
CSE 143 Lecture 14: testing.
Topic 21 arrays - part 1 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from "Should.
Preconditions precondition: Something your method assumes is true at the start of its execution. Often documented as a comment on the method's header:
this keyword this : A reference to the implicit parameter Syntax:
this keyword this : A reference to the implicit parameter Syntax:
CSE 143 Lecture 4 ArrayList Reading: 10.1.
Defining New Types of Objects, part 3
slides created by Ethan Apter
Object initialization: constructors
CSE 143 Lecture 2 Collections and ArrayIntList
Building Java Programs
slides created by Ethan Apter
slides adapted from Marty Stepp and Hélène Martin
slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 More ArrayIntList:
slides created by Ethan Apter
Go to pollev.com/cse143.
CSE 143 Lecture 5 More ArrayIntList:
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
CSE 373 Implementing a Stack Reading: Weiss Ch. 3; 3.6; 1.5
slides created by Marty Stepp
CSE 143 Lecture 4 Implementing ArrayIntList; Binary Search
Building Java Programs
slides created by Marty Stepp
CSE 143 Lecture 2 ArrayIntList, binary search
Building Java Programs
slides created by Ethan Apter
File output; Arrays reading: 6.4 – 6.5, 7.1
Lecture 8-2: Object Behavior (Methods) and Constructors
CSE 143 Lecture 6 interfaces; eclipse; testing
CSE 143 Lecture 4 Implementing ArrayIntList reading:
slides adapted from Marty Stepp
slides created by Ethan Apter and Marty Stepp
CSE 143 Lecture 21 Advanced List Implementation
Software Specifications
slides created by Marty Stepp
Implementing ArrayIntList
slides created by Marty Stepp
Presentation transcript:

CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin

2 Not enough space What to do if client needs to add more than 10 elements? –list.add(15); // add an 11th element –Possible solution: Allow the client to construct the list with a larger initial capacity. index value size10

3 Multiple constructors Our list class has the following constructor: public ArrayIntList() { elementData = new int[10]; size = 0; } Let's add a new constructor that takes a capacity parameter: public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } –The constructors are very similar. Can we avoid redundancy?

4 this keyword this : A reference to the implicit parameter (the object on which a method/constructor is called) Syntax: –To refer to a field: this. field –To call a method: this. method ( parameters ); –To call a constructor this( parameters ); from another constructor:

5 Revised constructors // Constructs a list with the given capacity. public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } // Constructs a list with a default capacity of 10. public ArrayIntList() { this(10); // calls (int) constructor }

6 Class constants public static final type name = value ; class constant: a global, unchangeable value in a class –used to store and give names to important values used in code –documents an important value; easier to find and change later classes will often store constants related to that type –Math.PI –Integer.MAX_VALUE, Integer.MIN_VALUE –Color.GREEN // default array length for new ArrayIntLists public static final int DEFAULT_CAPACITY = 10;

7 Running out of space What should we do if the client starts out with a small capacity, but then adds more than that many elements? –list.add(15); // add an 11th element –Answer: Resize the array to one twice as large. index value size10 index value size11

8 The Arrays class Class Arrays in java.util has many useful array methods: Syntax: Arrays. methodName ( parameters ) Method nameDescription binarySearch( array, value ) returns the index of the given value in a sorted array (or < 0 if not found) binarySearch( array, minIndex, maxIndex, value ) returns index of given value in a sorted array between indexes min /max - 1 (< 0 if not found) copyOf( array, length ) returns a new resized copy of an array equals( array1, array2 ) returns true if the two arrays contain same elements in the same order fill( array, value ) sets every element to the given value sort( array ) arranges the elements into sorted order toString( array ) returns a string representing the array, such as "[10, 30, -25, 17]"

9 Problem: size vs. capacity What happens if the client tries to access an element that is past the size but within the capacity (bounds) of the array? –Example: list.get(7); on a list of size 5 (capacity 10) –Currently the list allows this and returns 0. Is this good or bad? What (if anything) should we do about it? index value size5

10 Preconditions precondition: Something your method assumes is true at the start of its execution. –Often documented as a comment on the method's header: // Returns the element at the given index. // Precondition: 0 <= index < size public int get(int index) { return elementData[index]; } –Stating a precondition doesn't really "solve" the problem, but it at least documents our decision and warns the client what not to do. –What if we want to actually enforce the precondition?

11 Bad precondition test What is wrong with the following way to handle violations? // Returns the element at the given index. // Precondition: 0 <= index < size public int get(int index) { if (index = size) { System.out.println("Bad index! " + index); return -1; } return elementData[index]; } –returning -1 is no better than returning 0 (could be a legal value) –println is not a very strong deterrent to the client (esp. GUI)

12 Throwing exceptions (4.5) throw new ExceptionType (); throw new ExceptionType (" message "); Generates an exception that will crash the program, unless it has code to handle ("catch") the exception. Common exception types: –ArithmeticException, ArrayIndexOutOfBoundsException, FileNotFoundException, IllegalArgumentException, IllegalStateException, IOException, NoSuchElementException, NullPointerException, RuntimeException, UnsupportedOperationException Why would anyone ever want a program to crash?

13 Exception example public int get(int index) { if (index = size) { throw new ArrayIndexOutOfBoundsException (index); } return elementData[index]; } –Exercise: Modify the rest of ArrayIntList to state preconditions and throw exceptions as appropriate.

14 Private helper methods private type name ( type name,..., type name ) { statement(s) ; } a private method can be seen/called only by its own class –your object can call the method on itself, but clients cannot call it –useful for "helper" methods that clients shouldn't directly touch private void checkIndex(int index, int min, int max) { if (index max) { throw new IndexOutOfBoundsException(index); }

15 Postconditions postcondition: Something your method promises will be true at the end of its execution. –Often documented as a comment on the method's header: // Makes sure that this list's internal array is large // enough to store the given number of elements. // Postcondition: elementData.length >= capacity public void ensureCapacity(int capacity) { // double in size until large enough while (capacity > elementData.length) { elementData = Arrays.copyOf(elementData, 2 * elementData.length); } } –If your method states a postcondition, clients should be able to rely on that statement being true after they call the method.

16 Thinking about testing If we wrote ArrayIntList and want to give it to others, we must make sure it works adequately well first. Some programs are written specifically to test other programs. –We could write a client program to test our list. –Its main method could construct several lists, add elements to them, call the various other methods, etc. –We could run it and look at the output to see if it is correct. –Sometimes called a unit test because it checks a small unit of software (one class). black box: Tests written without looking at the code being tested. white box: Tests written after looking at the code being tested.

17 Tips for testing You cannot test every possible input, parameter value, etc. –So you must think of a limited set of tests likely to expose bugs. Think about boundary cases –positive; zero; negative numbers –right at the edge of an array or collection's size Think about empty cases and error cases –0, -1, null; an empty list or array test behavior in combination –maybe add usually works, but fails after you call remove –make multiple calls; maybe size fails the second time only

18 Example ArrayIntList test public static void main(String[] args) { int[] a1 = {5, 2, 7, 8, 4}; int[] a2 = {2, 7, 42, 8}; int[] a3 = {7, 42, 42}; helper(a1, a2); helper(a2, a3); helper(new int[] {1, 2, 3, 4, 5}, new int[] {2, 3, 42, 4}); } public static void helper(int[] elements, int[] expected) { ArrayIntList list = new ArrayIntList(elements); for (int i = 0; i < elements.length; i++) { list.add(elements[i]); } list.remove(0); list.remove(list.size() - 1); list.add(2, 42); for (int i = 0; i < expected.length; i++) { if (list.get(i) != expected[i]) { System.out.println( "fail; expect " + Arrays.toString(expected) + ", actual " + list ); }