💭 What is it?
Learners believe that a function’s return value must always come from a named variable, and that it’s not allowed to return a value directly using an expression.
For example, they assume the result of the calculation must first be stored in a variable and then returned:
int square(int x) {
int result = x * x; // Learners think the variable is necessary
return result;
}
As a result, they may think the following (perfectly valid) version is incorrect:
int square(int x) {
return x * x;
}
They believe that using an intermediate variable is mandatory, even when the value is only needed for the return statement.
🛠️ Why is it incorrect?
In Processing, it is perfectly valid to return a value directly using any expression that matches the function’s return type.
For example:
int doubleValue(int x) {
return x * 2;
}
Or:
boolean isEven(int value) {
return value % 2 == 0;
}
In the second example, the function returns true if the number is even, and false otherwise, without ever assigning the result to a named variable.
There is no requirement to declare a variable just to pass its value to return. In fact, returning expressions directly is often clearer, shorter, and easier to read, especially in simple cases.
That said, using a variable can still be useful when:
- the expression is long or complex,
- the value needs to be reused in the function,
- or naming the variable improves readability.
But it’s a style decision, not a rule.
🧩 Typical errors
- Declaring unnecessary variables just to hold the return value:
String getFullName(String firstName, String lastName) {
String name = firstName + " " + lastName;
return name;
}
🌱 Origin
This misconception may stem from early examples or exercises that always introduce a variable (e. g. result) before returning it. Over time, learners may mistakenly assume this pattern is a syntactic requirement rather than a stylistic convention.
Additionally, learners may overgeneralize from how values are handled in void functions, where results are stored in variables but not returned, and assume the same applies to returning values.
Some may also misunderstand the purpose of the return keyword itself, thinking it only works with declared variables, not with expressions.