Effective Java, Chapter 4: Classes and Interfaces Last Updated: Fall 2011.

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Mutability SWE 332 Fall 2011 Paul Ammann. SWE 3322 Data Abstraction Operation Categories Creators Create objects of a data abstraction Producers Create.
Effective Java, Chapter 3: Methods Common to All Objects.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 1 Object-Oriented.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 10 Classes Continued
From Theory to Practice 1 OOP Overview Reminder – some OOD principles from previous lessons: –Class Inheritance vs. Object Composition –Program.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Classes and Interfaces 1 How can we create deadlock condition on our servlet? Ans: one simple way to call doPost() method inside doGet() and doGet()method.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Java Implementation: Part 3 Software Construction Lecture 8.
Effective Java: Generics Last Updated: Spring 2009.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
Best Practices. Contents Bad Practices Good Practices.
CSSE501 Object-Oriented Development. Some OO Design Principles  Majority principles here come from: Design Principles in Java, Bob Tarr.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Implications of Inheritance COMP206, Geoff Holmes and Bernhard Pfahringer.
More Implications of Inheritance COMP204, Bernhard Pfahringer.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Static Attributes and Inheritance  static attributes behave the same as non-static attributes in inheritance  public and protected static attributes.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 11 Object-Oriented.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Mutability SWE 332 Fall 2015 Paul Ammann. SWE 3322 Data Abstraction Operation Categories Creators Create objects of a data abstraction Producers Create.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Data Abstraction: The Walls
Inheritance ITI1121 Nour El Kadri.
Inheritance and Polymorphism
Chapter 11 Object-Oriented Design
Software Engineering Fall 2005
CSE 331 Subtyping slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Functional Programming with Java
Effective Java: Classes and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Review for Midterm 3.
Chapter 5 Classes.
Basic Mutability Paul Ammann.
Presentation transcript:

Effective Java, Chapter 4: Classes and Interfaces Last Updated: Fall 2011

Classes and Interfaces 2 Agenda Material From Joshua Bloch Effective Java: Programming Language Guide Cover Items 14 through 20 “Classes and Interfaces” Chapter Was Items 12 through 18 in 1 st Edition Moral: Inheritance requires careful programming

Classes and Interfaces 3 Item 13: Minimize Accessibility of Classes and Members Standard advice for information hiding/encapsulation Decouples modules Allows isolated development and maintenance Java has an access control mechanism to accomplish this goal

Classes and Interfaces 4 Make Each Class or Member as Inaccessible as Possible Standard list of accessibility levels private package-private (aka package friendly) protected public Huge difference between 2 nd and 3 rd package-private: part of implementation protected: part of public API

Classes and Interfaces 5 Exception: Exposing Constants Public constants must contain either primitive values or references to immutable objects Wrong – Potential Security Hole: public static final Type[] VALUES = {…}; Problem: VALUES is final; entries in VALUES are not!

Classes and Interfaces 6 Exposing Constants - Solutions Correct: private static final Type[] PRIVATE_VALUES = {…}; public static final List VALUES = Collections.unmodifiableList(Arrays.asList (PRIVATE_VALUES)); Also Correct: private static final Type[] PRIVATE_VALUES = {…}; public static final Type[] values() { return (Type[]) PRIVATE_VALUES.clone(); }

Classes and Interfaces 7 Item 14: In Public Classes, Use Accessors, Not Public Fields Avoid code such as: class Point { public double x; public double y; } No possibility of encapsulation Also, public mutable fields are not thread safe Use get/set methods instead: public double getX() { return x; } public void setX(double x) { this.x = x} Advice holds for immutable fields as well Limits possible ways for class to evolve

