Remember how methods helped us avoid copying and pasting code? That was great! But as our programs grow bigger, we’re running into a new problem: too many separate variables that really belong together.
// We have to pass everything one by one
public static int increaseHealth(int currentHealth, int healAmount) {
return currentHealth + healAmount;
}
public static int increaseGold(int currentGold, int goldReward) {
return currentGold + goldReward;
}
Checkpoint3.3.1.Multiple Choice: Why Too Many Separate Pieces Is a Problem.
In the "Method Parameters" section, we compared carrying many separate school items to storing many separate player stats. Which statement below best captures why this approach can cause issues?
If two method parameters have the same type, swapping them by accident (e.g., passing playerGold where playerHealth is expected) will still compile and could lead to unexpected behavior at runtime.
True.
The compiler won’t stop you if the swapped parameters are both the same type, making it a silent but dangerous error.
False.
The compiler won’t stop you if the swapped parameters are both the same type, making it a silent but dangerous error.
In the section, we saw how having player1Health, player2Health, player1Gold, player2Gold, and so on can get “out of hand.” In 1-2 sentences, explain why managing multiple players with separate variables becomes difficult. Feel free to reference the “backpack” analogy.
Sample Solution: Each player has several stats to track, so using a separate variable for each stat (like player1Health, player2Health, etc.) quickly leads to long parameter lists and confusion. Bundling them into a single structure (a “backpack” or a Player class) simplifies both method calls and data organization.
Checkpoint3.3.4.Multiple Choice: The transferMoney Example.
Consider the method signature public static void transferMoney(int fromBalance, int toBalance, int amount). Which of the following best describes the biggest risk with this approach?
We saw a hint of a Player class that might hold health, gold, xp, etc. In 2-3 sentences, describe why bundling these stats into a single object could make code easier to maintain, before we even learn the full syntax of classes.
Sample Solution: One object can store all the player’s related data, so we don’t have to pass a dozen parameters whenever we modify or read stats. It also reduces the risk of mixing up parameter order. Once we have an object, we can define methods like p1.increaseHealth(5) that automatically update the right fields, making the code more organized and less error-prone.