System Properties


Both the method geTRosterReport and its test contain the use of '\n' to represent a line feed in many places. Not only is this duplication, it is not portabledifferent platforms use different special character sequences for advancing to a new line on output. The solution to this problem can be found in the class java.lang.System. As usual, refer to the J2SE API documentation for a more detailed understanding of the System class.

The System class contains a method named getProperty that takes a system property key (a String) as a parameter and returns the system property value associated with the key. The Java VM sets several system properties upon startup. Many of these properties return information about the VM and execution environment. The API documentation method detail for getProperties shows the list of available properties.

One of the properties is line.separator. According to the Java API documentation, the value of this property under Unix is '\n'. However, under Windows, the value of the property is '\r\n'. You will use the line.separator system property in your code to compensate for the differences between platforms.

The following changes to the test and to CourseSession demonstrate use of the System method getProperty.

Test code:

 public void testRosterReport() {    Student studentA = new Student("A");    Student studentB = new Student("B");    session.enroll(studentA);    session.enroll(studentB);    String rosterReport = session.getRosterReport();    assertEquals(       CourseSession.ROSTER_REPORT_HEADER +       "A" + CourseSession.NEWLINE +       "B" + CourseSession.NEWLINE +       CourseSession.ROSTER_REPORT_FOOTER + "2" +       CourseSession.NEWLINE, rosterReport); } 

Production code:

 class CourseSession {    static final String NEWLINE =       System.getProperty("line.separator");    static final String ROSTER_REPORT_HEADER =       "Student" + NEWLINE +       "-" + NEWLINE;    static final String ROSTER_REPORT_FOOTER =       NEWLINE + "# students = ";    ...    String getRosterReport() {       StringBuilder buffer = new StringBuilder();       buffer.append(ROSTER_REPORT_HEADER);       Student student = students.get(0);       buffer.append(student.getName());       buffer.append(NEWLINE);       student = students.get(1);       buffer.append(student.getName());       buffer.append(NEWLINE);       buffer.append(ROSTER_REPORT_FOOTER + students.size() + NEWLINE);       return buffer.toString();    } } 



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