Why Functions


Now that we've learned about functions, let's see why they are so important in our programmers' life:

Consider this: A student named Andy made a mistake and so his teacher told him to write this text 3 times on the whiteboard:

This is Andy
Andy made a mistake
Andy suffers the consequences

We would put this in a simple program like this:

System.out.println("This is Andy");
System.out.println("Andy made a mistake");
System.out.println("Andy suffers the consequences");

System.out.println("This is Andy");
System.out.println("Andy made a mistake");
System.out.println("Andy suffers the consequences");

System.out.println("This is Andy");
System.out.println("Andy made a mistake");
System.out.println("Andy suffers the consequences");

That's manageable. But what if the text consisted of more than 3 lines? And what if the teacher asked Andy to print it for 10 times or 100 times?

You can imagine that our code would get super long while executing 3 different instructions overall.


The story with functions:

This is where functions shine. We can write a function that prints the desired text and then just call the function for as many times as the teacher asks to:

void printMessage() {
	System.out.println("This is Andy");
	System.out.println("Andy made a mistake");
	System.out.println("Andy suffers the consequences");
}

printMessage();
printMessage();
printMessage();

Changing the story:

Need to print the text 3 more times? We call the function 3 more times instead of adding 9 lines to our program.

Need to change the student's name to Mike? We only change it inside the function instead of changing it in the whole program.

void printMessage() {
	System.out.println("This is Mike");
	System.out.println("Mike made a mistake");
	System.out.println("Mike suffers the consequences");
}

printMessage();
printMessage();
printMessage();
printMessage();
printMessage();

Note:

If you still don't like this code, especially the fact that we have 5 duplicate lines of code: printMessage(), you are correct! We will learn how we can make this even better with loops!


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


Introduction

Functions are a fundamental concept in programming that allow us to encapsulate code into reusable blocks. They are significant because they help in reducing redundancy, improving code readability, and making maintenance easier. Functions are particularly useful in scenarios where a specific task needs to be performed multiple times throughout a program.

Understanding the Basics

At its core, a function is a block of code designed to perform a particular task. Functions can take inputs, known as parameters, and can return a value after execution. Understanding these basics is crucial before diving into more complex aspects of functions.

For example, consider a simple function that adds two numbers:

public int add(int a, int b) {
    return a + b;
}

This function takes two integers as parameters and returns their sum.

Main Concepts

Key concepts related to functions include:

Let's apply these concepts with an example:

public class Main {
    public static void main(String[] args) {
        printMessage();
        printMessage();
        printMessage();
    }

    public static void printMessage() {
        System.out.println("This is Andy");
        System.out.println("Andy made a mistake");
        System.out.println("Andy suffers the consequences");
    }
}

In this example, printMessage is defined once and called three times, demonstrating how functions can reduce code duplication.

Examples and Use Cases

Consider a scenario where you need to calculate the area of different shapes. Instead of writing separate code for each shape, you can use functions:

public class Shapes {
    public static void main(String[] args) {
        System.out.println("Area of circle: " + areaOfCircle(5));
        System.out.println("Area of rectangle: " + areaOfRectangle(4, 5));
    }

    public static double areaOfCircle(double radius) {
        return Math.PI * radius * radius;
    }

    public static int areaOfRectangle(int length, int width) {
        return length * width;
    }
}

Here, we have two functions, areaOfCircle and areaOfRectangle, each performing a specific task.

Common Pitfalls and Best Practices

Common mistakes include not using functions to avoid code duplication and not properly naming functions. Best practices include:

Advanced Techniques

Advanced techniques include recursion, higher-order functions, and lambda expressions. For example, recursion is a technique where a function calls itself:

public class RecursionExample {
    public static void main(String[] args) {
        System.out.println("Factorial of 5: " + factorial(5));
    }

    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}

Recursion can be powerful but should be used with caution to avoid infinite loops.

Code Implementation

Let's revisit our initial example and improve it using loops:

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            printMessage();
        }
    }

    public static void printMessage() {
        System.out.println("This is Mike");
        System.out.println("Mike made a mistake");
        System.out.println("Mike suffers the consequences");
    }
}

This code uses a loop to call printMessage five times, further reducing redundancy.

Debugging and Testing

When debugging functions, ensure that the inputs and outputs are as expected. Use print statements or a debugger to trace the function's execution. Writing tests for functions can help ensure they work correctly:

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class FunctionTest {
    @Test
    public void testAdd() {
        assertEquals(5, add(2, 3));
    }

    public int add(int a, int b) {
        return a + b;
    }
}

This test checks if the add function returns the correct sum.

Thinking and Problem-Solving Tips

When approaching problems, break them down into smaller tasks that can be handled by individual functions. Practice by solving coding exercises and building small projects to improve your understanding of functions.

Conclusion

Functions are a powerful tool in programming that help in writing clean, efficient, and maintainable code. Mastering functions is essential for any programmer, and continuous practice will help in understanding their applications better.

Additional Resources