Thursday, October 18, 2018 19:55

Functions

Every person that ever wanted to become a programmer was at some point discouraged by one of the few things that makes programming so hard: its complexity. Whenever someone would want to code something like Skype, for instance, they would first of all feel overwhelmed about the incredibly complex task they face. Where to even begin?!

Well, programming has become so complex these days that no one could code a program from start to end in a single breath. What makes programming still human-doable is the old roman concept of divide et impera (divide and conquer). According to this old concept, the huge problem we are facing must be divided into smaller sub-problems , which can be much more easily solved. Taken separately, it is much more likely that one will be able to solve them and remember what each part was meant to do.

In our example, Skype could be divided into a few sub-parts (called subroutines), like: user interface; login/logout; getting and updating the friends list; updating presence and status; sending and receiving messages; etc, etc. Afterwards, its much more easy to deal with one of these parts, which we can eventually divide even more into sub-components.

This is where programming offers us two very useful concepts: functions and methods. What are they? At the most core concept, methods and functions are just a basic part of the program that was created to perform a single, specific task. The difference between methods and functions, as we will see later on, is that they both perform a certain task, but unlike methods, functions also return a result based on the performed task.

Methods and functions are the “functional” part of the programs, this where the “real job” gets done. This is the reason for which they are also called “base units” of a program. Without even knowing it, you’ve used a method in a lot of our examples, the method called Main.

This is an example of a simple method:

The keyword void tells the compiler that this block of code is a method, not a function. Another thing that indicates to us that this is a method, not a function, is that it does not use the return keyword. Functions MUST use the return keyword at least once inside their body (the area delimited by the curly brackets, also known as “block”). This is an example of a function:

Because our statement begins with the int keyword, this tells us three things: 1. this is not a method (it returns a value), but a function 2. the type of our function is of type int, which means the function must return an integer value 3. Our function must use the return keyword at least once.

There are a lot of other things about methods and functions, of which we will learn in the next lessons. Even if this lesson itself seems complicated and you didn’t understand much, don’t worry. It will all become clear once we start dissecting them in more detailed explanations.

Comments

comments

Tags: ,

Leave a Reply