Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Suppose we want to display an empty list as () and the list containing 1, 2, 3 as (1, 2, 3) . How do we do this? We need to add a method to the InList hierarchy of classes to perform this computation. Let's call this method listString() and let's proceed together.

Step 1: Instantiate the interpreter code template given above by replacing returnType with String , the methodName with listString and the parameter_list with nothing. Be sure to create one file for each class. The code will not compile. Why?

Step 1.5: Add syntactically correct code to the template so that the whole thing compile.

Step 2: Write appropriate JUnit test classes. Because of lack of time, we will not do this step in class.

Step 3: Write the code for listString in EmptyInstList . This is trivial! Make sure it passes the JUnit test though!

Step 4: Write the code for listString in ConsIntList . You can try the structural recursive code given in the template and see that it will not work. This is because by the time you reach the end of the list (i.e. when rest is the empty list), you need to do something different from what EmptyIntList . listString() is programmed to do. You will need to call on rest to perform an auxiliary ("helper") method to get the job done. Let's call this helper method listStringHelp .

...

The code will not compile because we have yet to add the method listStringHelp to the IntList hierarchy.

Step 5: Add the method String listStringHelp(String acc) to the IntList hierarchy; add stub template code so that the whole thing compile. Unless you accidentally write the correct code, the JUnit test for ConsIntList will not pass still.

Step 6: Write JUnit test code for listStringHelp . Again, due to lack of time, we will not do that here in the lab. Actually, more than often, writing the test code will help write the code for the method in question.

Step 7: Write the code for EmptyIntList.listStringHelp(String acc) What should the empty do here? It knows it has the accumulated string representation of the whole list so far and that all it needs is the closing parenthesis. So all it has to do is to add the closing parenthesis to the accumulated string and return: return acc + ")"; (And make sure it passes the JUnit test).

Step 8: Write the code for ConsIntList.listStringHelp (and make sure that it passes the JUnit test). What can a non-empty list do here? All it needs to do is to concatenate a comma and its first to the accumulated string representation so far and pass it on to rest to complete the job: return rest.listStringHelp(acc + ", " + first); (And make sure it passes the JUnit test).

...