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
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

1 Todays Objectives Announcements Homework #1 is due next week Return Quiz 1 – answers are posted on the Yahoo discussion page site Basic Java Programming.
 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).
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
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.
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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
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 
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
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.
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.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
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:...
Transformation of Java Card into Diet Java Semester Project Presentation Erich Laube.
© 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:  …
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
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.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
 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.
Written by: Dr. JJ Shepherd
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Interfaces.
null, true, and false are also reserved.
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 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 12.4 Trap 1 What does this print? 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.5 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? 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));

© O. Nierstrasz P2 — Common Errors, a few Puzzles 12.6 Trap 3 When are two Objects equal? 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.7 Trap 4 When are two Strings equal? 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.8 Trap 5 Is “now” really before “later”? 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.9 Trap 6 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);

© O. Nierstrasz P2 — Common Errors, a few Puzzles Trap 7 The binomial coefficient is Is this a correct implementation? 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? 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 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) 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)? 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); 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) 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) 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 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.