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.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

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.
8. Static Single Assignment Form Marcus Denker. © Marcus Denker SSA Roadmap  Static Single Assignment Form (SSA)  Converting to SSA Form  Examples.
Air Force Institute of Technology Electrical and Computer Engineering
7. Optimization Prof. O. Nierstrasz Lecture notes by Marcus Denker.
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
Discussion1 Quiz. Q1 Which of the following are invalid Java identifiers (variable names)? a) if b) n4m3 c) Java d) e) DEFAULT_VALUE f) bad-choice.
Q and A for Chapter 6 CS 104 Victor Norman. Return values Q: A function definition that returns a value (i.e., a non-void function) must have at least.
10. Applications of Logic Programming. © O. Nierstrasz PS — Applications of Logic Programming 10.2 Roadmap 1. Search problems —SEND + MORE = MONEY 2.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
Win8 on Intel Programming Course Win8 and Intel Paul Guermonprez Intel Software
ESE Einführung in Software Engineering 6. Modeling Objects and Classes Prof. O. Nierstrasz.
ESE Einführung in Software Engineering 7. Modeling Behaviour Prof. O. Nierstrasz.
Introduction to Software Engineering 7. Modeling Behaviour.
CP — Concurrent Programming 8. Liveness and Asynchrony Prof. O. Nierstrasz Wintersemester 2005 / 2006.
OORPT Object-Oriented Reengineering Patterns and Techniques 7. Problem Detection Prof. O. Nierstrasz.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
10. Petri Nets Prof. O. Nierstrasz. Roadmap  Definition: —places, transitions, inputs, outputs —firing enabled transitions  Modelling: —concurrency.
Object-Oriented Reengineering Patterns and Techniques Prof. O. Nierstrasz Prof. S. Ducasse T.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap  Syntax and Semantics  Semantics of Expressions 
6. Introduction to the Lambda Calculus. © O. Nierstrasz PS — Introduction to the Lambda Calculus 6.2 Roadmap  What is Computability? — Church’s Thesis.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
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.
The Software Composition Group Prof. O. Nierstrasz
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.
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.
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.
13. A bit of Smalltalk. © Oscar Nierstrasz 2 Roadmap  The origins of Smalltalk  What is Smalltalk?  Syntax in a nutshell  Seaside — web development.
CP — Concurrent Programming 12. Petri Nets Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
3. A Testing Framework. © O. Nierstrasz P2 — A Testing Framework 3.2 A Testing Framework Overview  What is a framework?  JUnit — a simple testing framework.
© 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.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
7. Liveness and Asynchrony Prof. O. Nierstrasz. Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
© S. Demeyer, S. Ducasse, O. Nierstrasz Chapter.1 MakeMoney Corp. C*O of MakeMoney Corp. Our Vision  We invest in software  We do not know software 
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:  …
SWOT Analysis Strengths Weaknesses SWOT Opportunities Threats.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Win8 on Intel Programming Course The challenge Paul Guermonprez Intel Software
© Copyright Showeet.com I NSERT YOUR TITLE HERE. © Copyright Showeet.com Insert Your Title Here 2 Master text styles –Second level Third level –Fourth.
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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
Numerical Methods Part: Simpson Rule For Integration.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Numerical Methods Continuous Fourier Series Part: Continuous Fourier Series
Numerical Methods Part: False-Position Method of Solving a Nonlinear Equation
Win8 on Intel Programming Course Paul Guermonprez Intel Software
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Design of Everyday Things Part 2: Useful Designs? Lecture /slide deck produced by Saul Greenberg, University of Calgary, Canada Images from:
CP — Concurrent Programming 6. Liveness and Guarded Methods Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
Images of pesticides By: Leslie London, University of Cape Town This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5.
Digital Ecosystems supporting growth and SMEs 1st cluster meeting Results and commitments 1st cluster meeting Results and commitments.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Numerical Methods Part: False-Position Method of Solving a Nonlinear Equation
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.
FOTW Worksheet Slides Christopher Penn, Financial Aid Podcast Student Loan Network.
Presentation transcript:

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 Concepts with Java Essentials, Wiley, 1998  The Java Report, April 1999

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.3 Roadmap  Common errors … —Typical programming traps  A few Java puzzles... —The darker side of Java

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.4 Roadmap  Common errors … —Typical programming traps  A few Java puzzles... —The darker side of Java

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.5 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));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.6 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==: false String.equals: true

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.7 Trap 3 When are two Objects equal? 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));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.8 Trap 4 When are two Strings equal? 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));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.9 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"); }

© O. Nierstrasz P2 — Common Errors, a few Puzzles Trap 6  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"); } What is printed when we run these checks? 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"); }

© O. Nierstrasz P2 — Common Errors, a few Puzzles 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; }

© 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) 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; }

© 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 Roadmap  Common errors … —Typical programming traps  A few Java puzzles... —The darker side of Java

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 1 A.p() Private methods are statically bound. 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()"); } } 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) 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; How are overloaded method calls resolved? 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,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) 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); 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 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; } } 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);

© O. Nierstrasz P2 — Common Errors, a few Puzzles Puzzle 4 (part II) 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; } } 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 Does try or finally return? 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());

© 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.