6.170 Recitation 2 - PowerPoint PPT Presentation

1 / 44
About This Presentation
Title:

6.170 Recitation 2

Description:

e.g. String, Object, ArrayList, List. A type is either a class or an interface ... e.g. in compareTo() earlier we should be sure to test for at least one input ... – PowerPoint PPT presentation

Number of Views:45
Avg rating:3.0/5.0
Slides: 45
Provided by: asfandya
Category:

less

Transcript and Presenter's Notes

Title: 6.170 Recitation 2


1
6.170 Recitation 2
  • Asfandyar Qureshi

2
Announcements
  • PS0, handed back today
  • PS1, due tonight
  • Questions?
  • PS2, out today
  • Recitation notes
  • Posted online after recitation
  • Start looking at Collections API

3
PS0 Arrays as Objects
  • In Java each array is an Object
  • Internally, java has different classes for each
    type of array int, String,
  • Array classes derive directly from
    java.lang.Object
  • they implement the java.lang.Cloneable and
    java.io.Seriliazable interfaces.
  • Arrays are special only at the syntactic level.

4
Example Curves
5
Subtyping
  • Type Hierarchies are integral to OOP
  • We want to
  • Treat similar types in the same way
  • When drawing, we want to abstract away the
    differences between a LineSegment and a Curve.
  • Extend more general types to more specialized
    ones (inheritance)
  • A straight line is just a special Curve
  • Reuse existing, tested code
  • Saves work, more maintainable

6
Subclasses
  • In Java a class can extend another class
  • By default, all classes extend java.lang.Object
  • What happens when we extend a class?
  • Inherit all its non-private methods and fields
  • Same as if they were part of our class
  • Overriding old non-private methods
  • If we provide our own definitions
  • Depends on method signatures.
  • Adding methods and fields

7
Curve Class Hierarchy
Add support for enclosed area
Cant have arbitrary length
8
Class Curve
  • class Curve
  • Point startPt
  • Point endPt
  • double length
  • Curve(Point s, Point e, double len)
  • ...
  • Point getStartingPoint() ...
  • Point getEndingPoint() ...
  • double getLength() ...
  • Curve appendCurve (Curve c) ...

9
Subclassing Java Syntax
  • extends keyword
  • class LineSegment extends Curve
  • ...
  • Always a single superclass
  • not always true in other languages (e.g. C)

10
Subclassing Java Syntax
  • super keyword
  • class LineSegment extends Curve
  • LineSegment(Point start, Point end)
  • super(startPoint, startEnd, 0.0)
  • ...
  • Calling Superclass constructors
  • Optional by default super() called
  • Can only call one constructor
  • Must be first line of constructor body

11
Subclassing Java Syntax
  • super keyword
  • class LineSegment extends Curve
  • ...
  • double getLength()
  • double len super.getLength()
  • return startPt.distance(endPt)

Overridden method
  • Calling Superclass methods
  • No dynamic dispatch

12
Dynamic Dispatch
  • LineSegment seg
  • new LineSegment(new Point(0,0),
  • new Point(0,10))
  • Curve c seg
  • System.out.println(
  • (c.getLength() seg.getLength())
  • ? equal unequal))

13
Reference Types
  • Java is a strictly typed language
  • Unlike, say, Scheme
  • Every reference variable has a type
  • e.g. String, Object, ArrayList, List
  • A type is either a class or an interface
  • A reference of type T can only hold
  • null
  • a reference to an object of type T
  • a reference to an object with type X
  • only if X is a subclass of T

14
Runtime Types vs Static Types
  • Static reference type
  • The declared type of the variable, in the code
  • Java uses this to ensure your code makes sense,
    at compile time
  • Runtime type
  • The type of the Object
  • Java uses this to decide what code to invoke
  • A subclasss code always run for overridden
    method
  • Code invoked never depends on ref. type

15
Dynamic Dispatch Drawing
  • void drawAll(Curve curves,
  • Graphics output)
  • for (int i 0
  • i
  • i)
  • curvesi.draw(output)

Polymorphism
16
Downcasting References
  • What methods can we invoke on type T?
  • Java ensures that method is part of the
    definition of T or one of Ts superclasses
  • If not, then we get a compile time error
  • Sometimes, we can convince ourselves that a ref
    of type T will definitely contain a ref to an
    object of type X at runtime
  • How do we convince Java?
  • We might want to run a method defined in X

17
Casting
  • String string firehose
  • Object obj string
  • obj.toUpperCase() // compiler error
  • ((String)obj).toUpperCase() // okay
  • string obj // compiler error
  • string (String)obj // okay

18
More Useful Casting
  • void drawAll(List curves,
  • Graphics output)
  • Iterator iter curves.iterator()
  • while (iter.hasNext())
  • Curve c (Curve)iter.next()
  • c.draw(output)

19
Casting vs Coercion
  • Casting only results in a type check
  • Same as the instanceof Java operator
  • No new objects created
  • Unless type check fails and Exception generated
  • Confusing primitive type casting can change the
    value
  • int x (int) (0.5) ? x 0

