Effective Java: Creating and Destroying Objects Last Updated: Fall 2012.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
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.
From Theory to Practice 2 OOP Overview Performance issues: –Preparing classes for inheritance –Memory management and release of obsolete object.
Generic programming in Java
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Advanced Programming Rabie A. Ramadan vPro/ Lecture 1.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Effective Java: Generics Last Updated: Spring 2009.
Utilities (Part 2) Implementing static features 1.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Programming in Java CSCI-2220 Object Oriented Programming.
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Introduction to Generics
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Effective Java, Chapter 7: Methods Items Last modified Fall 2012 Paul Ammann.
Everything is an object (CH-2) Manipulating Objects with References. Manipulating Objects with References. String s; String s = “IS2550” String s = new.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Object-Oriented Programming Chapter Chapter
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1  lecture slides online
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'
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Singleton Pattern Presented By:- Navaneet Kumar ise
Mixing Static and Non-static Singleton 1. Singleton Pattern 2  “There can be only one.”  Connor MacLeod, Highlander.
The Singleton Pattern (Creational)
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Overview of Creational Patterns ©SoftMoore ConsultingSlide 1.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Factory Design Pattern (contn’d). Static Factory Pattern public final class ComplexNumber { // Static factory method returns an object of this class.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Topic: Classes and Objects
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
Effective Java Source: Effective Java, Jason Arnold
Static data members Constructors and Destructors
Effective Java: Creating and Destroying Objects
Object Based Programming
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Implementing Non-Static Features
Generic programming in Java
Effective Java: 3rd Edition Creating and Destroying Objects
Effective Java: Creating and Destroying Objects
Chapter 5 Classes.
Presentation transcript:

Effective Java: Creating and Destroying Objects Last Updated: Fall 2012

Creating and Destroying Objects Agenda Material From Joshua Bloch Effective Java: Programming Language Guide Cover Items 1-7 Bottom Line: Understand Java Construction First C++ Creation/Destruction More Complex

Creating and Destroying Objects Item 1: Consider Static Factory Methods Instead of Constructors Constructor Calls vs Static Factory Method Alternate way to get an object Sometimes replaces constructors Sometimes augments constructors // Simple example from Boolean class public static Boolean valueOf (boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; }

Creating and Destroying Objects Item 1: Advantages Unlike constructors, static factory methods Can have meaningful names Need not create new instances Can return any subtype of return type Reduces client dependency on specific class Can reduce verbosity of creating parameterized type instances

Creating and Destroying Objects Advantage 1: Meaningful Names Consider the constructor/factory pair: // Constructs a randomly generated positive BigInteger // that is probably prime, with the specified bitLength // BigInteger (int bitLength, int certainty, Random rnd) vs. // Returns a positive BigInteger that is probably prime, // with the specified bitLength. // BigInteger.probablePrime (int bitLength, Random rnd) Note: The extra constructor argument avoids a clash with another constructor Unique parameter lists on constructors are really restrictive

Creating and Destroying Objects Advantage 2: Not Required To Create New Object Instance-controlled classes can be useful Can avoid creating unnecessary duplicate objects Boolean.valueOf(boolean) is an example Can guarantee a “singleton” or “noninstatiable” object Can allow for very fast “equals” test

Creating and Destroying Objects Advantage 3: Can Return Subtype of Return Type Consider the java.util.Collections classjava.util.Collections 32 Convenience implementations of Collection interfaces All are static factory methods Interface return type vs. actual classes Static factory methods can hide multiple implementations java.util.EnumSet has two implementations Future release could easily change this Clients neither know nor care about actual type Reduce client dependencies!

Creating and Destroying Objects Service Provider Factory Example // Service interface public interface Service {... // Service-specific methods go here } // Service provider interface public interface Provider { public Service getService(); } // Noninstantiable class for service registration and access public class Services { private Services() { } // Prevents instantiation (Item 4) private static final Map providers = new ConcurrentHashMap (); // static Provider registration API – services may be added long after factory defined public static void registerProvider(String name, Provider p){ providers.put(name, p); } // static Service factory API public static Service getInstance(String name) { Provider p = providers.get(name); if (p == null) throw new IllegalArgumentException("No provider named: " + name); return p.newService(); } }

Creating and Destroying Objects Advantage 4: Reduce Verbosity of Parameterized Type Instances // Parameterized type instances Map > m = new HashMap >(); vs. // Static factory alternative public static HashMap newInstance() { return new HashMap (); } // Now, client code looks like this // Compiler does type inference! Map > m = HashMap.newInstance();

Creating and Destroying Objects Item 1: Disadvantages of Static Factory Methods Subclassing impossible without constructors Arguably a blessing in disguise Naming conventions necessary valueOf – effectively a type converter (also just of ) getInstance – return instance described by parameters newInstance – like getInstance, but guarantees distinct object getType – like getInstance, but converts type newType – like newInstance, but converts type

Creating and Destroying Objects Item 2: Consider a Builder vs. Many Constructor Parameters Static factories and constructors don’t scale well to large numbers of optional parameters Bloch’s examples: NutritionFactsTelescoping.java NutritionFactsBeans.java NutritionFactsBuilder.java The last version enjoys significant advantages

Creating and Destroying Objects Item 3: Enforce Singleton Property A Singleton is a class that’s instantiated exactly once Note: singletons are hard to mock in unit testing Two approaches before Enums: Public static member (a constant, of course) Public static factory method Enum singleton is now preferred Lots of subtle advantages: security, serialization, etc.

Creating and Destroying Objects Item 3: Code Example // Option 1: public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...} } // Option 2: static factory method public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE; } } // Option 3: Enum type – now the preferred approach public enum Elvis { INSTANCE;... }

Creating and Destroying Objects Item 4: Enforce Noninstantiability With a Private Constructor Some classes just group static methods and/or fields Makes no sense to instantiate such a class Trying to enforce noninstantiability by making class abstract doesn’t work Subclassing is possible Clients are led to believe subclassing makes sense However, a private constructor does the job

Creating and Destroying Objects Item 4: Code Example // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); }... // Remainder of class omitted } // Note that no subclassing is possible (constructor chaining...) // Note that client can’t call constructor // Note that if constructor is mistakenly called inside class, // there is an immediate assertion violation.

Creating and Destroying Objects Item 5: Avoid Creating Unnecessary Objects On the one hand, performance is a secondary concern behind correctness On the other, gratuitous object creation is just bad programming // String s = new String(“stringette”); // Don’t do this! vs. // String s = “stringette”; // Let JVM optimize for you // Also see earlier Boolean.valueOf() static factory example

Creating and Destroying Objects Item 5: Code Example public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted // DON’T DO THIS public boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomStart = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomEnd = gmtCal.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; }

Creating and Destroying Objects Item 5: Code Example Fixed public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted private static final Date BOOM_START; private static final Date BOOM_END; static { // Note static block Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); BOOM_END = gmtCal.getTime(); } public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; }

Creating and Destroying Objects Item 5: Autoboxing Overhead // Hideously slow program! Can you spot the object creation? public static void main(String[] args) { Long sum = 0L; for (long i =0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); } // Lessons: 1) prefer primitives to Boxed primitives // 2) watch for unintentional autoboxing

Creating and Destroying Objects Item 6: Eliminate Obsolete Object References Sometimes, you manage your own memory (leak) Example: Stack.javaStack.java public Object pop () { if (size == 0) throw new IllegalStateException("Stack.pop"); Object result = elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; } Also a problem with caches and registration of listeners and callbacks Suggestion: Use weak pointers, such as WeakHashMap

Creating and Destroying Objects Item 7: Avoid Finalizers finalize() is a method in the Object class What the garbage collector may call when cleaning up an unused object Finalizers: unpredictable, dangerous, unnecessary! They are NOT the analog of C++ destructors There is no guarantee a finalizer will ever be called Finalizers have severe performance penalties Instead, provide explicit termination methods Sometimes requires “finalizer chaining”

Creating and Destroying Objects Item 7: Code Example // try-finally block guarantees execution of termination method // termination method ensures resources are released // Example resources: database connections, threads, windows Foo foo = new Foo(); try { // Do what must be done with foo } finally { foo.terminate(); // Explicit termination method in Foo }

Creating and Destroying Objects Item 7: Finalizer chaining // Manual finalizer chaining // Only do this if you *have* to use the protected void finalize() throws Throwable { try {... // Finalize subclass state } finally super.finalize(); // Note order of finalizer chaining } // Also consider “Finalizer Guardian” idiom for public, nonfinal // classes. The goal is to ensure that finalization takes place // even if subclass finalizer fails to invoke super.finalize()