Factory MethodsYou can modify CourseSession so that it supplies a static-side factory method to create CourseSession objects. By doing so, you will have control over what happens when new instances of CourseSession are created. Modify the CourseSessionTest method createCourseSession to demonstrate how you will use this new factory method.
In CourseSession, add a static factory method that creates and returns a new CourseSession object:
Find all other code that creates a CourseSession via new CourseSession(). Use the compiler to your advantage by first making the CourseSession constructor private:
Replace the CourseSession constructions you find (there should be one in RosterReporterTest and one in CourseSessionTest) with message sends to the static factory method. With the CourseSession constructor declared as private, no client code (which includes test code) will be able to create an instance of CourseSession directly using a constructor. Clients must instead use the static factory method. Joshua Kerievsky names the above refactoring "Replace [Multiple[4]] Constructors with Creation Methods."[5] The class methods are the creation methods. The significant benefit is that you can provide descriptive names for creation methods. Since you must name a constructor the same as the class, it cannot always impart enough information for a developer to know its use.
Now that you have a factory method to create CourseSession objects, tracking the total count can be done on the static side, where it belongs. Much of good object-oriented design is about putting code where it belongs. This doesn't mean that you must always start with code in the "right place," but you should move it there as soon as you recognize that there is a better place for it to go. It makes more sense for incrementCount message sends to be made from the static side:
|
Wednesday, October 14, 2009
Factory Methods
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment