Explaining why methods are important
Methods are code blocks that are given a name for ease of reference. They can accept inputs and return an output. Both the inputs and output are optional. A method should do one task and do it well. It is considered good practice to keep your methods short (less than 20 lines). The longer the method, the more likely it is that the method is doing too much. The maxim of “keep it simple” applies here.
Flow of control
Simply put, when a method is called (executed), the normal flow of control of execution is changed. Let us discuss a simple example that will help demonstrate this. This is an important point to appreciate, especially for inexperienced developers. Figure 7.1 presents the code:
Figure 7.1 – A very simple method
In this example, we have two methods: the main()
method (lines 4 to 8) and the simpleExample()
method (lines 9 to 11). Both exist inside the Methods
class (lines 3 to 12)...