Between an If and a Copy/Paste

Braid_final_rot

What to do if you have two functions that do almost the same but not exactly the same? Make one function and handle differences with if statements or make two functions and copy the code? Is there the third option? We had this dilemma yesterday with Hamax on the case of function with 30 lines of code. The function in question is quite standard. It first checks input parameters, then it prepares and executes a request to an external service, and finally it generates and returns a result, or handle any exceptions. Depending on a particular input parameter, the functions differ in preparation of the request and generation of the result. Using if statements produces convoluted code that it's hard to read and error prone. But duplicating code and having two separate functions is even harder to support. Namely, any change in the duplicated code must be applied twice, which is time consuming and even more error prone. Alternatives do exists, but are even less compelling. The first alternative is to split the original function into constituent pieces and than compose the functionality in two new functions. This looks compelling but only until you realize that functionality is now scattered over seven functions. Another alternative is to wrap functionality that differs into a new function and pass this new function as a parameter to the original function. While such solution is fine for the cases where the two functions differ in one place only, it immediately gets convoluted with two or more distinct places.

It might very well be that no better option exists than the ones enumerated above and that this dilemma is intrinsic to programming. But if you have some ideas yourself, please, describe them in comments.

Enhanced by Zemanta