Program design means planning a class before you code it: list what each object must remember and must do, then write a header for each job. You split large jobs into smaller methods, state what each method assumes and promises, and test the design by tracing calls on chosen inputs. This is how you plan any class in AP® Computer Science A.
Quick check
In the header public int addTwo(int x), what is the return type and what is the parameter?Show answerHide answer
The return type is
intand the parameter isint x: the method receives oneintand gives back anint.A comment above a method says "Precondition: n > 0". Must the method's code check that n is positive?Show answerHide answer
No. A precondition is a promise made by the calling code, so the method may assume it.
Know these already? Jump to the practice questions
What you'll be able to do
- Identify the state and behaviors a specification needs.
- Choose a header that matches each behavior.
- Explain why helper methods help.
- Use preconditions and postconditions to judge code.
- Determine what a sequence of calls prints by tracing.
Key terms
State
The data an object remembers between method calls, held in its instance variables.
- In plain English
- What the object knows right now.
- Don't write
- "A local variable is part of the object's state."
Procedural abstraction
Putting a task's steps in a method that other code calls, relying on what it does, not how.
- In plain English
- Wrap a job in a method once, then just call it.
- Don't write
- "Abstraction means making variables private."
Precondition
A condition that must be true when a method is called, which the method may assume.
- In plain English
- The caller's promise.
- Don't write
- "The method must test its precondition."
Postcondition
What is true when a method ends, if its preconditions held: its return value or how the state changed.
- In plain English
- The method's promise.
- Don't write
- "A postcondition is checked before the method runs."
How do you turn a specification into a class?
A specification describes in words what a class must do. Read it twice. First, mark the facts each object must remember between calls: these become private instance variables. Then mark what it must do or answer: each such behavior becomes a method, or the constructor.
A BusPass holds a number of rides, set when bought. Tapping uses a ride if any are left and reports whether the rider may board. Topping up adds rides, and the rider can ask how many are left.
| In the specification | Becomes |
|---|---|
| number of rides | instance variable ridesLeft |
| set when bought | constructor with an int parameter |
| tapping | method tap |
| top-up | method topUp |
| how many are left | method getRidesLeft |
Store only what can't be worked out from other state. A second variable hasRides could fall out of step with ridesLeft; the expression ridesLeft > 0 is always right.
Key idea
Facts the object must remember become instance variables; things it must do or answer become methods.
Check yourself
Show answerHide answer
One boolean, such as private boolean isOn;, because the lamp must remember which state it is in between presses.
How do you choose each method's header?
A header fixes the return type, the name and the parameters (variables that receive values from the caller). Ask two questions.
- What does the caller get back? A behavior that answers a question returns that type; one that only changes the state returns
void. - What must the caller supply? Information the object doesn't hold becomes a parameter.
BusPass behavior | Header |
|---|---|
| tap | public boolean tap() |
| top up | public void topUp(int rides) |
| rides left | public int getRidesLeft() |
tap answers "may the rider board?", so it returns a boolean; it needs no parameter because a tap always uses one ride. Methods that other classes call are public and instance variables private, so outside code changes state only through methods.
Examiner's eye
Marks go to headers that match the specification exactly. A method that prints a value it should return does not meet the specification.
Check yourself
Show answerHide answer
public double getReading(): it returns a decimal and needs nothing from the caller.
Why split a task into smaller methods?
Splitting a task into methods is procedural abstraction. A helper method does part of another method's job, and the caller relies on the helper's comment, not its code.
/** Precondition: 0 <= n <= 99
* Postcondition: returns n as a 2-character String,
* with a leading "0" when n < 10
*/
private static String twoDigits(int n)
{
if (n < 10)
{
return "0" + n;
}
return "" + n;
}
/** Precondition: 0 <= totalSeconds < 6000
* Postcondition: returns the time as "mm:ss"
*/
public static String formatTime(int totalSeconds)
{
int minutes = totalSeconds / 60;
int seconds = totalSeconds % 60;
return twoDigits(minutes) + ":" + twoDigits(seconds);
}
formatTime(125) sets minutes to 2 and seconds to 5, calls the helper twice and returns "02:05". The padding rule is written once, so a fix happens in one place, and each method is short enough to test alone. The helper is private because only its own class uses it.
Check yourself
Show answerHide answer
"00:59". minutes is 0 and seconds is 59.
What do preconditions and postconditions promise?
Together they form a contract, written as a comment above the method.
- The precondition is the caller's side.
twoDigitsmay assume0 <= n <= 99, so it has no code to reject 150; a caller who breaks it is promised nothing. - The postcondition is the method's side: for every
nthat meets the precondition,twoDigitsreturns a 2-character string.
Because formatTime requires totalSeconds < 6000, minutes is at most 99, so both helper calls meet the helper's precondition.
A method is correct when its postcondition holds for every input that meets its precondition, so test the edges of the allowed range: for twoDigits, try 0, 9, 10 and 99.
Check yourself
Show answerHide answer
No. The argument 150 breaks the precondition, so the fault lies with the caller.
Worked example 1: Design a class and test it by tracing
Question: Design a ReadingLog class from this specification, then state what the test code prints. A reading log tracks progress toward a page goal set at creation. The reader can add pages read, ask how many pages are left (never below 0) and ask whether the goal is met.
ReadingLog log = new ReadingLog(100);
log.addPages(30);
log.addPages(45);
System.out.println(log.pagesLeft());
log.addPages(40);
System.out.println(log.pagesLeft());
System.out.println(log.goalMet());
What tells you the method
A specification plus test calls: design the class, then trace the calls.
Step 1: List the state and the behaviors.
State:
intvariablesgoalandpagesRead. Behaviors: a constructor and three methods.WhyPages left can be worked out from the goal and the running total, so it is not stored.
Step 2: Write the class, reusing one method inside another.
public class ReadingLog { private int goal; private int pagesRead; /** Precondition: g > 0 */ public ReadingLog(int g) { goal = g; pagesRead = 0; } /** Precondition: pages > 0 * Postcondition: pagesRead has increased by pages */ public void addPages(int pages) { pagesRead += pages; } /** Postcondition: returns goal - pagesRead, * or 0 if that would be negative */ public int pagesLeft() { if (pagesRead >= goal) { return 0; } return goal - pagesRead; } public boolean goalMet() { return pagesLeft() == 0; } }WhygoalMetreusespagesLeft, so the "never less than 0" rule is written once.Step 3: Trace the test calls.
Call goalpagesReadPrinted constructor 100 0 addPages(30)100 30 addPages(45)100 75 pagesLeft()100 75 25 addPages(40)100 115 pagesLeft()100 115 0 goalMet()100 115 true WhyOnly
addPageschanges the state. Since 115 ≥ 100,pagesLeftreturns 0, not −15.
Check it
At the boundary, a goal of 50 with exactly 50 pages read makes 50 >= 50 true, so goalMet() returns true.
Answer
25 then 0 then true
Worked example 2: Choose the code that meets a postcondition
Question: This method is added to the ReadingLog class from Worked example 1. Which code segment can replace /* missing code */?
/** Precondition: perDay > 0
* Postcondition: returns the fewest whole days needed
* to read the pages left at perDay pages a day
*/
public int daysToFinish(int perDay)
{
/* missing code */
}
- A)
return pagesLeft() / perDay; - B)
return (pagesLeft() + perDay - 1) / perDay; - C)
return pagesLeft() / perDay + 1; - D)
return (goal + perDay - 1) / perDay;
What tells you the method
"Which code segment" plus a postcondition: test every option on valid inputs.
Step 1: Choose test inputs.
Let
pagesLeft()be 25 (goal 100, 75 read). ThenperDay= 10 needs 3 days andperDay= 5 needs exactly 5.Whyint / inttruncates, so exact and inexact divisions can behave differently.Step 2: Trace each option.
Option perDay= 10perDay= 5A 25 / 10 = 2 25 / 5 = 5 B 34 / 10 = 3 29 / 5 = 5 C 2 + 1 = 3 5 + 1 = 6 D 109 / 10 = 10 104 / 5 = 20 WhyA drops the last part-day, C adds a day to an exact division, and D ignores pages already read.
Check it
When the goal is met, pagesLeft() is 0, so B gives 9 / 10 = 0 days, which is right; C would give 1.
Answer
B
Your turn
Question: Here is the BusPass class written in full. What is printed when the test code runs?
public class BusPass
{
private int ridesLeft;
public BusPass(int rides)
{
ridesLeft = rides;
}
public boolean tap()
{
if (ridesLeft > 0)
{
ridesLeft--;
return true;
}
return false;
}
public void topUp(int rides)
{
ridesLeft += rides;
}
public int getRidesLeft()
{
return ridesLeft;
}
}
BusPass p = new BusPass(2);
p.tap();
p.tap();
System.out.println(p.tap());
p.topUp(5);
p.tap();
System.out.println(p.getRidesLeft());
Step 1: Trace the first two taps.
ridesLeftstarts at 2, and each tap findsridesLeft > 0and subtracts 1, so it ends at 0. Nothing is printed yet.Step 2: Your go: trace the third tap, the top-up and the last tap, then write both printed lines.
Show the full solutionHide the solution
Step 2. The third tap finds 0 > 0 false, so ridesLeft stays 0 and tap returns false, which is printed. topUp(5) makes ridesLeft 5, the last tap makes it 4, and getRidesLeft() returns 4, which is printed.
Answer: false then 4 on the next line.
Traps
Trap
A method must test its own precondition and reject bad input.
It seems right because extra checks look safer. But a precondition is the caller's promise, so the method may assume it and needs no checking code.
A method's precondition is amount > 0. Does its code need an if statement that rejects amount <= 0?
No. Making amount > 0 true is the caller's job.
Trap
Printing a value does the same job as returning it.
It seems right because both show the value in a test. But "returns" means the caller gets the value back to use; printing gives the caller nothing.
A specification says getTotal returns the int total. Does a void getTotal method that prints total meet it?
No. It needs the header public int getTotal() and the statement return total;.
What's examined
On the AP® Computer Science A exam, program design belongs to Unit 3 (Class Creation). Multiple-choice questions can ask which header or code segment fits a specification, or what a sequence of calls prints. One of the four free-response questions is a class design question: you write a whole class from a specification, judged on whether it does what the specification says, with the names and headers given.
Practice questions
- Recall Which statement describes a precondition?
- A) A condition the caller must make true before calling the method
- B) A condition the method guarantees is true when it returns
- C) A condition the method must test, printing an error if it fails
- D) A condition that must hold for the class to compile
Show answer
Answer: A. A precondition is the caller's side of the contract.
Why the others are wrong:
- B describes a postcondition, the method's side of the contract.
- C treats the precondition as something the method checks, when the method may simply assume it.
- D confuses a precondition with Java's syntax rules; code that breaks a precondition still compiles.
- Apply A
Thermostatremembers a target temperature, a whole number of degrees that starts at 20. Pressing up or down changes the target by 1, and the thermostat can report its target. Which instance variable declaration fits this design?
- A)
private boolean up; - B)
public int target; - C)
private int target; - D)
private String target;
Show answer
Answer: C. The one fact the thermostat must remember is a whole number, so it needs a private int.
Why the others are wrong:
- A turns a behavior, pressing up, into state; pressing is a method, not something remembered.
- B makes the state public, so outside code could change the target without using the methods.
- D stores a number as text, so the methods could not add 1 to it.
- Apply What is printed when the code after this class runs?
public class Score
{
private int points;
private int streak;
public Score()
{
points = 0;
streak = 0;
}
public void hit()
{
streak++;
points += bonus();
}
public void miss()
{
streak = 0;
}
private int bonus()
{
return streak * 10;
}
public int getPoints()
{
return points;
}
}
Score s = new Score();
s.hit();
s.hit();
s.miss();
s.hit();
System.out.println(s.getPoints());
Show answer
Answer: 40
Marking points:
- First
hit:streakbecomes 1, thenbonus()returns 10, sopointsis 10. - Second
hit:streakis 2 andpointsis 10 + 20 = 30. misssetsstreakto 0; the lasthitmakesstreak1 andpoints40.
- Apply What value does the expression
score(37) + score(60)have?
public static int clamp(int value, int low, int high)
{
if (value < low)
{
return low;
}
if (value > high)
{
return high;
}
return value;
}
public static int score(int raw)
{
return clamp(raw * 2, 0, 100) / 10;
}
Show answer
Answer: 17
Marking points:
score(37):clamp(74, 0, 100)returns 74, and 74 / 10 is 7 in integer division.score(60):clamp(120, 0, 100)returns 100, and 100 / 10 is 10.- 7 + 10 = 17.
- Exam-style In a
Batteryclass,chargeis a privateintinstance variable. The method below has the preconditionamount > 0and this postcondition: ifchargeis at leastamount,chargedecreases byamountand the method returnstrue; otherwisechargeis unchanged and it returnsfalse. Give the number of the line that stops the method meeting its postcondition.
1: public boolean use(int amount)
2: {
3: if (charge > amount)
4: {
5: charge -= amount;
6: return true;
7: }
8: return false;
9: }
Show answer
Answer: Line 3.
Marking points:
- When
chargeandamountare both 30, the postcondition says the method should use the charge and returntrue, but30 > 30is false, so it returnsfalse. - Changing line 3 to
if (charge >= amount)fixes it:chargebecomes 0 and the method returnstrue.
- Exam-style The method
clockTimemust use the helpertwoDigits. Which code segment can replace/* missing code */?
/** Precondition: 0 <= n <= 99
* Postcondition: returns n as a 2-character String
*/
private static String twoDigits(int n)
{
if (n < 10)
{
return "0" + n;
}
return "" + n;
}
/** Precondition: 0 <= mins < 1440
* Postcondition: returns the time as "hh:mm";
* for example, 75 gives "01:15"
*/
public static String clockTime(int mins)
{
/* missing code */
}
- A)
return mins / 60 + ":" + mins % 60; - B)
return twoDigits(mins % 60) + ":" + twoDigits(mins / 60); - C)
return twoDigits(mins / 60) + ":" + twoDigits(mins); - D)
return twoDigits(mins / 60) + ":" + twoDigits(mins % 60);
Show answer
Answer: D. For 75 it returns twoDigits(1) + ":" + twoDigits(15), which is "01:15".
Why the others are wrong:
- A skips the helper, so 75 gives "1:15" with no leading zero.
- B swaps hours and minutes, so 75 gives "15:01".
- C passes all the minutes instead of the remainder, so 75 gives "01:75"; any
minsabove 99 also breaks the helper's precondition.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Facts an object must remember become private instance variables; jobs it must do or answer become methods.
- Don't store a value you can compute from other state: compute it when asked.
- The return type comes from what the caller gets back (
voidif nothing); the parameters come from what the caller must supply. - Helper methods hold one task each, so a rule is written once and each piece can be tested alone.
- A precondition is the caller's promise; a postcondition is the method's promise for every input that meets the precondition.
- Test a design by tracing calls on stated inputs, including values at the edges of the allowed range.