An example how to design classes…
- Figure out what the class is supposed to do
- List the instance variables and methods
- Write Prepcode for the methods
- Write test code for the methods
- Implement the class
- Test the methods
- Debug and reimplement
prep code:
A form of pseudocode, to help focus on the logic without stressing about syntax.
METHOD
: String checkYourself(String userGuess)
GET
the users guess as a String parameter
CONVERT
the user guess to an int
REPEAT
with each of the location cells in the int array
// COMPARE
the user guess to the location cell
IF
the user guess matches
INCREMENT
the number of hits
FIND OUT
if it was the last location cell
IF
number fo hits is 3,
RETURN
"kill" as the result
ELSE
it was not a kill, so
RETURN
"hit"
END IF
ELSE
the user guess did not match, so
RETURN
"miss"
END REPEAT
END METHODMETHOD
: void setLocationCells(int[] cellLocation)
GET
the cell locations as an int array parameter
ASSIGN
the cell location parameter to the cell location instance variable
END METHOD
Write test code for the methods
Next you should write some code to test the methods. Thats right, right write test code before there’s anything to test.
The concept of writing the test code first is one of the practices of Extreme Programming(XP).
Based on the prepcode – Here’s what we should test:
- Instantiate a object
- Assign it a location (an array of 3 ints, like {2,3,4})
- Create a String to represent a user guess (“2”, “3”, ets.)
- Invoke the method “checkYourself()”, passig it the fake user guess
- Print out the result to see if its correct (“passed” of “failed”)
[php] public class SimpleDotComTestDrive{ public static void main (String[] args){ //instantiate a SimpleDotCom object SimpleDotCom dot = new SimpleDotCom(); /** * make an int array for the location * (3 consecutive ints out of a possible 7) */ int[] locations = {2,3,4}; // invoke the setter method on the dotcom dot.setLocationCells(locations); // make a fake guess String userGuess = "2"; /** * invoke the checkYourself() method on the dotcom object * and pass it the fake guess */ String result = dot.checkYourself(userGuess); String testResult = "failed"; if(result.equals("hit")){ // if the fake guess (2) gives back a "hit", it works testResult = "passed"; } // print out the test result (passed of failed) System.out.println(testResult); } } [/php]
Implement the class
Here’s the class “SimpleDotCom”
[php] public class SimpleDotCom{ int[] locationCells; int numOfHits = 0; public void setLocationCells(int[] locs){ locationCells = locs; } public String checkYourself(String stringGuess){ int guess = Integer.parseInt(stringGuess); String result = "miss"; for (int cell : locationCells){ if (guess == cell){ result = "hit"; numOfHits++; break; } } if (numOfHits == locationCells.length){ result = "kill"; } System.out.println(result); return result; } } [/php]
The Result of the Test should be…
hit
passed