There are two main reasons to put code into multiple functions:
- Abstraction/Encapsulation
- Reusability
Reusability is of course the simplest to explain. If I have a function:
int do_QWERTYalgo(int data1, int data2){ /*do stuff*/ }
Then obviously, if I need to do that workagain, I can just call the function from elsewhere , and "tada!" it's done, and I don't need to write it again.
Of course you know that, but have you thought about implementing a program where you need to do it multiple times with different intermediate steps?
//...a1 = 5;a2 = 7;a = do_QWERTYalgo (a1, a2);b1 = a;b2 = 8;b = do_QWERTYalgo (b1, b2);c = do_QWERTYalgo (a, b);
Suddenly, we've cut down a lot on the amount of code we need to write.
Additionally, if do_QWERTYalgo
was implemented incorrectly, we only need to change it in one single location now, which brings us nicely to our other point:
do_QWERTYalgo
is abstracted and encapsulated from the rest of the code.
The algorithm running above has no need to know how the do_QWERTYalgo
algorithm works, it just plugs in the inputs and recieves the output.
Also, should do_QWERTYalgo
need to change, as long as the inputs and outputs don't change, nothing else needs to change in the code.
To explain how this is meant to help you:lets say you are using a library to provide encrypted communication between yourself and a friend. Suddenly, there is news that the encryption method used is extremely vunerable to a new type of hack. Suddenly, there is a problem with your chat program. What do you do?Well, you grab an updated version of the library. Done. There may be dozens of places in your code where you use functionality provided by the library, but because the encryption functions are not embedded in your application code, you don't need to hunt down every single use and change it manually.
Another way of thinking about this:the function you are writing is a person. Said person wants to drive from A
to B
. So the person gets into the car
and puts input into the car
via the push_pedals
and turn_wheel
methods. With the correct inputs, the person gets to where they want to go.
Writing all your code in one big super method is like getting your person to implement the fuel_injection
functionality, the ignite_fuel
functionality, the gearbox
and clutch
functionalities, the turn_wheels_on_road_when_steering_wheel_turned
functionality, the push_pedals
, accellerate
, brake
functionalities, while also having to drive the car...
everything still happens as before, but there is a lot more work going on.
All code-folding does is hide some of that from your view, it's no better than giving your navigator a blindfold.