Agile Javaв„ў: Crafting Code with Test-Driven Development

Since java.util.ArrayList provides a size method, you can just ask the students ArrayList object for its size instead of tracking numberOfStudents separately.

int getNumberOfStudents() { return students.size(); }

Make this small refactoring, then recompile and rerun the test. Having the test gives you the confidence to change the code with impunityif the change doesn't work, you simply undo it and try something different.

Since you no longer return numberOfStudents from getNumberOfStudents, you can stop incrementing it in the enroll method. This also means you can delete the numberOfStudents field entirely.

While you could scan the CourseSession class for uses of numberOfStudents, removing each individually, you can also use the compiler as a tool. Delete the field declaration, then recompile. The compiler will generate errors on all the locations where the field is still referenced. You can use this information to navigate directly to the code you need to delete.

The final version of the class should look like the following code:

class CourseSession { private String department; private String number; private java.util.ArrayList<Student> students = new java.util.ArrayList<Student>(); CourseSession(String department, String number) { this.department = department; this.number = number; } String getDepartment() { return department; } String getNumber() { return number; } int getNumberOfStudents() { return students.size(); } void enroll(Student student) { students.add(student); } java.util.ArrayList<Student> getAllStudents() { return students; } }

Категории