Class Note for CMPSCI 220 at UMass(17)
Class Note for CMPSCI 220 at UMass(17)
Popular in Course
Popular in Department
This 7 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at University of Massachusetts taught by a professor in Fall. Since its upload, it has received 14 views.
Reviews for Class Note for CMPSCI 220 at UMass(17)
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 02/06/15
Highly Skilled Programming CMPSCI 220 291A I Pro cient with Programming Methodology I Tools Spring 2009 l Methods I The two are often interrelated I Eg design methods and programming language I Speci cally 00 language features and design 2 Effective Java Items 1 2 3 amp 4 7 UNIVERSITY OF MASSACHUSEI39rS AMHERST Department or Compmer Science UNIVERSnY 0E MASSACHUSETES AMHERST Department of Computer Science OO Programmer s Toolbox Effective Java Item 1 I Consider static factory methods instead of or I Language Basics in addition to constructors I Fundamental language constructs I Normal way for classes to permit creation of instances is to provide a public constructor I Highly skilled programmer s toolkit should also contain an alternative approach I Standard usage idioms I Advanced Language Features I Sometimes added in later releases or versions I Customary and Effective Usage I I I I Public static factory method 2 static method that I Gmdance from experienced users returns an instance of the class For eXarnple 39 Elements Of SW16 gt C0b01 With SW16 public static Boolean valueOfboolean b M gt M I return b BooleanTRUE BooleanFALSE 2 UNIVERSITY OF MASSXCHusETEAMHERST 39 Department Of Computer Science UNIVERSITY OF MASSACHllsFrTiS AMHERST 39 Department Of Compmer Science Static Factory Methods Static Factory Methods Advantages Advantages I Unlike constructors they are not required to create a new object each time they are invoked I Allows immutable classes to avoid unnecessary I Unlike constructors they have names I Uses are easier to read and understand Eg BiglntegerprobablePrime instances I AVOlClS39 limitation of only one constructor w1th Repeatedly dispensing Precomputed or cached instances given Signature I For example Boolean valueOfO never creates an object I Better than reordering parameters to distinguish I Similar to Flyweight design pattern constructorsl I Supports instancecontrolled classes I Well chosen names highlight differences I Strict control over what instances exist at any time I Class can guarantee it is singleton or noninstantiable I Immutable class can guarantee only one instance with given value enum types do this allows instead of equalsO UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Static Factory Methods Static Factory Methods Enable Advantages Service Provider Frameworks l Unlike COnSttllCtOIS they C2111 realm 2111 ObIeCt 0f I Class returned need not even exist when static any subtype Of thEiI 16mm type factory method s class is written 39 Even inStmces Ofdasses that are nOt PUbhc I Makes possible Service Provider Frameworks 39 supports interface39based frameworks I E g Java Database Connectivity API GDBC l Interfaces are natural retum types for static factory methods I By convention static factory methods for interface names I suCh frameworks prOVIde Type are in nonemstantiable class named Types I Service interface implemented by provider I Java Collections Framework provides 32 implementations this I Provider registration API way rather than v1a 32 public classes W reducing conceptual weight of the API I Service access API I Class returned can vary from invocation to invocation 39 OPtIOHQHW servlce PrOVIdet Interface I Depending on values of parmeters to static factory method UNIVERSITY OF MASSACHUSETTS AMHERST 39 Department Of Computer Science UNIVERSITY OF MASSACHUSHTS AMHERST 39 Department Of Compmoer Science Service Provider Framework Service Provider Framework Service and Provider Interfaces Service Registration and Access Service provider framework sketch Serche Wider Framework SkeW Service interface Noninstantiable class for serv1ce registration and access public interface Service import javautil SerVice speCific methods go here import javautilconcurrent public class Services SerVice pr OV39Ldelquot framework sketch private ServicesO Prevents instantiation Item 4 Service provider interface public interface Provider Maps serv1ce names to serv1ces private static final MapltString Providergt providers new ConcurrentHashNkaltString Providergt public static final String DEFAULTPROIDERNAME ltdefgt Service newServi ceC UNIVERSITY or MASSACHUSE ITS AMHERST Department of Computer Science UNIVERSITY or MAssAcHusnTs AMHERST Department of Computer Science SerVIce Prowder Framework SerVIce PrOVIder Framework PrOVIder RegIstratIon AP SerVIce Access AP Provider registration API Service access API public static void registerDefaultProviderProvider p PUbllC Static seerce SWInSthceO registerProviderDEFAULTPROVIDERNAME p FStUFn heWI SthCECDEFAUL39ILPROVIDERNAME public static void registerProviderString name Provider p PUPHC Static seerceneWIn5tanceStr ln9 name providersputname p Prov1der p prov1dersgetname if p null throw new IllegalArgumentException quotNo provider registered with name quot name return p newServiceo Umvrnsmiof MASSACHUSHTS AMHERsr Department of Computer Science Static Factory Methods Advantages I They reduce the verbosity of creating instances of parameterized types I Constructors for pararneterized classes generics require explicit type parameter specification I With static factories type inference can be done by compiler Instead of MapltString ListltStringgtgt m new HashMap ltString ListltStringgtgt 0 Allows MapltString ListltStringgtgt m HashMapnewnstance T UNIvERsmr or MASSACHUSETTS AMHERST Department of Computer Science Static Factory Methods Disadvantages I Not easily distinguished from other static methods I Naming conventions to reduce this problem such as I valueOfW same value as parameters type conversion I getlnstance W not same value as parameters I newlnstance W guarantees distinct instances I getType W when factory method in a different class I newType W when factory method in a different class Telescoping Constructor Pattern Telescoping constructor pattern does not scale well public class NutritionFacts private Final int servingSize mL required private Final int servings per container required private Final int calories optional private Final int Fat g optional private Final int sodium mg optional private Final int carbohydrate g optional public NutritionFactsint servingSize int servings thisservingSi2e servings 0 UNIVERSITY or MASSACHUSETTS AMHERST Department of Computer Science Static Factory Methods Disadvantages I A class Without public or protected constructors cannot be subclassed I Same for nonpublic classes returned by static factory methods I But this encourages use of composition vs inheritance I Item 16 and HFDP s first design principle 7 Umvsnsm 0F MASSACHUSFl39fS AMHERST Department creompmerScaenee Effective Java Item 2 I Consider a builder when faced with many constructor parameters I Shared limitation of constructors and static factories don t scale well to lots of parameters I Traditional approaches I Telescoping constructor pattern I Client code hard to Write even harder to read I JavaBeans pattern I Allows inconsistent state during construction I Precludes making class immutable UNIVERSITYTOFTVIASSACHLISFTTS AMHERST Department of Computer Science Telescoping Constructor Pattern public NutritionFactsint servingSize int servings int calories thisservingSi2e servings calories 0 public NutritionFactsint servingSize int servings int calories int Fat thisservingSi2e servings calories Fat 0 public NutritionFactsint servingSize int servings int calories int Fat int sodium thisservingSi2e servings calories Fat sodium 0 UNIVERSITY or MAssAcHusnTs AMHERsr Department of Compmer Science Telescoping Constructor Pattern Telescoping Constructor Pattern Usage and Problems public NutritionFactsint servingSize int servings bl39 t t39 39d 39 St 39 int calories int Fat int sodium int carbohydrate W N S a I V01 mum mng args NutritionFacts cocaCola thiSservinQSize serviHQSize new NutritionFacts240 8 100 o 35 27 thisserVings serVings thiscalories calories thisf39at Fat Use constructor With shortest parameterlrst containing this sodium sodium all desired parameters even though extras are likely included thls39 carbohydrate carbohydrate Hard to write easy to get unlabelled values out of order Harderto read must count parameter locations UNIVERSnY 0E MASSACHUSETES AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSFl39fS AMHERST Department or Compmer Science Java Beans Pattern Java Beans Pattern JavaBeans Pattern allows inconsistency mandates mutability public class NutritionFacts H 56 Parameters initialized to default values if any pumlc Vold setserV 951e1 t Val Servlngsue Val private int servingSize l Required no default value publlc vold setservmgsmt val 56 th val private int servings l u u u u public void setCaloriesint val calories val private int calories 0 public void setFatintval Fat val private int Fat public void setSodiumint val sodium val private int sodium 0 public void setCarbohydrateint val carbohydrate val private int carbohydrate 0 public NutritionFactsO UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY oEiIIASSAcHuSE rTS AMHERST Department of Computer Science Java Beans Pattern Usage Builder Approach Based on Builder design pattern public static void mainString args NutritionFacts cocaCola new NutritionFactsO Client C3115 constructor or Static factory all cocaCola setSerVingSi2e240 cocaCola setSerVings8 requlred parameters bullder obiect returned cocaCola setCalories100 wwcdmsetswiumes I Client uses setter like methods to set optional Dcacola39 SEtCGrthydmteQn parameters then calls build to generate object I Builder is a static member Class of Class it builds Object may be in inconsistent state during construction I Chent COde easy to wnte and read 39NO POSSibi39itV 0f immUtab39e Class I Builder pattern simulates named optional parameters eg Python Ada UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY or MASSACHUSETTS AMHERST Department of Computer Science Builder Pattern Builder Pattern 1 Builder Pattern public static class Builder public class NutritionFacts Requ1red Parameters private Final int servingSize Perate nal lnt servingslze private Final int servings Private Final Int Servings private Final int calories optional parameters 532 gz ium initialized to deFault values private Final int carbohydrate Perate lnt calories 0 private int Fat 0 private int carbohydrate 0 private int sodium 0 public Builderint servingSize int servings thisservingSi2e servingSize thisservings servings UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Builder Pattern Builder Pattern public Builder caloriesint val calories val return this t N t t F t priva e u ri ion ac sBuilder builder publ cfgilldjglfatclnt Valreturn thiy servingSize builderservingSi2e servin s builderservin s public Builder carbohydrateint val wiorigs buildercalorigs carbohydrate val return this f at builderFat public Builder sodiumint val sodium buiidersodium sodium Val Y Stur n this carbohydrate buildercarbohydrate public NutritionFacts build return new NutritionFactsthis UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Builder Pattern Effective Java Item 3 public static void mainString args I Enforce the Smgleton Property Wlth apnvate NutritionFacts cocaCola new NutritionFactsBuilder240 8 caloriesloosodium35carbohydrate27build constructor or an enum type I Singleton class instantiated exactly once I Intrinsically unique system component such as I Window manager I File system I Game engine I 7 UNIVERSITY MAEAJISHTS AMHERST Department of Computer Science Singleton via Final Field Singleton with public Final Field public class Elvis public static Final Elvis INSTANCE new Elvis private Elvis public void leaveTheBuildingO SystemoutprintlnquotWhoa baby I39m outta herequot This code would normally appear outside the class public static void mainString args Elvis elvis ElvisINSTANCE elvisleaveTheBuildingO 7 UNIvERsmr or MASSACHUSETES AMHERSI Department of Computer Science Making Singletons Safe for Serialization Serializable singleton with public Final Field public static Final Elvis INSTANCE new Elvis private Elvis public void leaveTheBuildingO SystemoutprintlnquotWhoa baby I39m outta herequot private Object readResolveO Return the one true Elvis and let the garbage collector take care oF the Elvis impersonator return INSTANCE This code would normally appear outside the class public static void mainString args Elvis elvis ElvisINSTANCE elvisleaveTheBuildingO umvrnsm o Magsxacuusms AMHERST Department of Computer science Effective Java Item 4 I Enforce noninstantiability with a private constructor I Classes that just group static methods and static fields should not be instantiated I Such classes can be useful W static methods including factory methods implementing an interface for eXarnple I Not designed to be instantiated instance wouldn t make sense UNIVERSITY or MASSACHUSETTS AMHERST Department of Computer Science Singleton via Static Factory Singleton with static Factory public class Elvis private static Final Elvis INSTANCE new Elvis private Elvis public static Elvis getInstanceO return INSTANCE public void leaveTheBuildingO SystemoutprintlnquotWhoa baby I39m outta herequot This code would normally appear outside the class public static void mainString args Elvis elvis ElvisgetInstance elvisleaveTheBuildingO Singleton the New Way Enums Enum singleton the preFerred approach public enum Elvis INSTANCE public void leaveTheBuildingO SystemoutprintlnquotWhoa baby I39m outta herequot This code would normally appear outside the class public static void mainString args Elvis elvis ElvisINSTANCE elvisleaveTheBuildingO UNIVERSITYioFiMASSACHLISFTTS AMHERST Department of Computer Science Making a Class Uninstantiable I Providing no constructor doesn t work I If no explicit constructors compiler provides a public pararneterless default constructor I Looks just like any other constructor to clients I Allows for unintentionally instantiable classes I Making a class abstract doesn t work I Class can be subclassed and subclass can be instantiated I Also misleads user into thinking class was designed for inheritance UNIVERSITY or MASSACHUSETTS AMHERST Department of Campmer Science Making a Class Uninstantiable I Including a private constructor does work I 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 UtilityClassC throw new AssertionErrorC UNIVERSITY or MAssAcHusH Es AMHERST Depantmemg of Computer Science Making a Class Uninstantiable I Constructor is private so inaccessible outside of class I ASSGFtiOhEI I OI not necessary but ags accidental invocation of constructor from inside class I Comment helpful since usage counterintuitive I Also prevents class from being subclassed I All constructors must invoke a superclass constructor I No accessible superclass constructor UNIVERSITY or MASSACHUSETTS AMHERST Department of Compmoer Sciense
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'