Deprecated: Creation of dynamic property wpdb::$categories is deprecated in /var/www/twodee/blog/wp-includes/wp-db.php on line 668

Deprecated: Creation of dynamic property wpdb::$post2cat is deprecated in /var/www/twodee/blog/wp-includes/wp-db.php on line 668

Deprecated: Creation of dynamic property wpdb::$link2cat is deprecated in /var/www/twodee/blog/wp-includes/wp-db.php on line 668

Deprecated: Return type of WP_Theme::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 554

Deprecated: Return type of WP_Theme::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 595

Deprecated: Return type of WP_Theme::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 535

Deprecated: Return type of WP_Theme::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 544

Deprecated: Return type of WP_REST_Request::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 960

Deprecated: Return type of WP_REST_Request::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 980

Deprecated: Return type of WP_REST_Request::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 992

Deprecated: Return type of WP_REST_Request::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 1003

Deprecated: Return type of WP_Block_List::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 151

Deprecated: Return type of WP_Block_List::next() should either be compatible with Iterator::next(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 175

Deprecated: Return type of WP_Block_List::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 164

Deprecated: Return type of WP_Block_List::valid() should either be compatible with Iterator::valid(): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 186

Deprecated: Return type of WP_Block_List::rewind() should either be compatible with Iterator::rewind(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 138

Deprecated: Return type of WP_Block_List::offsetExists($index) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 75

Deprecated: Return type of WP_Block_List::offsetGet($index) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 89

Deprecated: Return type of WP_Block_List::offsetSet($index, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 110

Deprecated: Return type of WP_Block_List::offsetUnset($index) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 127

Deprecated: Return type of WP_Block_List::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 199

Deprecated: Creation of dynamic property Automattic\Jetpack\Connection\Manager::$error_handler is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/vendor/automattic/jetpack-connection/src/class-manager.php on line 91

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Instagram_Gallery::$is_wpcom is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-instagram-gallery.php on line 23

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Mailchimp::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-mailchimp.php on line 17

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Tweetstorm_Gather::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-tweetstorm-gather.php on line 21

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Tweetstorm_Gather::$is_wpcom is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-tweetstorm-gather.php on line 22

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Gutenberg_Available_Extensions::$wpcom_is_site_specific_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/gutenberg-available-extensions.php on line 20

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Memberships::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/memberships.php on line 23

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Memberships::$wpcom_is_site_specific_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/memberships.php on line 24

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Subscribers::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/subscribers.php on line 15

Deprecated: Creation of dynamic property Automattic\Jetpack\Sync\Queue::$random_int is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/vendor/automattic/jetpack-sync/src/class-queue.php on line 38

Deprecated: Creation of dynamic property Automattic\Jetpack\Sync\Queue::$random_int is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/vendor/automattic/jetpack-sync/src/class-queue.php on line 38

Deprecated: Creation of dynamic property WPCOM_Widget_Goodreads::$shelves is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/modules/widgets/goodreads.php on line 33

Deprecated: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated in /var/www/twodee/blog/wp-includes/script-loader.php on line 348

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$toolbar_classic_block is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 347

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$toolbar_block is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 349

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$toolbar_block_side is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 350

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$panels_block is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 351

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$used_block_buttons is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 354

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Term::$object_id is deprecated in /var/www/twodee/blog/wp-includes/class-wp-term.php on line 198

Deprecated: Creation of dynamic property WP_Term::$object_id is deprecated in /var/www/twodee/blog/wp-includes/class-wp-term.php on line 198

Deprecated: Creation of dynamic property WP_Term::$object_id is deprecated in /var/www/twodee/blog/wp-includes/class-wp-term.php on line 198
» CS1: Lecture 13 – Test-driven Development

teaching machines

CS1: Lecture 13 – Test-driven Development

October 2, 2019 by . Filed under
Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383

Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383

Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383
cs1, fall 2019, lectures.

Dear students,

Is there anything like charAt for integers? For instance, given a number and an “index” representing the place, can we get back the digit at that place? Not exactly, but there’s nothing stopping us from writing our own method to accomplish this task!

But before we do that, let me share with you a quotation from Maurice Wilkes, one of the developers of the first computers:

By June 1949 people had begun to realize that it was not so easy to get programs right as at one time appeared. I well remember when this realization first came on me with full force. The EDSAC was on the top floor of the building and the tape-punching and editing equipment one floor below… It was on one of my journeys between the EDSAC room and the punching equipment that “hesitating at the angles of stairs” the realization came over me with full force that a good part of the remainder of my life was going to be spent in finding errors in my own programs.

That “hesitating at the angles of stairs” is Wilkes alluding to the poetry of T.S. Eliot.

If we are going to be an inventor—which is what we software developers are—we must care to do it right. Our software must do its task well. Our financial institutions, health systems, and Gabe Newell’s networth depend on it. There are many practices that will help us produce software of high quality, including code reviews, unit tests like the SpecChecker provides, and pair programming. We’ll talk about another one of them today: test-driven development.

Test-driven Development

Here’s a recipe to follow when writing a method to accomplish some task:

  1. Accept that you will not write the method perfectly in the first draft, and that this imperfection doesn’t mean you are not cut out to write code.
  2. Determine the method name and its inputs and outputs.
  3. Write the method so that it does nothing but compile. Have it immediately return 0 or false or null.
  4. Write a test thats feeds certain values to the method. Pit the expected results from running the method on these values against the actual results.
  5. Fix the method so that the test passes.
  6. Clean up any code that needs cleaning up, making sure the tests continue to pass as you make changes.
  7. Repeat step 3.

This process is called red-green-refactor—red for erroring test, green for passing test, and refactor for that beautiful moment when you know you code is working and where edits can be made without fear. The process is intended to minimize headache. Writing software can be an enjoyable intellectual activity, but only when you anticipate your mistakes. When you bounce from error to error and each one surprises you, you will start to think you aren’t fit to write code. But really the problem is your blundersome technique.

digitAt

Let’s see these ideas at work with our charAt for numbers. We’ll call the method digitAt, give it the number and place index, and have it return the digit, which will be an int in [0-9]:

public static int digitAt(int n, int place) {
  // ...
}

Step 3 is about doing the least you can to make the code compile:

public static int digitAt(int n, int place) {
  return 0;
}

Step 4 is to write a test. We could do this in a little main:

public static void main(String[] args) {
  int expected = 7;
  int actual = digitAt(8752, 2);
  System.out.printf("%d == %d | place 2 from 8752%n", expected, actual);
}

Step 5 is to fix the code so the test passes. A purist of test-driven development might tell you to do the simplest thing possible to make the test pass:

public static int digitAt(int n, int place) {
  return 2;
}

The test should pass now.

Let’s jump back to step 3 and add another test:

public static void main(String[] args) {
  int expected = 7;
  int actual = digitAt(8752, 2);
  System.out.printf("%d == %d | place 2 from 8752%n", expected, actual);
  expected = 5;
  actual = digitAt(8752, 1);
  System.out.printf("%d == %d | place 1 from 8752%n", expected, actual);
}

Assertion Utility

If we are going to consistently test code, we want to make writing tests as simple and brief as possible. Let’s create a new abstraction in a separate class that we will expect to reuse:

public class Certainly {
  public static void same(int expected, int actual, String message) {
    System.out.printf("%d == %d | %s%n", expected, actual, message);
  }
}

Then in main I can simply say this:

Certainly.same(7, digitAt(8752, 2), "place 2 from 8752");
Certainly.same(5, digitAt(8752, 1), "place 1 from 8752");

When I run this, the first test passes but the second fails. Now we must attend to the deeper logic issues we have going on in digitAt. We’ll sort out the implementation together in class. But after we get something working, we keep adding tests to try and break it. We should test on negative numbers, we should test place indices that reach beyond the number.

Here’s how I’d implement it:

public static int digitAt(int n, int place) {
  int withoutRightDigits = n / (int) Math.pow(10, place);
  int onesPlace = withoutRightDigits % 10;
  return onesPlace;
}

We could do some magic with String too, but that solution requires an if statement to avoid out-of-bounds errors. I guess we could write it like this:

public static int digitAt(int n, int place) {
  n = Math.abs(n);
  String s = "0" + n;
  return s.charAt(Math.max(0, s.length() - 1 - place)) - '0';
}

But this solution seems obtuse to me.

Other Problems

Let’s apply test-driven development to a few other problems. We’ll extend our assertion utilities as necessary to handle Strings.

TODO

Here’s your TODO list to complete before we meet again:

See you next class!

Sincerely,

P.S. It’s time for a haiku!

Red-green-refactor
It hurts less than my old way
Red-bloody-burning

P.P.S. Here’s the code we wrote together in class…

Main.java

package lecture1002.cs145;

public class Main {
  public static void main(String[] args) {
    Certainly.samesies(1, NumberUtilities.digitAt(210, 1));
    Certainly.samesies(2, NumberUtilities.digitAt(210, 2));
    Certainly.samesies(0, NumberUtilities.digitAt(210, 0));
    Certainly.samesies(0, NumberUtilities.digitAt(210, 3));
    Certainly.samesies(0, NumberUtilities.digitAt(-210, 0));
    Certainly.samesies(1, NumberUtilities.digitAt(-210, 1));
    Certainly.samesies(2, NumberUtilities.digitAt(-210, 2));

    Certainly.samesies(0, NumberUtilities.occurrences("Chris", 'p'));
    Certainly.samesies(1, NumberUtilities.occurrences("Chris", 'i'));
    Certainly.samesies(1, NumberUtilities.occurrences("Chris", 'i'));
    Certainly.samesies(2, NumberUtilities.occurrences("Marshall", 'a'));
    Certainly.samesies(2, NumberUtilities.occurrences("Marshall", 'l'));
    Certainly.samesies(1, NumberUtilities.occurrences("Marshall", 'M'));
    Certainly.samesies(0, NumberUtilities.occurrences("Marshall", 'm'));
  }
}

Certainly.java

package lecture1002.cs145;

public class Certainly {
  public static void samesies(int expected, int actual) {
    System.out.printf("%d == %d%n", expected, actual);
  }
}

NumberUtilities.java

package lecture1002.cs145;

public class NumberUtilities {
  public static int digitAt(int number, int place) {
    int shifted = Math.abs(number) / (int) Math.pow(10, place);
    int ones = shifted % 10;
    return ones;
  }

  public static int occurrences(String haystack, char needle) {
    int originalLength = haystack.length();
    int shortenedLength = haystack.replaceAll(needle + "", "").length();
    return originalLength - shortenedLength;
  }
}

Main.java

package lecture1002.cs148;

public class Main {
  public static void main(String[] args) {
    Certainly.samesies(6, NumberUtilities.digitAt(246, 0), "digitAt: Bad ones place!");
    Certainly.samesies(4, NumberUtilities.digitAt(246, 1), "digitAt: Bad tens place!");
    Certainly.samesies(2, NumberUtilities.digitAt(246, 2), "digitAt: Bad hundreds place!");
    Certainly.samesies(0, NumberUtilities.digitAt(246, 3), "digitAt: Bad thousands place!");
    Certainly.samesies(6, NumberUtilities.digitAt(-246, 0), "digitAt: Bad ones place for negative!");
    Certainly.samesies(4, NumberUtilities.digitAt(-246, 1), "digitAt: Bad tens place for negative!");
    Certainly.samesies(2, NumberUtilities.digitAt(-246, 2), "digitAt: Bad hundreds place for negative!");
    Certainly.samesies(0, NumberUtilities.digitAt(-246, 3), "digitAt: Bad thousands place for negative!");

    Certainly.samesies(0, NumberUtilities.count("What's up, Jo?", 'z'), "count: No occurrences");
    Certainly.samesies(1, NumberUtilities.count("What's up, Jo?", 'J'), "count: Single occurrence");
    Certainly.samesies(2, NumberUtilities.count("What's up, Jo?", ' '), "count: Two occurrences");
  }
}

Certainly.java

package lecture1002.cs148;

public class Certainly {
  public static void samesies(int expected, int actual, String message) {
    if (expected != actual) {
      throw new RuntimeException(String.format("%s%nExpected: %d%n  Actual: %d%n", message, expected, actual));
    }
  }
}

NumberUtilities.java

package lecture1002.cs148;

public class NumberUtilities {

  /**
   * Return digit at particular place in number.
   * @return A number 0-9 at given place.
   */
  public static int digitAt(int number, int index) {
    int shifted = Math.abs(number) / (int) Math.pow(10, index);
    int ones = shifted % 10;
    return ones;
  }

  public static int count(String text, char needle) {
    return text.length() - text.replaceAll(needle + "", "").length();
  }
}