Welcome back to an exciting journey into the world of Java! Today's itinerary includes "Function Chaining", the practice of calling a function within another and handling multiple return values using Java's Pair
and List
classes. Picture nested matryoshka dolls and a multi-handled briefcase, and you'll grasp the concepts!
Let's demystify "Function Chaining". Have you ever prepared a cup of coffee? You sequentially boil water, brew coffee, and add cream. Now, imagine these steps as functions: boilWater()
, brewCoffee()
, and addCream()
. If we chain these functions together, we have our prepareCoffee()
function — an apt illustration of function chaining!
Take a look:
Java1public static int doubleNumber(int number) { 2 return number * 2; // doubles the input 3} 4 5public static int addFive(int number) { 6 return number + 5; // adds 5 to the input 7} 8 9public static int doubleAndAddFive(int number) { 10 return addFive(doubleNumber(number)); // calls doubleNumber first, then addFive 11}
In doubleAndAddFive()
, doubleNumber()
is called first, and then its result fuels addFive()
. That's function chaining!
Now, let's dip our toes into function chaining. Consider the task of finding the square root of the sum of two numbers. We call sum()
inside sqrtOfSum()
, feeding its result to sqrt()
.
Java1public static void main(String[] args) { 2 System.out.println(sqrtOfSum(25, 25)); // prints the square root of the sum 3} 4 5static int sum(int a, int b) { 6 return a + b; // returns the sum 7} 8 9static double sqrt(int number) { 10 return Math.sqrt(number); // returns the square root 11} 12 13static double sqrtOfSum(int a, int b) { 14 return sqrt(sum(a, b)); // calls sum first, then sqrt 15}
Consider this scenario: a board game where throwDice()
simulates the throw of two dice and returns both results. But how do you return both values from the function? This is where Java's List class saves the day!
You can just return a List
from the function, and it can handle any number of values in it. Let's see on example:
Java1import java.util.*; 2 3static List<Integer> throwDice() { 4 Random rand = new Random(); 5 return Arrays.asList(rand.nextInt(6) + 1, rand.nextInt(6) + 1); // returns a list of two element the dice throws 6}
Here, we created an ArrayList
of two elements and provided it as a return value - easy and simple! You can access returned elements using the ArrayList::get
method after that.
Congratulations! You've delved into function chaining and learned how to handle multiple return values using the Pair
and the List
classes. Now, get ready for some fun practice exercises to reinforce your knowledge. Onwards, brave coder!