Classes and Interfaces 8 Example: Questionable Use of Immutable Public Fields public final class Time { private static final int HOURS_PER_DAY = 24; private static final int MINUTES_PER_HOUR = 60; public final int hour; // Not possible to change rep for class public final int minute; // But we can check invariants, since fields are final public Time ( int hour, int minute ) { if (hour = HOURS_PER_DAY) throw new IllegalArgumentException(“Hour: “ + hour); if (minute = MINUTES_PER_HOUR) throw new IllegalArgumentException(“Minute: “ + minute); this.hour = hour; this.minute = minute; } // Remainder omitted }

Classes and Interfaces 9 Item 15: Minimize Mutability Reasons to make a class immutable: Easier to design Easier to implement Easier to use Less prone to error More secure Easier to share Thread safe

Classes and Interfaces 10 Example: Class Complex public final class Complex { private final double re; private final double im; public Complex (double re, double im) { this.re = re; this.im = im;} // Accessors with no corresponding mutators public double realPart() { return re; } public double imaginaryPart() { return im; } // Note standard “producer” pattern public Complex add (Complex c) { return new Complex (re + c.re, im + c.im); } // similar producers for subtract, multiply, divide // implementations of equals() and hashCode() use Double class }

Classes and Interfaces 11 5 Rules to Make a Class Immutable Don’t provide any mutators Ensure that no methods can be overridden (more detail…) Make all fields final (more detail…) Make all fields private Ensure exclusive access to any mutable components (more detail…)

Classes and Interfaces 12 Rule 2: No Overridden Methods Prevents careless or malicious subclasses from compromising the immutable behavior of the class How to implement Make class final (easiest) Make methods final (allows subclassing) Make all constructors private or package- private Requires static factories, which are better anyway

Classes and Interfaces 13 Example: Static Factory for Complex Class // Note that this version is no longer a final class public class Complex { private final double re; private final double im; // private constructor shuts off subclassing // package friendly constructor would allow local subclassing private Complex (double re, double im) { this.re = re; this.im = im; } // Static factory – could have lots of possible implementations public static Complex valueOf (double re, double im) { return new Complex (re, im); } // Remainder as before }

Classes and Interfaces 14 Rule 3: Make All Fields Final Clearly expresses intent System enforcement of immutability Issues with object instantiation and thread access Sometimes, making fields final is too strong Lazy initialization may be preferable

Classes and Interfaces 15 Rule 5: Exclusive Access to Mutable Components Never initialize a mutable field to a client provided reference Never return a reference to a mutable field Make defensive copies Note what this says about mutability Performance advantage often illusory!

Classes and Interfaces 16 Typical Transformation Typical method in mutable class Foo: public void foo(T1 t1, T2, t2, …) {modify “this”} Immutable version of Foo: public Foo foo(T1 t1, T2, t2, …) { Foo f = … … return f; } Functional programming vs. procedural programming. See Poly example

Classes and Interfaces 17 Disadvantage: Performance Typical approach: Provide immutable class Provide mutable companion class for situations where performance is an issue Clients choose on performance needs Example in Java Library: String (Immutable) StringBuilder (Companion Mutable Class) StringBuffer (Deprecated Companion Mutable Class) Static factories can cache frequently used items

Classes and Interfaces 18 Item 16: Favor Composition over Inheritance Issue ONLY for implementation inheritance Interface inheritance does NOT have these problems Interface inheritance is better for lots of reasons… Inheritance breaks encapsulation! Difficult to evolve superclass without breaking subclasses Difficult for superclass to maintain invariants in face of malicious/careless subclass

Classes and Interfaces 19 Example: Broken Subtype // This is very common, but broken public class InstrumentedHashSet extends HashSet private int addCount = 0; // add() calls public InstrumentedHashSet() {} public InstrumentedHashSet(Collection c) { super(c); } public boolean add(E o) { addCount++; return super.add(o); } public boolean addAll(Collection c) { addCount += c.size(); return super.addAll(c); } // accessor method to get the count public int addCount() { return addCount; } }

Classes and Interfaces 20 Broken Example, continued So, what’s the problem? InstrumentedHashSet s = new InstrumentedHashSet (); s.addAll(Arrays.asList(“Snap”, “Crackle”, “Pop”)); What does addCount() return? 3? 6? Internally, HashSet addAll() is implemented on top of add(), which is overridden. Note that this is an implementation detail, so we can’t get it right in InstrumentedHashSet

Classes and Interfaces 21 Source of Difficulty: Overridden Methods Overriding methods can be tricky May break the superclass invariant Overridden method does not maintain invariant May break subclass invariant New methods may be added to superclass What if new method matches subclass method? Also, recall problems with equals() and hashCode()

Classes and Interfaces 22 Composition Fortunately, composition solves all of these problems – even though it makes the programmer work harder // Inheritance public Class Foo extends Fie {…} // Composition public class Foo { private Fie f = …; // Note: forwarded methods... }

Classes and Interfaces 23 Revisiting the Example // Note that an InstrumentedSet IS-A Set public class InstrumentedSet implements Set { private final Set s; private int addCount = 0; public InstrumentedSet (Set s) { this.s = s} public boolean add(E o) { addCount++; return s.add(o); } public boolean addAll (Collection c) { addCount += c.size(); return s.addAll(c); } // forwarded methods from Set interface }

Classes and Interfaces 24 A More Elegant Version // Wrapper class – uses composition in place of inheritance public class InstrumentedSet extends ForwardingSet { private int addCount = 0; public InstrumentedSet (Set s) { super(s); public boolean add(E e) { addCount++; return super.add(e); public boolean addAll(Collection c) { addCount += c.size(); return super.add(c); } public int getAddCount() { return addCount; } } // Reusable Forwarding Class public class ForwardingSet implements Set { private final Set s; public ForwardingSet (Set s) { this.s = s;} public void clear() { s.clear();} public boolean contains(E o) { return s.contains(o);} // plus forwards of all the other Set methods }

Classes and Interfaces 25 This is Cool! Consider temporarily instrumenting a Set Note that Set is an interface static void f(Set s) { InstrumentedSet myS = new InstrumentedSet (s); // use myS instead of s // all changes are reflected in s! }

Classes and Interfaces 26 A Variation That Doesn’t Work // Note that this uses the “basic” version, // but extending a “ForwardingCollection” doesn’t // work either, for the same reason public class InstrumentedCollection implements Collection { private final Collection c; private int addCount = 0; public InstrumentedCollection (Collection c) { this.c = c} public boolean add(E o) {…} public boolean addAll (Collection c) {…} // forwarded methods from Collection interface public boolean equals(Object o) { return c.equals(o); } // Now, we’re dead! }

Classes and Interfaces 27 This is no longer Cool! Consider temporarily instrumenting a Set Note: Set is a subtype of Collection Set s = new HashSet (); InstrumentedCollection t = new InstrumentedCollection (s); s.equals(t) // t is not a Set, so false t.equals(s) // t.c == s, so true Issue: Set has a uniform equals() contract Collection does not (and should not…) Keep this in mind when using this model.

Classes and Interfaces 28 Item 17: Design and Document for Inheritance Or else prohibit it. First, document effects of overriding any method Document “self use”, as in InstrumentedHashSet example This is “implementation detail”, but unavoidable, since subclass “sees” implementation. Inheritance violates encapsulation!

Classes and Interfaces 29 Efficiency May Require Hooks protected methods may be required for efficient subclasses. Example: protected removeRange() method in AbstractList Not of interest to List clients Only of interest to implementers of AbstractList – provides fast clear() operation Alternative – O(n^2) clear() operation

Classes and Interfaces 30 Inheritance is Forever A commitment to allow inheritance is part of public API If you provide a poor interface, you (and all of the subclasses) are stuck with it. You cannot change the interface in subsequent releases. TEST for inheritance How? By writing subclasses

Classes and Interfaces 31 Constructors Must Not Invoke Overridable Methods // Problem – constructor invokes overridden m() public class Super { public Super() { m();} public void m() {…}; } public class Sub extends Super { private final Date date; public Sub() {date = new Date();} public void m() { // access date variable} }

Classes and Interfaces 32 What Is the Problem? Consider the code Sub s = new Sub(); The first thing that happens in Sub() constructor is a call to constructor in Super() The call to m() in Super() is overridden But date variable is not yet initialized! Further, initialization in Super m() never happens! Yuk!

Classes and Interfaces 33 Inheritance and Cloneable, Serializable Since clone() and readObject() behave a lot like constructors, these methods cannot invoke overridable methods either. Problem – access to uninitialized state For Serializable readResolve(), writeReplace() must be protected, not private Or they will be ignored in subclass.

Classes and Interfaces 34 Bottom Line Be sure you want inheritance, and design for it, or Prohibit inheritance Make class final, or Make constructors private (or package- private)

Classes and Interfaces 35 Item 18: Prefer Interfaces to Abstract Classes Existing classes can be easily retrofitted to implement a new interface Same is not true for abstract classes due to single inheritance model in Java Interfaces are ideal for “mixins” Example: Comparable interface Interfaces aren’t required to form a hierarchy Some things aren’t hierarchical

Classes and Interfaces 36 More Interfaces Wrapper idiom a potent combination with interfaces See ISet example Possible to provide skeletal implementations for interfaces java.util does this with AbstractCollection, AbstractSet, AbstractList, and AbstractMap

Classes and Interfaces 37 Example for AbstractList // Concrete implementation built on abstract skeleton static List intArrayAsList(final int[] a) { if (a == null) throw new NPE(…); // Note anonymous class return new AbstractList() { public Object get(int i) { return new Integer(a[i]); } public int size() { return a.length; } public Object set(int i, Object o) { int oldVal = a[i]; a[i] = ((Integer) o).intValue(); return new Integer(oldVal); } }; }

Classes and Interfaces 38 This Implementation Does a Lot! The List interface includes many methods. Only 3 of them are explicitly provided here. This is an “anonymous class” example Certain methods are overridden Note that it is possible to add a method to an abstract class in a new release It is not possible to add a method to an interface

Classes and Interfaces 39 Item 19: Use Interfaces Only to Define Types Example that fails the test: “Constant” interface – avoid public interface PhysicalConstants { static final double AVOGADROS = } Why is this bad? Users of a class that implements this interface don’t care about these constants! Think about the client, not the implementor

Classes and Interfaces 40 Alternative to Constants in Interfaces Constant utility class public class PhysicalConstants { public static final double AVOGADROS =... }

Classes and Interfaces 41 Item 20: Prefer Class Hierarchies to Tagged Classes //Tagged Class – vastly inferior to a class hierarchy class Figure { enum Shape { RECTANGLE, CIRCLE }; final Shape shape; // Tag field double length; double width; // for RECTANGLE double radius; // for CIRCLE Figure (double length, double width) {…} // RECTANGLE Figure (double radius) {…} // CIRCLE double area() { switch (shape) { // Gag! Roll-your-own dispatching! case RECTANGLE: return length*width; case CIRCLE: return Math.PI*(radius * radius); default: throw new AssertionError(); }

Classes and Interfaces 42 Item 20 Continued: A much better solution //Class hierarchy replacement for a tagged class abstract class Figure { // Note: NOT instantiable! abstract double area(); } class Circle extends Figure { final double radius; Circle(double rad) { radius = rad; } double area() { return Math.PI * (radius * radius); } class Rectangle extends Figure { final double length; final double width; Rectangle (double len; double wid) { length = len; width = wid; } double area() { return length * width; }

Classes and Interfaces 43 Item 21: Use Function Objects to Represent Strategies In Java, you can’t pass functions directly Only Objects can be arguments So, pass Objects to pass functions // Strategy interface public interface Comparator { public int compare ( T t1, T t2); } // Question: Is compare() consistent with equals() Class StringLengthComparator implements Comparator { private StringLengthComparator() {} public static final StringLengthComparator INSTANCE = new StringLengthComparator(); public int compare (String s1, String s2) { return s1.length – s2.length; }

Classes and Interfaces 44 Item 22: Favor Static Member Classes Over Nonstatic Nested classes Defined within another class Four flavors Static member class Nonstatic member class (inner) Anonymous class (inner) Local class (inner)

Classes and Interfaces 45 Static vs NonStatic Static requires no connection to enclosing instance. Nonstatic always associated with enclosing instance Possible performance issue Possible desire to create by itself Hence recommendation to favor static See Iterator implementations

Classes and Interfaces 46 Local classes Declared anywhere a local variable may be declared Same scoping rules Have names like member classes May be static or nonstatic (depending on whether context is static or nonstatic)