12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Overview  Common errors … —Typical.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
Written by: Dr. JJ Shepherd
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
ESE Einführung in Software Engineering 7. Modeling Behaviour Prof. O. Nierstrasz.
FIT FIT1002 Computer Programming Unit 19 Testing and Debugging.
CP — Concurrent Programming 8. Liveness and Asynchrony Prof. O. Nierstrasz Wintersemester 2005 / 2006.
1 CS101 Introduction to Computing Lecture 23 Flow Control & Loops (Web Development Lecture 8)
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap  Syntax and Semantics  Semantics of Expressions 
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Overview  Common errors … —Typical.
ESE Einführung in Software Engineering N. XXX Prof. O. Nierstrasz Fall Semester 2009.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
13. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Summary, Trends, Research...  Summary: functional, logic and object-oriented.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
13. A bit of Smalltalk. © Oscar Nierstrasz 2 Roadmap  The origins of Smalltalk  What is Smalltalk?  Syntax in a nutshell  Seaside — web development.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
N. XXX Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap Overview  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
Transformation of Java Card into Diet Java Semester Project Presentation Erich Laube.
Chapter 10 Classes Continued
OORPT Object-Oriented Reengineering Patterns and Techniques X. CHAPTER Prof. O. Nierstrasz.
CP — Concurrent Programming X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
12. eToys. © O. Nierstrasz PS — eToys 12.2 Denotational Semantics Overview:  … References:  …
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Java Tutorial. Object-Oriented Programming Concepts Object –a representation of some item state  fields/members and should be encapsulated behavior 
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.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
1 Relational Expressions Relational expressions: –Expressions that compare operands –Sometimes called conditions –Evaluated to yield a result –Typically.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CP — Concurrent Programming 6. Liveness and Guarded Methods Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Information and Computer Sciences University of Hawaii, Manoa
Computer Science II Exam 1 Review.
Java Programming Language
slides created by Ethan Apter and Marty Stepp
Presentation transcript:

