A suggestion on how to handle this situation
Posted by Boteon@reddit | learnprogramming | View on Reddit | 3 comments
Imagine a situation in which a function (fun1) you have written a function that does something specific.
Now, you need another function (fun2) in which the code of fun1 is almost perfect, except for the output type. The main problem is that the output is created within a for loop (see below), thus I cannot create a sub-function that can be called from both fun1 and fun2.
Here is my question: how should I handle this? stick with copying fun1 and editing the output for fun2 or are there any other strategies?
If it helps, this is Matlab
ncut = 0;
for kk = 1:length(seq)
if kk == 1 % Esx
w = wEsx;
elseif kk == length(seq) % Edx
w = wEdx;
else % I
w = wI;
end
if all(w~=seq(kk))
ncut = ncut+1; %%% THIS IS THE OUTPUT OF fun1 WHICH MUST BE CHANGED FOR fun2
end
end
mierecat@reddit
If
function_1
returnsxyz
andfunction_2
returnsxyc
then just make a function that returnsxy
and decide the final element somewhere else.But you haven’t explained your problem well enough so idk what to tell you
EsShayuki@reddit
Depends on what you want to do with it in the future, and how you want to evoke the function.
In C, I could, for instance, return a void* and cast it to the correct value, or I would edit the target variable directly with the appropriate pointer without the caller having to know about any of it. Or I could use a function pointer as a callback parameter to decide whether to use function 1 or function 2, or I could use if-else to choose between the right one to call, too.
The solution you choose depends on what you want to do and at which point.
In general, by the way, copying 90% of the function is usually the wrong thing to do. In this case, it's usually better to split it into two parts. In practically every case, being able to copy 90% of a function and just swapping one part of it violates the "single responsibility principle" because if you then have to copy that initial part, you must make the same change in every single function instead of just doing it in one location.
Make all your functions do only one thing, and don't worry about making too many functions.
chaotic_thought@reddit
So, if I understood properly, in fun1 you "DON'T" want to do the "if CONDITION ncut=ncut+1", and in fun2 you "DO" want to do that.
So, why not just make your fun1 take a parameter that lets the caller choose whether she wants to do the conditional ncut increment or not. If your language supports "default parameters" you can make the default behaviour equivalent to what you're currently doing in fun1.