CS 145 Lecture 10 – Testing
Agenda
- what ?s
- method guess who
- what does this do?
- digitAtPlace
- interface vs. implementation
- test-driven development
Method Guess Who
- On your own, dream up a non-crazy one-line method. Let it accept one or two parameters. Return some value. (Non-crazy means use String or the primitives, but not Scanner or Random or convoluted expressions.)
- Pair up with a neighbor and take turns trying to figure out each other’s methods. Keep your method body a secret. Tell your neighbor what parameter types you accept. The neighbor feeds you various values for these parameters, and you report back the return value.
What Does This Do?
public class Mystery { public static void main(String[] args) { int n = 5; negate(n); System.out.println(n); } public void negate(int n) { n = -n; } }
Code
Mystery.java
package lecture0924;
public class Mystery {
public static void main(String[] args) {
int n = 5;
negate(n);
System.out.println(n);
}
public static void negate(int n) {
n = -n;
}
}
Digitizer.java
package lecture0924;
public class Digitizer {
public static void main(String[] args) {
// System.out.println(0 == getDigitAt(42, 100));
System.out.println(4 == getDigitAt(42, 10));
System.out.println(2 == getDigitAt(42, 1));
System.out.println(0 == getDigitAt(103, 10));
}
public static int getDigitAt(int n,
int place) {
// This implementation fails when callers ask for a
// place that's not explicitly defined in n. Like the
// 100ths place of 42.
String placeAsString = "" + place;
int nDigitsInPlace = placeAsString.length();
String s = "" + n;
int indexOfPlace = s.length() - nDigitsInPlace;
char c = s.charAt(indexOfPlace);
return c - '0';
}
public static int getDigitAtAlternative(int n,
int place) {
// This implementation is incomplete.
return n / place;
}
}
Haiku
on predestination:
Am I a function?
With many parameters?
Or is this free will?
Am I a function?
With many parameters?
Or is this free will?