12. Common Errors, a few Puzzles

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Overview  Common errors … —Typical programming traps  A few Java puzzles... —The darker side of Java Sources  Cay Horstmann, Computing Concepts with Java Essentials, Wiley, 1998  The Java Report, April 1999

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.3 Trap 1 What does this print? 25.0 Don’t assume that floating point numbers are exact representations of mathematical values! double f = 2e ; double g = 2e ; println(100*(f-g)); double f = 2e ; double g = 2e ; println(100*(f-g));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.4 static void test(String name, boolean bool) { println(name + ": " + (bool?"true":"false")); } static void test(String name, boolean bool) { println(name + ": " + (bool?"true":"false")); } Trap 2 When are two Strings equal? == tests object identity; equals() tests object equality String s1 = new String("This is a string"); String s2 = new String("This is a string"); test("String==", s1 == s2); test("String.equals", s1.equals(s2)); String s1 = new String("This is a string"); String s2 = new String("This is a string"); test("String==", s1 == s2); test("String.equals", s1.equals(s2)); String==: false String.equals: true String==: false String.equals: true

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.5 Trap 3 When are two Objects equal? object==: false object.equals: false object==: false object.equals: false The default implementation of equals() is ==, and should normally be overwritten Object x = new Object(); Object y = new Object(); test("object==", x == y); test("object.equals", x.equals(y)); Object x = new Object(); Object y = new Object(); test("object==", x == y); test("object.equals", x.equals(y));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.6 Trap 4 When are two Strings equal? String==: true String.equals: true String==: true String.equals: true Literal strings with the same content refer to the same object! Always use equals() or compareTo() to compare strings. String s3 = "This is a string"; String s4 = "This is a string"; test("String==", s3 == s4); test("String.equals", s3.equals(s4)); String s3 = "This is a string"; String s4 = "This is a string"; test("String==", s3 == s4); test("String.equals", s3.equals(s4));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.7 Trap 5 Is “now” really before “later”? see you now Date later = new Date(now.getTime()); Explicitly create a clone if you need one: Calendar now = Calendar.getInstance(); Calendar later = now; later.set(Calendar.HOUR_OF_DAY, 1 + now.get(Calendar.HOUR_OF_DAY)); if (now.before(later)) { println("see you later"); } else { println("see you now"); } Calendar now = Calendar.getInstance(); Calendar later = now; later.set(Calendar.HOUR_OF_DAY, 1 + now.get(Calendar.HOUR_OF_DAY)); if (now.before(later)) { println("see you later"); } else { println("see you now"); }

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.8 Trap 6  nothing  0 is even 1 is negative  nothing  0 is even 1 is negative static void checkEven(int n) { boolean result = true; if (n>=0) if ((n%2) == 0) println(n + " is even"); else println(n + " is negative"); } static void checkEven(int n) { boolean result = true; if (n>=0) if ((n%2) == 0) println(n + " is even"); else println(n + " is negative"); } What is printed when we run these checks? checkEven(-1); checkEven(0); checkEven(1); checkEven(-1); checkEven(0); checkEven(1); Always use braces to group nested if { } else { } statements! if (n>=0) { if ((n%2) == 0) { println(n + " is even"); } else { println(n + " is negative"); } if (n>=0) { if ((n%2) == 0) { println(n + " is even"); } else { println(n + " is negative"); }

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.9 Trap 7 The binomial coefficient is Is this a correct implementation? binomial(7,3) = 21  35 To avoid off-by-1 errors: 1. Count the iterations — do we always do k multiplications? (no) 2. Check boundary conditions — do we start with n/1 and finish with (n-k+1)/k? (no) Off-by-1 errors are among the most common mistakes in implementing algorithms. static int binomial(int n, int k) { int bc = 1; for (int i=1; i<k; i++) { bc = bc * (n+1-i) / i; } return bc; } static int binomial(int n, int k) { int bc = 1; for (int i=1; i<k; i++) { bc = bc * (n+1-i) / i; } return bc; }

© O. Nierstrasz P2 — Common Errors, a few Puzzles Trap 8 For which values does this function work correctly? brokenFactorial(0) = 1 brokenFactorial(5) = 120 brokenFactorial(-1) =... (doesn’t terminate) brokenFactorial(0) = 1 brokenFactorial(5) = 120 brokenFactorial(-1) =... (doesn’t terminate) Always use an inequality test to terminate a loop. static int brokenFactorial(int n) { int result=1; for (int i=0; i!=n; i++ ) { result = result*(i+1); } return result; } static int brokenFactorial(int n) { int result=1; for (int i=0; i!=n; i++ ) { result = result*(i+1); } return result; }

© O. Nierstrasz P2 — Common Errors, a few Puzzles Some other common errors Magic numbers  Never use magic numbers; declare constants instead. Forgetting to set a variable in some branch  If you have non-trivial control flow to set a variable, make sure it starts off with a reasonable default value. Underestimating size of data sets  Don’t write programs with arbitrary built-in limits (like line-length); they will break when you least expect it. Leaking encapsulation  Never return a private instance variable! (return a clone instead) Bugs are always matter of invalid assumptions not holding

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 1 A.p() Private methods are statically bound. A b = new B(); b.m(); A b = new B(); b.m(); class A { public void m() { this.p(); } private void p() { println("A.p()"); } } class B extends A { private void p() { println("B.p()"); } } class A { public void m() { this.p(); } private void p() { println("A.p()"); } } class B extends A { private void p() { println("B.p()"); } } Are private methods inherited? Which is called? A.p() or B.p()?

© O. Nierstrasz P2 — Common Errors, a few Puzzles Static and Dynamic Types Consider: The static type of variable a is A — i.e., the statically declared class to which it belongs. The static type never changes. The dynamic type of a is B — i.e., the class of the object currently bound to a. The dynamic type may change throughout the program. Now the dynamic type is also A! A a = new B(); a = new A();

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 2 (part I) m(A,A) m(A,B) m(B,A) m(B,B) m(A,A) m(A,B) m(B,A) m(B,B) The static type of arguments is always used to resolve overloaded method calls. class A { } class B extends A { } void m(A a1, A a2) { println("m(A,A)"); }; void m(A a1, B b1) { println("m(A,B)"); }; void m(B b1, A a1) { println("m(B,A)"); }; void m(B b1, B b2) { println("m(B,B)"); }; B b = new B(); A a = b; class A { } class B extends A { } void m(A a1, A a2) { println("m(A,A)"); }; void m(A a1, B b1) { println("m(A,B)"); }; void m(B b1, A a1) { println("m(B,A)"); }; void m(B b1, B b2) { println("m(B,B)"); }; B b = new B(); A a = b; How are overloaded method calls resolved? m(a, a); m(a, b); m(b, a); m(b, b); m(a, a); m(a, b); m(b, a); m(b, b); Which is considered: the static or dynamic argument type?

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 2 (part II) What happens if we comment out: Will the examples still compile? If so, which methods are called? m(a,a) won’t compile m(b,b) won’t compile Prints: m(A,A) m(B,A) m(B,B) m(A,A) m(B,A) m(B,B) m(A,A)? m(B,B)? m(A,B)? m(A,A)? m(B,B)? m(A,B)?

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 3 How do static and dynamic types interact? A.m(A) B.m(B) A.m(A) B.m(B) Static types determine which message is sent. Dynamic types determine which method is called. a.m(a); a.m(b); b.m(a); b.m(b); a.m(a); a.m(b); b.m(a); b.m(b); class A { void m(A a) { println("A.m(A)"); } } class B extends A { void m(B b) { println("B.m(B)"); } } B b = new B(); A a = b; class A { void m(A a) { println("A.m(A)"); } } class B extends A { void m(B b) { println("B.m(B)"); } } B b = new B(); A a = b; In which cases will B.m(B) be called?

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 4 (part I) C.i = 0 C.j = 0 C.k = 0 C.l = 0 C.i = 0 C.j = 0 C.k = 0 C.l = 0 First, default values are assigned... then constructors are evaluated. How do default values and constructors interact? class C { int i = 100, j = 100, k = init(), l = 0; C() { i = 0; k = 0; } int init() { j = 0; l = 100; return 100; } } class C { int i = 100, j = 100, k = init(), l = 0; C() { i = 0; k = 0; } int init() { j = 0; l = 100; return 100; } } What gets printed? 0 or 100? C c = new C(); println("C.i = " + c.i); println("C.j = " + c.j); println("C.k = " + c.k); println("C.l = " + c.l); C c = new C(); println("C.i = " + c.i); println("C.j = " + c.j); println("C.k = " + c.k); println("C.l = " + c.l);

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 4 (part II) B.i = 0 B.j = 0 B.i = 0 B.j = 0 First all super initialization is executed, then the subclass initialization abstract class A { int j = 100; A() { init(100); j = 200; } abstract void init(int value); } class B extends A { int i = 0, j = 0; B() { super(); } void init(int value) { i = value; } } abstract class A { int j = 100; A() { init(100); j = 200; } abstract void init(int value); } class B extends A { int i = 0, j = 0; B() { super(); } void init(int value) { i = value; } } B b = new B(); println("B.i = " + b.i); println("B.j = " + b.j); B b = new B(); println("B.i = " + b.i); println("B.j = " + b.j); What gets printed? 0, 100 or 200?

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 5 The finally clause always takes precedence! 3 3 Does try or finally return? class A { int m() { try { return 1; } catch (Exception err) { return 2; } finally { return 3; } } class A { int m() { try { return 1; } catch (Exception err) { return 2; } finally { return 3; } } Prints 1, 2, or 3? A a = new A(); println(a.m()); A a = new A(); println(a.m());

© O. Nierstrasz P2 — Common Errors, a few Puzzles What you should know!  When can you trust floating-point arithmetic?  To which “if” does an “else” belong in a nested if statement?  How can you avoid off-by-1 errors?  Why should you never use equality tests to terminate loops?  Are private methods inherited?  What are the static and dynamic types of variables?  How are they used to dispatch overloaded methods?

© O. Nierstrasz P2 — Common Errors, a few Puzzles Can you answer these questions?  When is method dispatching ambiguous?  Is it better to use default values or constructors to initialize variables?  If both a try clause and its finally clause throw an exception, which exception is really thrown?

© O. Nierstrasz P2 — Common Errors, a few Puzzles License > Attribution-ShareAlike 2.5 You are free: to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. Attribution-ShareAlike 2.5 You are free: to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above.