Unit 06 · lesson
Parameters Cross a Boundary; Local Variables Stay Local
A method receives information through parameters.
int addBonus(int score, int bonus) {
int adjusted = score + bonus;
return adjusted;
}
Inside the method:
scoreandbonusare parameter variables;adjustedis local state;- the returned
intcrosses back out to the caller.
Scope limits where a name exists
This will not work:
int addBonus(int score, int bonus) {
int adjusted = score + bonus;
return adjusted;
}
void main() {
IO.println(adjusted);
}
adjusted exists only inside the method's scope.
That is useful. Local state cannot be accidentally read or changed from everywhere in the program.
Same name, different variable
int doubleValue(int value) {
int result = value * 2;
return result;
}
void main() {
int value = 5;
int doubled = doubleValue(value);
IO.println(value);
IO.println(doubled);
}
The caller's value and the parameter named value are distinct variables in different scopes.
Passing the integer gives the method the value it needs. Reassigning the parameter inside the method would not rename or reassign the caller's local variable.
Object references will make this conversation more interesting later. For now, keep the boundary clear.
Parameters are inputs, not a dumping ground
A method with ten loosely related parameters often signals that a larger concept has not been modeled yet.
This is hard to reason about:
createUser(name, grade, email, id, active, role, room, adviser, points, warnings)
Later, an object can group state that belongs together. Do not solve the problem early with a mystery array or a giant string.
Pure calculation versus hidden state
A method like:
int square(int value) {
return value * value;
}
is easy to reason about because its output depends on explicit input.
A method that silently reads and changes shared state has more hidden dependencies. That does not make shared state forbidden, but it raises the evidence burden.
Scope experiment
Create:
int adjust(int value) {
value = value + 10;
int internal = value * 2;
IO.println("inside value=" + value);
return internal;
}
void main() {
int value = 5;
int result = adjust(value);
IO.println("outside value=" + value);
IO.println("result=" + result);
}
Predict all three outputs before running.
Then answer:
- which
valuechanges insideadjust? - why does the caller's
valueremain 5? - why can
mainnot printinternaldirectly?
Evidence
Draw a boundary around one method from your own code. Put parameters on arrows entering, the return value on an arrow leaving, and local variables inside the box.
If you cannot draw the boundary cleanly, the method's responsibility may still be unclear.