More on Initialization


To support the notion of in-state versus out-of-state students, the Student object needs to store a state that represents where the Student resides. The school happens to be located in the state of Colorado (abbreviation: CO). If the student resides in any other state, or if the student has no state specified (either the student is international or didn't complete the forms yet), then the student is an out-of-state student.


Here is the test:

 public void testInState() {    Student student = new Student("a");    assertFalse(student.isInState());    student.setState(Student.IN_STATE);    assertTrue(student.isInState());    student.setState("MD");    assertFalse(student.isInState()); } 

The logic for determining whether a student is in-state will have to compare the String representing the student's state to the String "CO". This of course means you will need to create a field named state.

 boolean isInState() {    return state.equals(Student.IN_STATE); } 

To compare two strings, you use the equals method. You send the equals message to a String object, passing another String as an argument. The equals method will return true if both strings have the same length and if each string matches character for character. Thus "CO".equals("CO") would return true; "Aa".equals("AA") would return false.

In order for testInState to pass, it is important that the state field you create has an appropriate initial value. Anything but "CO" will work, but the empty String ("") will do just fine.

 package sis.studentinfo; public class Student {    static final String IN_STATE = "CO";    ...    private String state = "";    ...    void setState(String state) {       this.state = state;    }    boolean isInState() {       return state.equals(Student.IN_STATE);    } } 

You might also consider writing a test to demonstrate what should happen if someone passes a lowercase state abbreviation. Right now, if client code passes in "Co", it will not set the student's status to in-state, since "Co" is not the same as "CO". While that may be acceptable behavior, a better solution would be to always translate a state abbreviation to its uppercase equivalent prior to comparing against "CO". You could accomplish this by using the String method toUpperCase.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net