Download Advantages and Use Cases of Static Factory Methods in Java and more Study notes Computer Science in PDF only on Docsity!
UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science
2 - Effective Java - Items 1, 2, 3 & 4
CMPSCI 220 (291A) Programming Methodology Spring 2009 UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^2 Highly Skilled Programming
! Proficient with
! Tools
! Methods
! The two are often interrelated
! E.g., design methods and programming
language
! Specifically, OO language features and design
UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 3 OO Programmer’s Toolbox
! Language Basics
! Fundamental language constructs
! Standard usage idioms
! Advanced Language Features
! Sometimes added in later releases or versions
! Customary and Effective Usage
! Guidance from experienced users
! Elements of Style => Cobol with Style
! Effective C++ => Effective Java
UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 4 Effective Java - Item 1
! Consider static factory methods instead of (or
in addition to ) constructors
! Normal way for classes to permit creation of
instances is to provide a public constructor
! Highly skilled programmer’s toolkit should also
contain an alternative approach:
! Public static factory method = static method that
returns an instance of the class. For example
public static Boolean valueOf(boolean b) {
return b? Boolean.TRUE : Boolean.FALSE; }
Static Factory Methods: Advantages
! Unlike constructors, they have names
! Uses are easier to read and understand
! E.g., BigInteger.probablePrime
! Avoids limitation of only one constructor with
given signature
! Better than reordering parameters to distinguish
constructors!
! Well chosen names highlight differences
Static Factory Methods: Advantages
! Unlike constructors, they are not required to
create a new object each time they are invoked
! Allows immutable classes to avoid unnecessary
instances
! Repeatedly dispensing precomputed or cached instances
! For example, Boolean.valueOf() never creates an object
! Similar to Flyweight design pattern
! Supports instance-controlled classes
! Strict control over what instances exist at any time
! Class can guarantee it is singleton or noninstantiable
! Immutable class can guarantee only one instance with given
value; enum types do this (allows == instead of .equals() )
UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^7 Static Factory Methods: Advantages
! Unlike constructors, they can return an object of
any subtype of their return type
! Even instances of classes that are not public
! Supports interface-based frameworks
! Interfaces are natural return types for static factory methods
! By convention, static factory methods for interface names
Type are in non-instantiable class named Types
! Java Collections Framework provides 32 implementations this
way, rather than via 32 public classes -- reducing conceptual
weight of the API
! Class returned can vary from invocation to invocation
! Depending on values of parameters to static factory method
UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^8 Static Factory Methods Enable Service Provider Frameworks
! Class returned need not even exist when static
factory method’s class is written
! Makes possible Service Provider Frameworks
! E.g., Java Database Connectivity API (JDBC)
! Such frameworks provide:
! Service interface, implemented by provider ! Provider registration API ! Service access API ! (Optionally) Service provider interface UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 9 Service Provider Framework: Service and Provider Interfaces
// Service provider framework sketch -
// Service interface
public interface Service {
// Service-specific methods go here
// Service provider framework sketch -
// Service provider interface
public interface Provider {
Service newService()
UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 10 Service Provider Framework: Service Registration and Access // Service provider framework sketch // Noninstantiable class for service registration and access import java.util.; import java.util.concurrent.; public class Services { private Services() { } // Prevents instantiation (Item 4) // Maps service names to services private static final Map<String, Provider> providers = new ConcurrentHashMap<String, Provider>(); public static final String DEFAULT_PROVIDER_NAME = “”; Service Provider Framework: Provider Registration API // Provider registration API public static void registerDefaultProvider(Provider p) { registerProvider(DEFAULT_PROVIDER_NAME, p); } public static void registerProvider(String name, Provider p){ }^ providers.put(name, p); Service Provider Framework: Service Access API // Service access API public static Service newInstance() { return newInstance(DEFAULT_PROVIDER_NAME); } public static Service newInstance(String name) { Provider p = providers.get(name); if (p == null) throw new IllegalArgumentException( "No provider registered with name: " + name); return p.newService(); }^ }
UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^19 Telescoping Constructor Pattern public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate) { this.servingSize = servingSize; this.servings = servings; this.calories = calories; this.fat = fat; this.sodium = sodium; this.carbohydrate = carbohydrate; } } UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^20 Telescoping Constructor Pattern: Usage and Problems public static void main(String[] args) { NutritionFacts cocaCola = new NutritionFacts(2 40 , 8 , 1 00 , 0 , 35 , 27)
- Use constructor with shortest parameter list containing
all desired parameters, even though extras are likely included
- Hard to write -- easy to get unlabelled values out of order
- Harder to read -- must count parameter locations UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 21 Java Beans Pattern // JavaBeans Pattern - allows inconsistency, mandates mutability public class NutritionFacts { // Parameters initialized to default values (if any) private int servingSize = -1; // Required; no default value private int servings = -1; // " " " " private int calories = 0; private int fat = 0; private int sodium = 0; private int carbohydrate = 0; public NutritionFacts() { } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 22 Java Beans Pattern // Setters public void setServingSize(int val) { servingSize = val; } public void setServings(int val) { servings = val; } public void setCalories(int val) { calories = val; } public void setFat(int val) { fat = val; } public void setSodium(int val) { sodium = val; } public void setCarbohydrate(int val) { carbohydrate = val; } Java Beans Pattern: Usage public static void main(String[] args) { NutritionFacts cocaCola = new NutritionFacts(); cocaCola.setServingSize(240); cocaCola.setServings(8); cocaCola.setCalories(100); cocaCola.setSodium(35); cocaCola.setCarbohydrate(27); } }
- Object may be in inconsistent state during construction
- No possibility of immutable class Builder Approach
! Based on Builder design pattern
! Client calls constructor or static factory with all
required parameters; builder object returned
! Client uses setter-like methods to set optional
parameters, then calls build() to generate object
! Builder is a static member class of class it builds
! Client code easy to write and read
! Builder pattern simulates named optional
parameters (e.g., Python, Ada)
UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^25 Builder Pattern // Builder Pattern public class NutritionFacts { private final int servingSize; private final int servings; private final int calories; private final int fat; private final int sodium; private final int carbohydrate; UUNIVERSITY OFNIVERSITY OF^ MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST^ • •^ Department of Computer ScienceDepartment of Computer Science^^26 Builder Pattern public static class Builder { // Required parameters private final int servingSize; private final int servings; // Optional parameters - // initialized to default values private int calories = 0; private int fat = 0; private int carbohydrate = 0; private int sodium = 0; public Builder(int servingSize, int servings) { this.servingSize = servingSize; this.servings = servings; } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 27 Builder Pattern public Builder calories(int val) { calories = val; return this; } public Builder fat(int val) { fat = val; return this; } public Builder carbohydrate(int val) { carbohydrate = val; return this; } public Builder sodium(int val) { sodium = val; return this; } public NutritionFacts build() { return new NutritionFacts(this); } } UUNIVERSITY OFNIVERSITY OF MMASSACHUSETTSASSACHUSETTS, A, AMHERSTMHERST • • Department of Computer ScienceDepartment of Computer Science 28 Builder Pattern private NutritionFacts(Builder builder) { servingSize = builder.servingSize; servings = builder.servings; calories = builder.calories; fat = builder.fat; sodium = builder.sodium; carbohydrate = builder.carbohydrate; } } Builder Pattern public static void main(String[] args) { NutritionFacts cocaCola = new NutritionFacts.Builder(2 40 , 8). calories(100).sodium(35).carbohydrate(27).build(); } Effective Java - Item 3
! Enforce the singleton property with a private
constructor or an enum type
! Singleton = class instantiated exactly once
! Intrinsically unique system component, such as:
! Window manager ! File system ! Game engine
Making a Class Uninstantiable
! Including a private constructor does work
! A default constructor is generated only if a class
contains no explicit constructors
// Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for
// noninstantiability
private UtilityClass() {
throw new AssertionError();
Making a Class Uninstantiable
! Constructor is private, so inaccessible outside
of class
! AssertionError not necessary, but flags
accidental invocation of constructor from
inside class
! Comment helpful since usage counterintuitive
! Also prevents class from being subclassed
! All constructors must invoke a superclass
constructor
! No accessible superclass constructor