Eliza 5 - A better way to select a response

by Ravi Bhavnani


So far, we've been selecting a random response from a pattern's set of responses. We've done this by using Random.Next() to generate an index between zero and the number of responses, and returning the response at that index. Because the number of responses for a phrase is relatively small, Random.Next() might return the same index as before, causing Eliza to sound like she's repeating herself. To ensure Eliza never repeats a response, let's instead cycle through each response.

We'll do this by using an integer to keep track of the index of the last used response. Because different phrases have different numbers of responses, we'll need a separate index for each phrase. Something like this:

    // Index of next response for BECAUSE.
    private int _indexBecause;

    // Index of next response for YES.
    private int _indexYes;

    // Index of next response for NO.
    private int _indexNo;

What if Eliza grows to recognize a hundred phrases? Or even a thousand? Clearly, we'll need an index variable for each phrase. This leads to code that's hard to scale (i.e. expand).

WHENEVER YOU SEE YOURSELF DUPLICATING CODE, ASK YOURSELF:
"Is there a way to generalize what I'm doing?"

Real-world example

Suppose you were tasked with designing a C# class PhoneBook to keep track of the phone numbers of residents in a town. The residents are:

  • Bob & Alice Smith
  • Paul Hawkins
  • Samir & Ritu Shah
  • ... about a thousand more names ...

Would the Phonebook class contain a thousand different variables, one to store the phone number of each resident?  Something like this:

    // Phone number of Bob & Alice Smith
    private string _phoneNumberBobAliceSmith;

    // Phone number of Paul Hawkins
    private string _phoneNumberPaulHawkins;

    // Phone number of Samir & Ritu Shah
    private string _phoneNumberSamirRituShah;

    ... about a thousand more variables ...

I hope you said "No!" 

GENERALIZE Pattern.cs SO THAT IT'S SIMPLER AND REPRESENTS A SINGLE PHRASE.
THEN COMPARE YOUR CODE WITH THAT IN THE SOLUTION.

Testing your changes

Now that you've generalized the Pattern class, run the driver program and verify that Eliza is working correctly, by having the following conversation where the user repeats saying YES and NO.

THE ONLY WAY TO VERIFY THAT YOUR CODE CHANGES ARE CORRECT
IS TO HAVE A WAY TO TEST YOUR CHANGES.

WHEN DEVELOPING MISSION-CRITICAL SOFTWARE (e.g. SOFTWARE ON WHICH HUMAN LIVES DEPEND), ENGINEERS BUILD THE TESTS BEFORE WRITING THE SOFTWARE. THIS WAY OF DEVELOPING SOFTWARE IS CALLED "TEST-DRIVEN DEVELOPMENT" OR TDD.
 

Most of the content at this site is copyright © Ravi Bhavnani.
Questions or comments?  Send mail to ravib@ravib.com