Question

How can I get rid of the code duplication in my vistUpper, visitDowner, visitX... functions? the only thing different in them is the creation of new WhateverAction(params)

I can make startVisit and endVisit functions which will reduce the length of the duplication, but the duplication will still be there... I was hoping there might be a more elegant way to do this?

    virtual void visitUpper(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new UpperAction(potion);
        actions.push_back(action);
        // add to our button list
    }
    virtual void visitDowner(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new DownerAction(potion);
        actions.push_back(action);
        // add to our button list
    }
    //    ... and some more visitX which are identical except new XAction ...
    void actOn(int actionIndex)
    {
        actions[actionIndex]->prepareDrink();
    }
Was it helpful?

Solution

You could try the following in your class:

private:
    template<typename T>
    void visit(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new T(potion);
        actions.push_back(action);
        // add to our button list
    }

 public:

    virtual void visitUpper(const Potion& potion)
    {
        visit<UpperAction>(potion);
    }
    virtual void visitDowner(const Potion& potion)
    {
        visit<DownerAction>(potion);
    }
    // more visitXXX ...

OTHER TIPS

Maybe something like this:

virtual void visitUpper(const Potion& potion)
{
    CommonCode(new UpperAction(potion));
}
virtual void visitDowner(const Potion& potion)
{
    CommonCode(new DownerAction(potion));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top