2.1.10 Passing a Returned Value as an Argument

Video: Don't Drop the Baby (8:22)
Pass a Soccer Result into Another Method

A method call can supply an argument for another call. The inner method must finish its calculation before the receiving method can use that returned value.

The Wildcats application calculates points from wins, then passes those points to a method that adds a training bonus.

Follow the Result Between Calls
Pass a Soccer Result into Another Method.
Pass a Soccer Result into Another Method
  • New
  • Changed
  • Removed

The sequence diagram shows GetWinPoints completing before AddTrainingBonus begins. The value on the first return arrow becomes the argument on the next call. The final return sends the bonus-adjusted result to the original caller.

Connect the Calls in One Expression

Place all three methods in the same existing Game class. The first accepts a win count; the second accepts points. Keeping those meanings distinct helps you trace the handoff.

Pass a Soccer Result into Another Method
public int GetWinPoints(int wins)
{
    return wins * 3;
}

public int AddTrainingBonus(int points)
{
    return points + 1;
}

public int GetAward()
{
    return this.AddTrainingBonus(this.GetWinPoints(2));
}
Follow the Values and Execution Order

Start with the call inside the parentheses

this.GetWinPoints(2) receives 2 in its wins parameter. It multiplies by 3 and returns 6.

That 6 is the value available to use as the argument of the surrounding call.

Use types to check the handoff

GetWinPoints returns int and AddTrainingBonus accepts int. The returned value therefore fits the receiving parameter.

The shared soccer scenario alone is not enough; the value's type must also be compatible with the parameter.

Separate the calls when you want an intermediate pause

The calculation can also store the inner result in int points = this.GetWinPoints(2); and then execute return this.AddTrainingBonus(points);.

That version keeps the call order but gives you a local to inspect between the calls.

Follow one number through two meanings

The value 2 represents wins when it enters GetWinPoints. The returned 6 represents points when it enters AddTrainingBonus. The methods are related, but they do not receive the same input meaning.

Use the parameter names in the diagram and trace to explain that change. The combined statement saves a temporary local; it does not combine the two method bodies into one simultaneous calculation.

Trace This Example
Worked soccer trace
Order Operation Value
1 GetWinPoints receives wins 2
2 GetWinPoints returns 6
3 AddTrainingBonus receives points 6
4 AddTrainingBonus returns 7
5 GetAward returns to its caller 7
Try a Focused Change
Predict and Explain

Check your reasoning

GetWinPoints returns 0 because zero wins produce zero points. AddTrainingBonus receives that 0 and returns 1. GetAward returns 1 to its caller.