Wednesday, October 21, 2009

The Student Directory








The Student Directory



package sis.studentinfo;

import junit.framework.*;
import java.io.*;

public class StudentDirectoryTest extends TestCase {
private StudentDirectory dir;

protected void setUp() throws IOException {
dir = new StudentDirectory();
}

protected void tearDown() throws IOException {
dir.close();
dir.remove();
}

public void testRandomAccess() throws IOException {
final int numberOfStudents = 10;
for (int i = 0; i < numberOfStudents; i++)
addStudent(dir, i);
dir.close();

dir = new StudentDirectory();
for (int i = 0; i < numberOfStudents; i++)
verifyStudentLookup(dir, i);
}

void addStudent(StudentDirectory directory, int i)
throws IOException {
String id = "" + i;
Student student = new Student(id);
student.setId(id);
student.addCredits(i);
directory.add(student);
}

void verifyStudentLookup(StudentDirectory directory, int i)
throws IOException {
String id = "" + i;
Student student = dir.findById(id);
assertEquals(id, student.getLastName());
assertEquals(id, student.getId());
assertEquals(i, student.getCredits());
}
}


The most significant new addition to StudentDirectoryTest appears in testRandomAccess. When it adds the students to the directory, the test closes it. It then creates a new directory instance to be used for the student lookups. By doing this, the test demonstrates at least some notion of persistence.


An additional performance test might be worthwhile to demonstrate that a lookup into the directory takes the same amount of time regardless of where it appears in the file. Additions of students to the directory should also execute in constant time.



package sis.studentinfo;

import java.io.*;
import sis.db.*;

public class StudentDirectory {
private static final String DIR_BASENAME = "studentDir";
private DataFile db;

public StudentDirectory() throws IOException {
db = DataFile.open(DIR_BASENAME);
}

public void add(Student student) throws IOException {
db.add(student.getId(), student);
}

public Student findById(String id) throws IOException {
return (Student)db.findBy(id);
}

public void close() throws IOException {
db.close();
}

public void remove() {
db.deleteFiles();
}
}


In contrast, most of the StudentDirectory class has changed. The StudentDirectory class now encapsulates a DataFile instance to supply directory functionality. It provides a few additional specifics, including the key field to use (the student id) and the base filename for the data and key files. Beyond that, the class merely delegates messages to the DataFile object.








    No comments: