Introduction
This lesson will teach you about the importance of functions and how they are implemented in D.
We'll cover the following
Functions #
Similar to how fundamental types are building blocks of program data, functions are building blocks of program behavior.
Functions are also closely related to the craft aspect of programming. Functions that are written by experienced programmers are succinct, simple and clear. This goes both ways: the mere act of trying to identify and write smaller building blocks of a program makes for a better programmer.
We have covered basic statements and expressions in previous chapters. Although there will be many more statements in later chapters, what we have seen so far are commonly-used features of D. Still, they are not sufficient on their own to write large programs. The programs that we have written so far have all been very short, each demonstrating just a simple feature of the language. Trying to write a program with any level of complexity without functions would be very difficult and prone to bugs.
This chapter covers only the basic features of functions. We will see more about functions in a later chapter.
Function: A real-life analogy #
Functions are features that group statements and expressions together to form a unit of program execution. Together these statements and expressions are given a name that describes what they collectively achieve. This name can then be used to execute this unit of code.
This idea of giving names to a sequence of steps to do a task is common in our daily lives. For example, the act of cooking an omelet can be described in some level of detail as follows:
-
get a pan
-
get butter
-
get an egg
-
turn on the stove
-
put the pan on the fire
-
put butter into the pan when it is hot
-
put the egg into butter when it is melted
-
remove the pan from the fire when the egg is cooked
-
turn off the stove
Since that much detail is obviously excessive, steps that are related together would be combined under a single name:
-
make preparations (get the pan, butter and the egg)
-
turn on the stove
-
cook the egg (put the pan on the fire, etc.)
-
turn off the stove
Going further, there can be a single name for all of the steps:
- make a one-egg omelet(all of the steps)
Functions are based on the same concept: steps that can collectively be named as a whole are put together to form a function. As an example, let’s start with the following lines of code that achieve the task of displaying a menu:
Get hands-on with 1400+ tech skills courses.