Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of breaking a code into several small functions in C++? [closed]

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 ?

like image 521
Mody Avatar asked Nov 06 '12 17:11

Mody


1 Answers

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:

  1. 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.

  2. Code-reuse can aid in robustness and maintainability by isolating potential bugs to one place rather than several.

  3. 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.

  4. If you are opposed to functions with multiple return points, breaking big functions up can help reduce them.

  5. 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:

  1. If the big function worked before, trying to modularize it may create defects.

  2. In multithreadded applications, you might introduce deadlocks and race conditions if your synchronization policies are subtle or just plain wrong.

  3. You might introduce a performance hit from the function calls.

like image 122
John Dibling Avatar answered Oct 27 '22 09:10

John Dibling