The if Statement


The if Statement

You use the if statement for conditional branching: If a condition holds true, execute one branch (section) of code, otherwise execute another branch of code. A branch can be a single statement or a block of statements.

Flesh out the CourseSessionTest method testCompareTo by adding tests to represent more complex comparisons:

 public void testComparable()  {    final Date date = new Date();    CourseSession sessionA = CourseSession.create("CMSC", "101", date);    CourseSession sessionB = CourseSession.create("ENGL", "101", date);    assertTrue(sessionA.compareTo(sessionB) < 0);    assertTrue(sessionB.compareTo(sessionA) > 0);    CourseSession sessionC = CourseSession.create("CMSC", "101", date);    assertEquals(0, sessionA.compareTo(sessionC));    CourseSession sessionD = CourseSession.create("CMSC", "210", date);    assertTrue(sessionC.compareTo(sessionD) < 0);    assertTrue(sessionD.compareTo(sessionC) > 0); } 

Then update the compareTo method in CourseSession:

 public int compareTo(CourseSession that) {    int compare =       this.getDepartment().compareTo(that.getDepartment());    if (compare == 0)       compare = this.getNumber().compareTo(that.getNumber());    return compare; } 

Paraphrased, this code says: Compare this department to the department of the parameter; store the result of the comparison in the compare local variable. If the value stored in compare is 0 (if the departments are the same), compare this course number to the parameter's course number and assign the result to compare. Regardless, return the value stored in the compare local variable.

You could have also written the code as follows:

 public int compareTo(CourseSession that) {    int compare =       this.getDepartment().compareTo(that.getDepartment());    if (compare != 0)       return compare;    return this.getNumber().compareTo(that.getNumber()); } 

If, on the first comparison, the departments are unequal (the result of the comparison is not 0), then that's all that needs to happen. You can stop there and return the result of the comparison. The rest of the code is not executed. This style of coding can be easier to follow. Be cautious, however: In longer methods, multiple returns can make the method more difficult to understand and follow. For longer methods, then, I do not recommend multiple return statements. But the real solution is to have as few long methods as possible.

All tests should pass.



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