dguan
dguan

Reputation: 1033

which is better OO practice?

I need advice on how to design an interface, the problem is simplified like this:

I have to design a set of checking classes for some classes, at first there is only one class to be checked, now I need to do checking for a new class which requires a new interface, something like this:

In the beginning,

Class Base{ blah;};
Class D1 public Base {...};
Class IChecker { virtual bool CheckIt(Base*) = 0; };
Class Checker1 public IChecker;
Class Checker2 public IChecker;
......

Now I need to check on a new class:

Class D2 public Base {...};

To check this D2, I need a different interface

virtual bool CheckIt(const vector<unique_ptr<Base>> &) = 0;

My Question is, which is a better OO design, Should I implement a aggregated IChecker

class IChecker{
    virtual bool CheckIt(Base*) = 0;
    virtual bool CheckIt(const Vector<unique_ptr<Base>>&) = 0;
}
class Checker1 public IChecker {};
class Checker2 public Ichecker {};
......

Or Should I make two ICheckers for each types to be checked:

class ICheckerD1 { virtual bool CheckIt(D1*) = 0; }

and

class IcheckerD2 { virtual bool CheckIt(vector<unique_ptr<D2>>&) = 0; }

This time the solid checkers will look like this:

class Checker1D1 public ICheckerD1 {};
class Checker2D1 public IcheckerD1 {};
class Checker1D2 public IcheckerD2 {};

Thanks a lot!

Upvotes: 0

Views: 78

Answers (1)

Carlos Jimenez Bermudez
Carlos Jimenez Bermudez

Reputation: 1175

It would be better design and less code redundance if you implement a single IChecker class to work with several types in the case that you're working with set types only. However depending on your case it might be wise to use templated class.

Remember that unlike .Net or Java, C++ allows multiple inheritance from classes (not necessarily interfaces), so doing both would work fine.

An example of a templated class would be the following:

template <class T>
class IChecker { 
public:
virtual bool CheckIt(const T& thingToCheck) = 0;

}

And you would inherit this way:

class InheritChecker : public IChecker<someClass>, public IChecker<someOtherType>
{
    //Your method definitions here.
}

Summarizing it depends on your use case. If you will only use it for set types, then use only one class for all types. If you want the flexibility to be able to use any type any time. Make IChecker a templated class. That anyone can inherit from.

Upvotes: 1

Related Questions