gpalex
gpalex

Reputation: 852

Specializing a function's behavior depending on caller/context

Say you have a program in which 2 pieces of old code do the same work, except they do it in two different contexts: one does it in a GUI, the other one in an API. Say you want to refactor them in order to pool/merge the code, so that you only have one code doing the work for both the API & the GUI.

But there's an issue: the pieces of code are not 100% identical. The GUI has to do some additional work compared to the API (for instance in the GUI, each changes made must pass through the undo/redo system, but not in the API since it does not use the undo/redo).

So say you can merge 80% of the behavior of your piece of code, but you're left with 20% that must be specialized for API vs GUI (ie. can't be pooled/merged by definition).

How would you solve that?

I thought about:

But none of these solution satisfy me:

Any other idea anyone?

Upvotes: 0

Views: 160

Answers (3)

caps
caps

Reputation: 1243

It also sounds like the only differences are things that the GUI does that the API does not do. If there are things the API does that the GUI does not do, that will affect the answer.

--

If there is any way to refactor your code so that all of the special case stuff happens in the same code block, you could put that code block in a function for the GUI which then calls the "common" function afterward.

void GUI_Func()
{
    //do some special GUI stuff

    common_func();
}

void common_func()
{
    //do stuff common to both the GUI and the API
}

--

However, it sounds to me like you have the different functionality scattered throughout the function by necessity.

You mentioned an Undo/Redo system. Could that code be moved into a class responsible for handling Undoing and Redoing? In that case, you could template the function on template<typename UndoRedo>. For the GUI form you would pass in your Undo/Redo class, for the API form you would pass in an empty class with a matching interface; albeit empty of any functionality. At compile-time the empty class operations would be no-ops and would possibly be elided away by the compiler.

Upvotes: 1

Marco
Marco

Reputation: 2020

In your place I would think about delegation, you put all the code that is UI related in this delegate class.

Upvotes: 0

Muhammad Khan
Muhammad Khan

Reputation: 425

I'm not sure I understand to what scale your code is complicated, but for certain situations like these I would pass in an optional boolean parameter which when true would make the extra stuff happen. Again, not entirely sure if that is suitable for this situation. In this case, the GUI would call the common function with the parameter set to true and the API version would call the common function with the parameter set to false.

Upvotes: 0

Related Questions