20
Class Cast Exceptions
  • Java still checks to make sure all reference
    assignments obey type rules.
  • Invariant variable of type T can only hold
  • null
  • a reference to an object of type T
  • a reference to an object with type X
  • only if X is a subclass of T
  • If we try to break this invariant by explicit
    casting ? ClassCastException
  • ArrayList list (ArrayList)string

21
Interfaces
  • Well discuss these in detail later in the
    course, but since youll see them in the psets
    and java API
  • A Java interface is a partial specification
  • No code, just method signatures
  • No method implementations
  • No field definitions

22
Java Syntax
  • implements keyword
  • class Card implements Comparable
  • ...
  • public int compareTo(Object o)
  • ...
  • ...
  • Can implement multiple interfaces!

23
Abstraction by Specification
  • Procedural specification abstracts away the
    implementation from the caller
  • If the caller obeys the preconditions, the callee
    guarantees that the implementation will obey the
    postconditions
  • Ideally never need to read anyone elses code!

24
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

25
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

26
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

27
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

28
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

29
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • effects
  • If obj is an instance of CardValue, this returns
    an integer greater than, equal to, or less than
    zero if obj is greater than, equal to, or less
    than this, respectively.
  • If obj is null, this throws a NullPointerException
  • Otherwise, this throws a ClassCastException

30
Specifications Strength
  • We might want to replace one method with another
    throughout a program
  • This is only guaranteed to work if new methods
    spec is stronger or equal to old spec
  • How do we compare?
  • Spec X is no weaker than spec Y, if
  • Any implementation of X would also obey Y
  • Xs preconditions cannot require more than Ys
  • Xs postconditions cannot promise less than Ys

31
Specifications Strength
  • Intuitively
  • A stronger spec is harder to satisfy
  • As set of implementations a subset of Bs set
  • A stronger precondition has more constraints and
    makes a spec weaker.
  • Strongest true, always satisfied
  • Weakest false, never satisfied
  • Stronger postconditions make more promises, and
    make the spec stronger

32
Non-deterministic Specs
  • If the postconditions are weak enough to allow
    different implementations to give different
    outputs given the same input, then the spec is
    non-deterministic.
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

Non-deterministic?
33
Only a Partial Ordering
  • Not all specifications, can be compared.
  • Key Spec X is no weaker than spec Y, if
  • Any implementation of X would also obey Y
  • This does not imply that spec X is stronger if
    some implementation of X would not obey Y.

34
Procedural Specifications
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

35
Implementing Specifications
  • Efficiency is not a part of our specs
  • Focus on getting the right semantics out of the
    implementation.
  • public int compareTo(Object o)
  • if (o null)
  • throw new NullPointerException()
  • return VALUES.indexOf(this) - VALUES.indexOf(
    (CardValue) o)

36
Unit Testing
  • Test each module (class) on its own
  • Build test drivers
  • Make sure it (seems to) obey its specs then move
    on to next module
  • Finally test the system as a whole
  • JUnit
  • Lets you test single Java classes
  • Questions?

37
Test Driven Development
  • First, write specifications
  • Second, write test cases
  • Third, implement specifications

38
Testing Specifications
  • Were all human ? our code has bugs
  • If we ran every possible input combination and
    compared the results with our specs we would find
    all our bugs
  • Not a good idea!
  • Intelligent testing can help us find most bugs
    with relatively few test cases.
  • For now Black Box Testing

39
Black Box Testing
  • Ignore the implementation.
  • Test each class/procedure based only on its
    specifications.
  • How do we choose inputs?
  • No hard rules, we only have heuristics
  • We want coverage
  • Does not mean a lot of test cases
  • e.g. testing a million integers for abs() is a
    bad idea

40
Choosing Test Cases
  • Multiple paths through the spec
  • Sometimes the spec will be written in a
    case-by-case way, implying multiple classes of
    inputs, each of which have to be tested for.
  • e.g. in compareTo() earlier we should be sure to
    test for at least one input less than, one input
    greater than, and one input equal to the object.

41
Choosing Test Cases
  • Boundary Conditions
  • Test on values on the edges of the input space.
  • e.g. Integer.MAX_VALUE, Integer.MIN_VALUE, the
    empty list.
  • Also, test boundaries between multiple classes of
    inputs
  • For compareTo(), test an object almost equal to,
    but less than and an object almost equal to, but
    greater than, etc.

42
Choosing Test Cases
  • Aliasing
  • Two different arguments refer to the same object.
  • Typical Values
  • Of course, you want to test some typical input
    values as well

43
Exposing Bugs Example
  • public class CardValue
  • public int compareTo (Object obj)
  • requires true
  • modifies nil
  • returns an integer greater than, equal to, or
    less than zero if obj is greater than, equal to,
    or less than this, respectively.
  • exception NullPointerException, if obj is null
  • exception ClassCastException, if obj not a
    CardValue

44
Exposing Bugs Example
  • public int compareTo(Object o)
  • return o.hashCode()
  • this.hashCode()
  • public int compareTo(Object o)
  • return VALUES.indexOf(this) - VALUES.indexOf(o)
Write a Comment
User Comments (0)
About PowerShow.com