overview
play

Overview Topics Kinds of errors Preconditions, postconditions, and - PowerPoint PPT Presentation

Overview Topics Kinds of errors Preconditions, postconditions, and invariants CSE 143 Java Specification as a contract Throwing Exceptions Assertions Software Quality Programming by Contract Reading: Ch. 5 7/6/2004 (c)


  1. Overview • Topics • Kinds of errors • Preconditions, postconditions, and invariants CSE 143 Java • Specification as a contract • Throwing Exceptions • Assertions Software Quality Programming by Contract Reading: Ch. 5 7/6/2004 (c) 2001-4, University of Washington 10-1 7/6/2004 (c) 2001-4, University of Washington 10-2 Getting Software Right Example: StringList class • Software is notoriously prone to errors • Here’s a recycled example of a class that implements a simple, fixed-size list data structure. Operations: • Bugs can be amusing class StringList { // a list of strings • Bugs can be fatal StringList(int capacity); // create new StringList with given capacity • Bugs are almost always costly boolean isEmpty( ); // = “this StringList is empty” boolean isFull( ); // = “this StringList is full” • What are errors and why do they happen? int size( ); // = # of Strings in this StringList • What can we do to detect them? boolean add(String str); // add str to this StringList, result true // if success • How can we handle errors? boolean contains(String str); // = “this StringList contains str” • How can we prevent them? String get(int pos); // return String at given position String remove(int pos); // return String at given position and remove // it from this StringList 7/6/2004 (c) 2001-4, University of Washington 10-3 7/6/2004 (c) 2001-4, University of Washington 10-4 CSE143 Sp04 10-1

  2. StringList Instance Variables StringList: What Could Go Wrong? • Representation is an array whose length is fixed when • What kinds of errors could occur in either the the StringList is created, plus a count of the current implementation or use of StringList number of strings stored in the list • This is a different question from how would one test for these problems • For each possible error class StringList { // a list of strings // instance variables • What could go wrong? private String[ ] strings; // Strings in this StringList are stored in • How should we deal with it? private int size; // strings[0] through strings[size-1] … } 7/6/2004 (c) 2001-4, University of Washington 10-5 7/6/2004 (c) 2001-4, University of Washington 10-6 Error Handling Preconditions and Postconditions • Software failures fall into two broad categories • Methods typically make assumptions about the state of the world before, during, and after they are executed • Internal programming errors (“bugs”) • Typically logical formulas: 0<=size<capacity; the array is • Failures because of interaction with external resources or users (out of memory, file not found, etc.) sorted; etc. • Two key kinds of assumptions • Incorrectly formatted data and similar problems also need to be handled, but that is part of normal processing • Precondition : Something that must be true before a method can be called; a requirement • For now, focus on software failures • Postcondition : Something that is guaranteed to be true after a • Principle: If a method detects it is going to fail, it must method terminates execution (provided the precondition was do something appropriate to report the failure; it is never true when it was called) acceptable to return to the caller as if nothing happened 7/6/2004 (c) 2001-4, University of Washington 10-7 7/6/2004 (c) 2001-4, University of Washington 10-8 CSE143 Sp04 10-2

  3. Preconditions & Postconditions Class Invariants • What would be reasonable preconditions for • An invariant is a condition that is always true • Special case: a class invariant –an invariant about a square root function? properties of class instances; often a relationship between instance variables (state) a method to insert new item into a list object? • Examples 0 <= size <= capacity • What would be reasonable postconditions for The list data is stored in items[0..size-1] • Note: a class invariant might be false for a moment while a a sort routine? method is updating related variables, but it must always be true by the time a constructor or method terminates the constructor for a list object? 7/6/2004 (c) 2001-4, University of Washington 10-9 7/6/2004 (c) 2001-4, University of Washington 10-10 Writing Bug-Free Software Design by Contract • Preconditions, postconditions, and invariants are • The preconditions and postconditions of a method can incredibly useful be viewed as a contract between the implementer of the method and the client code that uses it • Include all non-trivial ones as comments in the code • Clearly specifies the responsibilities of both parties • These are essential parts of the design and a reader must understand them to understand the code • Client must ensure all preconditions are true before calling the • If you don’t write them down, the reader (who may be you) will method have to reconstruct them as best he/she can • Implementation must guarantee that postconditions are true, provided the preconditions were true when the method was • Whenever you update a variable, check any invariants called that mention it to be sure the invariant still holds • May need to update related variables to make this happen 7/6/2004 (c) 2001-4, University of Washington 10-11 7/6/2004 (c) 2001-4, University of Washington 10-12 CSE143 Sp04 10-3

  4. Precondition Failures What if a precondition is not true? • Principle: Crash early! • Suppose this method is called with pos < 0 or pos >=size()? • The sooner a precondition failure is detected the better /** Return list element at given position. Precondition: 0<=pos<size() */ • Who is responsible for checking? String get (int pos) { • Most logical place is at the beginning of the called method … • How aggressive should we be about checking? } • Can overdo it Actual normal-case code becomes hard to find • What should we do? Expensive checks can hurt performance Can’t always check everything 7/6/2004 (c) 2001-4, University of Washington 10-13 7/6/2004 (c) 2001-4, University of Washington 10-14 What if a precondition is not true? Critique • One solution • Not a good idea for at least two reasons /** Return list element at given position. Precondition: 0<=pos<size() • Should never have extra output in a method that is not String get (int pos) { intended to produce output if (pos < 0 || pos >= size) { • (bad cohesion; also, unexpected output might panic end user) System.out.println(“naughty user – pos has bad value in get”); return null; • Null as an error code (and error codes in general) } else { • Can it get confused with a legitimate return value? return strings[pos]; • Will the programmer always remember to check? } (What do you think?) } • Helpful error message, returns something user can check • Good idea or not? 7/6/2004 (c) 2001-4, University of Washington 10-15 7/6/2004 (c) 2001-4, University of Washington 10-16 CSE143 Sp04 10-4

  5. Throwing Exceptions Details • One good solution: throw an exception • The statement `throw new IndexOutOfBoundsException( ); • Basic idea: generate a runtime error, exactly as done for creates a new exception object and uses it to signal a things like out-of-bounds array subscripts or null particular kind of error references • Normally halts execution with a suitable error message /** Return list element at given position. Precondition: 0<=pos<size * @throws IndexOutOfBoundsException if pos is invalid */ • Not the same as a regular return statement – can terminate String get (int pos) { many active methods at once if nobody catches and recovers if (pos < 0 || pos >= size) { from the problem (coming next lecture) throw new IndexOutOfBoundsException( ); We’ll also see how to define new kinds of exceptions (errors) } return strings[pos]; } 7/6/2004 (c) 2001-4, University of Washington 10-17 7/6/2004 (c) 2001-4, University of Washington 10-18 Some common standard Java exceptions How much checking should we do? • IllegalArgumentException • Can overdo it Parameter value is inappropriate • Error checking code can overwhelm normal code • NullPointerException Harder to read, understand, modify • Checking takes time; can have unacceptable performance Parameter value is null when it should not be penalty Use this instead of less specific IllegalArgumentException if it applies • IndexOutOfBoundsException • Distinguish two cases Array or list index is out of range • Public methods: can’t trust the caller Use this instead of IllegalArgumentException if it applies Need to check parameters and signal errors whenever possible • Non-public methods: programmer controls circumstances under which method is called Programmer has no one else to blame if something is wrong Still, worth some sort of check during development to catch bugs early 7/6/2004 (c) 2001-4, University of Washington 10-19 7/6/2004 (c) 2001-4, University of Washington 10-20 CSE143 Sp04 10-5

Recommend


More recommend