- CourseSession
- Enrolling Students
- int
- Initialization
- Default Constructors
- Suites
- The SDK and java.util.ArrayList
- Adding Objects
- Incremental Refactoring
- Objects in Memory
- Packages and the import Statement
- The java.lang Package
- The Default Package and the package Statement
- The setUp Method
- More Refactoring
- Class Constants
- Dates
- Overloaded Constructors
- Deprecation Warnings
- Refactoring
- Creating Dates with Calendar
- Comments
- Javadoc Comments
- Exercises
More Refactoring
The method testEnrollStudents is a bit longer than necessary. It contains a few too many assertions that track the number of students. Overall, the method is somewhat difficult to follow.
Instead of exposing the entire list of students to client code (i.e., other code that works with CourseSession objects), you can instead ask the Course-Session to return the Student object at a specific index. You currently have no need for the entire list of students as a whole, so you can eliminate the getAllStudents method. This also means that you no longer have to test the size of the ArrayList returned by getAllStudents. The test method can be simplified to this:
public void testEnrollStudents() { Student student1 = new Student("Cain DiVoe"); session.enroll(student1); assertEquals(1, session.getNumberOfStudents()); assertEquals(student1, session.get(0)); Student student2 = new Student("Coralee DeVaughn"); session.enroll(student2); assertEquals(2, session.getNumberOfStudents()); assertEquals(student1, session.get(0)); assertEquals(student2, session.get(1)); }
Add the get method to CourseSession and remove the method getAllStudents. This refactoring shows how you can move common code from the test class directly into the production class in order to remove duplication.
class CourseSession { ... ArrayList<Student> getAllStudents() { return students; } Student get(int index) { return students.get(index); } }
Another significant benefit of this refactoring is that you have hidden a detail of CourseSession that was unnecessarily exposed. You have encapsulated the students collection, only selectively allowing the get, add, and size operations to be performed on it.
This encapsulation provides two significant benefits: First, you currently store the list of in an ArrayList. An ArrayList is one specific kind of data structure with certain use and performance characteristics. If you expose this list directly to client code, their code now depends upon the fact that the students are available as an ArrayList. This dependency means that later you cannot easily change the representation of how students are stored. Second, exposing the entire collection means that other classes can manipulate that collection—add new Student objects, remove Student objects, and so on—without your CourseSession class being aware of these changes. The integrity of your CourseSession object could be violated!