This is just a general help question, I'm trying to know What is the advantage of having a set of small functions in a C++ application's code over having one long complex function containing all the statements necessary to solve a problem ?
Edit Credit for this mnemonic goes to the commenters in the OP.
Breaking big functions up in to several smaller ones can lead to MURDER! Which, in this case, might be a good thing. :)
M - Maintainability. Smaller, simpler functions are easier to maintain.
U - Understandability. Simpler functions are easier to understand.
R - Reuseability. Encourages code reuse by moving common operations to a separate function.
D - Debugability. It's easier to debug simple functions than complex ones.
E - Extensibility. Code reuse and maintainability lead to functions that are easier to refactor in 6 months.
R - Regression. Reuse and modularization lead to more effective regression testing.
There are a few potential benefits to breaking big functions up in to smaller functions. In the order they fell out of my brain:
It encourages code-reuse. Often in large functions you have to do more-or-less the same thing many times. By generalizing this in to a single common function, you can use that one block of code in multiple places.
Code-reuse can aid in robustness and maintainability by isolating potential bugs to one place rather than several.
It is easier to understand the semantics of the function when there are fewer lines of code and a bunch of calls to well-named functions.
If you are opposed to functions with multiple return points, breaking big functions up can help reduce them.
It helps to identify and isolate (potential) problems with subtle data dependencies that are otherwise hard to notice.
It's important to note however that you take the good with the bad with this. There are also a few potential drawbacks to breaking big functions up:
If the big function worked before, trying to modularize it may create defects.
In multithreadded applications, you might introduce deadlocks and race conditions if your synchronization policies are subtle or just plain wrong.
You might introduce a performance hit from the function calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With