Class Note for CMPSCI 220 at UMass(33)
Class Note for CMPSCI 220 at UMass(33)
Popular in Course
Popular in Department
This 4 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 15 views.
Reviews for Class Note for CMPSCI 220 at UMass(33)
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
CMPSCI 220 291A Programming Methodology Fall 2008 5 Design Effective Java Items 21 1 amp 4 UNIVERSITY OF MASSACHUSETES AMHERST Department of Computer Science 00 Programmer s Toolbox I Language Basics I Fundamental language constructs I Standard usage idioms I Advanced Language Features I Sometimes added in later releases or versions I Customary and Effective Usage I Guidance from experienced users I Elements of Stvle gt Cobol With Style I Effective C gt Effective ava umvrnsm 0E MASSACHUSE I EAMHERST Department of Computer science Item 21 Function Objects I Invoking aJava method on an object typically performs some operation on that object I Possible to define objects whose methods operate on other objects passed as parameters I Instance of a class exporting exactly one such method is effectively a pointer to that method I Such instances are known as function objects UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Highly Skilled Programming I Pro cient with I Tools I Methods I The two are often interrelated I Eg design methods and programming language I Specifically 00 language features and design UNIVERSITY or MASSACHUSETTS AMHERST Department of Compmer Science Effective Java Item 21 I Use function objects to represent strategies In many languages functions can be passed as parameters to other functions via function pointers etc E g a SOl l function might be passed a comparator Different comparators yield different sorting behaviors An example ofthe Strategy Pattern the comparator function represents a strategy for sorting elements I Java has no function pointers I So how to achieve the strategy pattern UNIVERSITY or MASSACHUSETTS AMHERST Department of Computer Science Example Function Object class StringLengthComparator public int com pareString si String s2 return 81 lengthO s2 lengthO 39Method orders string by length not lexicographically 39Reference to StringLengthComparator serves as a function pointer lnstance of class is a concrete strategy for string comparison 7 UNIVERsmr or MASSACHUSETTS AMHERSI Department of Computer Science Passing the Function Object 0 What type for the function object Parameter StringLengthComparator no good W allows only one strategy 39Define a Comparator interface 39Modify StringLengthComparator to implement it Singleton Function Object class StringLengthComparator private StringLengthComparatorO public static final StringLengthCom parator NSTANCE new StringLengthComparatorO public int compareString s1 String s2 return s1 Ien th s2en th g 0 g 0 Strategyinten ace public interface Com paratorltTgt public int com pareT t1 T t2 39Concrete strategy class is typically stateless Hence 211 mStmces are mCtiOmlly equivalent class StringLengthCom parator implements Com paratorltStringgt 39Singleton saves unnecessary object creation costs Same class body as before CUNIVERSITY or MAssAcHusFrrs AMHERST Department oiTCompmver Science Anonymous Strategy Classes Hosting Strategy Classes I Concrete strategy class need not be public to Arrays sortstringArray new ComparatorltStringgt export a concrete strategy public int compareString s1 String s2 return 81 ength S2 ength I A host class can export a public static eld l Or a static factory method Item 1 I The strategy interface will be the type I Concrete strategy class can be a private nested class of the host I Unlike anonymous class allows implementing additional interfaces 39Concrete strategy classes are often declared using anonymous classes 39Each call creates a new instance 39lfused often better to store function object in a private static final field with descriptive name and reuse it UNIVERsiwiorliIAssAcHusFrTs AMHERST Department of Computer Science ibmvrnsm o Magsxicuusms AMHERST Department of Computer science Hosting Strategy Classes Item 21 Summary Exporting a concrete strategy class Host private static class StrLenCmp implements ComparatorltStringgt Serializable public intcompareString s1 String s2 return s1 ength s2 ength I Implementing the Strategy pattern is a primary use of function pointers I To implement the Strategy pattern in Java Declare an interface to represent the strategy Create a class implementing this interface for each concrete strategy For sin 1e use strate 39es an anon mous class llRetumed comparator is serializable g g y public static final Com paratorltStringgt STR NG LENGTH COMPARATOR new StrLenCmpO For repeated use strategies a private static member class exported as a public static final field Whose type is the strategy interface Rest of class omitted UNIVERSITY or MAssAcHusHTs AMHERsr Department of Compmer Science iumvrnsm OF MASSACHUSETTS AMHERST Department ofComputer Science Static Factory Methods Effective Java Item 1 Advantages I Consider static factory methods instead of I Unlike constructors they have names constructors I Uses are easier to read and understand I Normal Way for classes to permit creation of I Avoids limitation of only one constructor With instances is to provide a public constructor given signature I Highly skilled programmer s toolkit should I Better than reordering parameters to distinguish also contain an alternative approach constructors I Public static factory method 2 static method that returns an instance of the class For example pubic static Boo ean va ueOtboo ean b return b Boo ean TRUE Boo ean FALSE UNIVERsmr or MASSACHUSETES AMHERSI Department of Computer Science iUNIVERSITY or MAssAcHusFrrs AMHERST Department ot39Compmver Science Static Factory Methods Static Factory Methods Advantages Advantages I Unlike constructors they are not required to create a I Unlike constructors they can return an object of any new object each time they are invoked subtype of their return type I Allows immutable classes to avoid unnecessary instances I Even instances of classes that are not public I Repeatedly dispensingprecomputed or cached instances I Supports interfacebased frameworks 39 F01 CXBIUPIC BOOIean valueOfO 119V creates an Obie I Interfaces are natural return types for static factory methods I Supports instancecontrolled classes I By convention static factory methods for interface names I Strict control over what instances exist at any time Type are in nonrinstantiable class named Types I Class can guarantee it is singleton or noninstantiable I Immutable class can guarantee only one instance with I Depending on values of parameters to static factory method glven value quot mum types do this I They reduce the verbosity of creating instances of pararneterized types I Class returned can vary from invocation to invocation umvtnsm o Massxtcuusms AMHERST Department of Computer science UNIVERSITYioFiMASSACHLISFrTS AMHERST Department of Computer Science Static Factory Methods Disadvantages Effective Java Item 4 I A class Without public or protected constructors I Enforce noninstantiability with a private cannot be subclassed constructor I Sarne for nonpublic classes returned by static factory methods I Classes that just group static methods and static I But this encourages use of composition vs inheritance elds ShOUId nOt be ulsmntlated I Not easily distinguished from other static methods I Such classes can be useful W static methods I Naming conventions to reduce this problem such as including factory methodsgt implementing an I valueOfW same value as parameters type conversion lterface for ex Ple I getlnstance W not same value as parameters I Not designed to be instantiated instance I newlnstance W guarantees distinct instances wouldn t make sense I getType W when factory method in a different class I newT W when facto method in a different class UNIVERSITY OF MASSACHUSETTS AMHERST Department Of Computer Science UNIVERSITY or MAssAcHusnTs AMHERsr Department of Compmer Science Making a Class Uninstantiable I Providing no constructor doesn t work I If no explicit constructors compiler provides a public parameterless default constructor l 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 UNIVERsmr or MAssAcHusHEs AMHERST Depantmemg of Computer Science Making a Class Uninstantiable I Constructor is private so inaccessible outside of class I ASSGFthhEI I OI not necessary but ags accidental invocation of constuctor 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 Umvznsm or MASSECHUSETEAMHERS39F Department of Computer 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 7 UNIVERSITY or MASSACHUSFl39fS AMHERST Department of Compmer Science
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'