Comp 110 Writing and Testing

Best Practices when Writing and Testing Functions

STEP 1: Write a "function definition skeleton" meaning:

  1. Declare the function with the correct name, parameter, and return type
  2. Return a "dummy" value to begin with
    1. Return type is number? Return 0.
    2. Return type is string? Return "?".
    3. Return type is boolean? Return false.
    4. Return type is List? Return null.

STEP 2: Write some example use cases of calling this function from your main function...store the returned values in variables and print the results

STEP 3: Once you know the test calls in step 2 are working, go back to the function definition and work on correctly implementing its logic.

STEP 4: Try different arguments in your test cases to help you convince yourself that your implementation is correct.

Example:

Task: write a function repeatStuff that takes in a string str and a number n and returns a string that repeats n times

STEP 1: declaration and 'dummy' value

let repeatStuff = (str: string, n: number):string => {

     return "?";
}

STEP 2: example use cases

print(repeatStuff("Bo", 4)); 
//-> "BoBoBoBo"

print(repeatStuff("MakeHappy", 2)); 
//-> "MakeHappyMakeHappy"

print(repeatStuff("what.", 0)); 
//-> ""

STEP 3: function logic

let repeatStuff = (str: string, n: number):string => {

     return "?";
}

//base case = when n is 0
let repeatStuff = (str: string, n: number):string => {
     if(n===0){
          return "";
     } else {
          return "?";
}

//what are we concatenating for each 'n'?
let repeatStuff = (str: string, n: number):string => {
     if(n===0){
          return "";
     } else {
          return str + repeatStuff(str, n-1);
          //str is being concatenated over and over until n === 0
          //when n===0, the concatenated strs will be concatenated with ""
}

STEP 4: testing

//call your main() function with your test cases that you wrote earlier and confirm that they all return what is expected!
//if one of your tests fail, find where in your code something goes wrong!
//what is unique about this test (compared to the others) that is causing the failure? 
//for example, if test 3 is failing, then something must be wrong with your base case!