Here are examples showing how you might (1) coalesce two similar functions using a "mode" flag, (2) break the common code out to a third function, and (3) make one function a proper subset of another, by having one function call the other.
(1) If you have two functions which are almost identical except for one little difference in the middle, like this:
function_1() function_2() { { common statement 1; common statement 1; common statement 2; common statement 2; different statement 3; different statement 4; common statement 5; common statement 5; common statement 6; common statement 6; } }
sometimes it's appropriate to coalesce the two functions, adding a "mode" flag telling it which of the two options to perform:
combined_function(int flag) { common statement 1; common statement 2; if(flag) different statement 3; else different statement 4; common statement 5; common statement 6; }
(2) If you have two functions where the common code is all together, with the differences around the edges, like this:
function_1() function_2() { { different statement 1; different statement 2; common statement 3; common statement 3; common statement 4; common statement 4; common statement 5; common statement 5; different statement 6; different statement 7; } }
you can often break the common code out to a third function, like this:
function_1() { different statement 1; function_3(); different statement 6; } function_2() { different statement 2; function_3(); different statement 7; } function_3() { common statement 3; common statement 4; common statement 5; }
(3) Finally, if one function is a subset of another, like this:
little_function(int a, int b) big_function(int a, int b, int c) { { common statement 1; common statement 1; common statement 2; common statement 2; common statement 3; common statement 3; } different statement 4; different statement 5; }
you can often have one function call the other. Sometimes it will look like this:
little_function(int a, int b) { common statement 1; common statement 2; common statement 3; } big_function(int a, int b, int c) { little_function(a, b); different statement 4; different statement 5; }
Or, sometimes, the extra code in the "big" function applies only if the extra parameter takes on some non-default value. In that case, sometimes you can make the little function a "wrapper" around the big one:
little_function(int a, int b) { big_function(a, b, default_value); } big_function(int a, int b, int c) { common statement 1; common statement 2; common statement 3; if(c != default_value) { different statement 4; different statement 5; } }