teaching machines

CS 245 Lecture 1 – Hi and JUnit

January 21, 2014 by . Filed under cs245, lectures, spring 2014.

Agenda

TODO

Who Are You?

  1. Name?
  2. Where is home?
  3. Last unassigned book you read?
  4. If not computers, what? (Unacceptable answer: reinvent them.)

Black Box

What can you say about the following methods, based only their signatures? Propose a task they might accomplish.

Red-Green Refactor

  1. Red: think about a feature of your code that you want to support. Write a test to check the correctness of this feature’s implementation. In your code, write only a method signature and possibly a return statement. Just enough to make your code compile. Your test should fail. That’s good.
  2. Green: fix your implementation to make the test pass, but alter no other code. You might have great ideas about how to change parts of your code, but postpone any fixes until you have all tests passing again. That way you can verify that none of your changes break stuff.
  3. Refactor: now that all tests are passing, you can clean up any existing code. Rename. Simplify. Factor repeated code out into a method. Keep on testing to make sure you haven’t broken anything. When you are ready to add a new feature, return to step 1.

Code

IPAddress.java

package lecture01;

public class IPAddress {
  private String ip;

  public IPAddress(String ip) {
    this.ip = ip;
  }

  public String toString() {
    return ip;
  }

  public boolean isLocal() {
    return ip.startsWith("192.168.");
  }
}

TestIPAddress.java

package lecture01;

import org.junit.Assert;
import org.junit.Test;

public class TestIPAddress {
  @Test
  public void testConstructor() {
    IPAddress addy = new IPAddress("1.1.1.1");
    Assert.assertEquals("toString gave incorrect ip address", "1.1.1.1", addy.toString());
  }

  @Test
  public void testIsLocal() {
    IPAddress addy = new IPAddress("1.1.1.1");
    Assert.assertFalse(addy.isLocal());
    addy = new IPAddress("192.168.0.1");
    Assert.assertTrue(addy.isLocal());
  }
}

Haiku

I wanted a dog
Dad said no and licked my face
That’ll work, I guess