As a program grows, complexity grows. If the code cannot handle this growth, it is easy to become bogged down in the complexity of application. The best way to manage our code is to break it down into small, self-contained portions and the complex problem can be solved by putting these portions together. Kotlin can help us to divide our code into small chunks, and we can then assign a meaningful name to our code. That block can perform one particular task for us. In different programming languages, this technique is called a method, subroutine, or procedure. In Kotlin, this technique is called a function.
There are several reasons for dividing code into functions:
- Divide and conquer: A programmer can solve a complex task by dividing it into small functions.
- Reusability: Pasting similar code in different places is not a good approach. In the future, if a program's logic changes, we must update the pasted code everywhere else. Functions help us to reuse code anywhere in our program, and if the function code changes, it will have an effect in all areas.
- Debugging: With big, complex problems, if the code does not work as expected, it is often difficult to find the hidden bug in spaghetti code. Without well-defined functions, it is a difficult, frustrating, and time-consuming task to fix the problem. If everything is divided into functions, a coder can test each function one by one in order to confirm its output.
- Abstraction: In order to use a function, it is enough to know its name and parameters. The programmer does not need to know how it is implemented and what logic is used by another programmer.