Interviewee
Interviewee

Reputation: 21

How do I refactor two classes with similar functionality?

I have classes with methods with the same names that do the same thing yet they are implemented differently.

Ex:

class converterA {
    map(Item1 item1) {
        // Implementation details.
    }

    convert(Item1 item1) {
        // Implementation details.
    }

    translate(Item1 item1) {
        // Implementation details.
    }
}

class converterB {
    map(Item2 item2) {
    // Implementation details.
    }

    convert(Item2 item2) {
    // Implementation details.
    }

    translate(Item2 item2) {
    // Implementation details.
    }
}

I considered using an interface but the issue is that is that the methods take in different parameters. Yet a template doesn't exactly fit either because Item1 and Item2 operate in different ways. In other words, they don't have common methods so a template doesn't exactly fit either.

Is there a solution here for refactoring the code?

Upvotes: 2

Views: 79

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106076

Given your comment "way to... have an interface styled class that can be extended", you might be interested in using templates to express the common "interface":

template <typename Item>
struct Converter
{
    virtual void map(Item) = 0;
    virtual void convert(Item) = 0;
    virtual void translate(Item) = 0;
};

class converterA : public Converter<Item1> {
    void map(Item1 item1) final { ... }
    void convert(Item1 item) final { ... }
    void translate(Item1 item) final { ... }
};
class converterB : public Converter<Item2> {
    ...same kind of thing...
};

All it buys you though is an expression of the "Converter" interface they share, some compile-time enforcement that the function signatures and names match that (e.g. if you change Converter<> you'll be reminded to update all the derived types), and the ability to handle the derived classes using pointer/references to the template instantiations they derive from (which is not of any ostensible use to you).

Upvotes: 1

JeffW
JeffW

Reputation: 1

I was thinking about using template specialization, but if they both use totally different methods it's not really worth it, although it would be more readable.

Upvotes: 0

Related Questions