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!
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.
Related
I'm working on a very, very simple data access layer (DAL) featuring two classes: DataTransferObject (DTO) and DataAccessObject (DAO). Both classes are abstract base classes and need to be inherited and modified for a specific use case.
class DataTransferObject {
protected:
//protected constructor to prevent initialization
};
class DataAccessObject {
public:
virtual bool save(DataTransferObject o) = 0;
virtual DataTransferObject* load(int id) = 0;
};
in case of a House class from the business logic layer, the implementation of the DAL classes would read something along these lines:
class Dto_House : public DataTransferObject {
public:
int stories;
string address; //...which are all members of the House class...
Dto_House(House h);
};
class Dao_House : public DataAccessObject {
public:
bool save(Dto_House h) { /*...implement database access, etc...*/ }
Dto_House* load(int id) {/*...implement database access, etc...*/ }
};
EDIT: Of course, the derived classes know about the structure of the House class and the data storage.
Simple, nice, okidoke.
Now I wanted to provide a method toObject() in the DTO class in order to quickly convert the Dto_House into a House object. I then read about the automatic return type deduction in C++14 and tried:
class DataTransferObject {
public:
virtual auto toObject() = 0;
};
But I had to discover: No automatic return type deduction for virtual functions. :(
What are your ideas about implementing a "virtual function with deduced return type" for this specific case? I want a general toObject() function in my DTO "interface".
The only thing that came to my mind was something like:
template <typename T>
class DataTransferObject {
virtual T toObject() = 0;
};
class Dto_House : public DataTransferObject<House> {
public:
int stories;
string address;
House toObject() {return House(stories, address);}
};
EDIT:
A possible use case would be:
House h(3, "231 This Street");
h.doHouseStuff();
//save it
Dto_House dtoSave(h);
Dao_House dao;
dao.save(dtoSave); //even shorter: dao.save(Dto_House(h));
//now load some other house
Dto_House dtoLoad = dao.load(id 2);
h = dtoLoad.toObject();
h.doOtherHouseStuff();
But the house does not know it can be saved and loaded.
Of course, the abstract DAO class may be derived to further refine it for the use with, e.g. Sqlite, XML files or whatever... I just presented the very basic concept.
How about setting an empty abstract class - practically, an interface, then have both of your types implement it and set this as the toObject returning reference type?
class Transferable
{
virtual ~Transferable() = 0;
}
And then:
class DataTransferObject {
public:
//Return a reference of the object.
virtual Transferable& toObject() = 0;
};
Dto_House : public DataTransferObject, Transferable { /*...*/ }
House : public DataTransferObject, Transferable { /*...*/ }
The example above is to get my point.
Even better, you can use the DataTransferObject for this cause as your returning reference type, and no other abstract class:
class DataTransferObject {
public:
virtual DataTransferObject& toObject() = 0;
};
Dto_House : public DataTransferObject { /*...*/ }
House : public DataTransferObject { /*...*/ }
Update: If you want to have the classes separated apart, separating any association between data and operations by convention, you could set the name of the base class on something that represents the data i.e.: Building, Construction etc, and then use it for the reference type in toObject.
You can also have the class manipulating those operations on the API of data manipulation.
In general, you can not have a virtual function returning different types in different subclasses, as this violates the whole concept of statically typed language: if you call DataTransferObject::toObject(), the compiler does not know what type it is going to return until runtime.
And this highlight the main problem of your design: why do you need a base class at all? How are you going to use it? Calling DataTransferObject::toObject(), even if you use some magic to get it work (or use a dynamically typed language), sounds like a bad idea since you can not be sure what the return type is. You will anyway need some casts, or some ifs, etc, to get it working — or you will be using only the functionality common for all such objects (House, Road, etc.) — but then you just need a common base class for all of them.
In fact, there is one exception to the same return type rule: if you return a pointer to a class, you can use the Covariant return type concept: a subclass may override a virtual function to return a subclass of the original return type. If all your "objects" have a common base class, you may use something along the lines of
struct DataTransferObject {
virtual BaseObject* toObject() = 0;
};
struct Dto_House : public DataTransferObject {
virtual House* toObject() { /*...*/ } // assumes that House subclasses BaseObject
};
However, this will still leave the same problem: if all you have in your code is DataTransferObject, even if you (but not the compiler) know it is a Dto_House, you will need some cast, which might be unreliable.
On the other hand, you template solution seems quite good except that you will not be able to explicitly call DataTransferObject::toObject() (unless you know the type of the object), but that's a bad idea as I have explained.
So, I suggest you think on how you are going to actually use the base classes (even write some sample code), and make your choice based on that.
I'm writing a C++ library for optimization, and I've encountered a curious issue with contra-variant types.
So, I define a hierarchy of "functions", based on what information they can compute.
class Function {
public:
double value()=0;
}
class DifferentiableFunction : public Function {
public:
const double* gradient()=0;
}
class TwiceDifferentiableFunction : public DifferentiableFunction {
public:
const double* hessian()=0;
}
Which is all well and good, but now I want to define interfaces for the optimizers. For example, some optimizers require gradient information, or hessian information in order to optimize, and some don't. So the types of the optimizers are contravariant to the types of the functions.
class HessianOptimizer {
public:
set_function(TwiceDifferentiableFunction* f)=0;
}
class GradientOptimizer : public HessianOptimizer {
public:
set_function(DifferentiableFunction* f)=0;
}
class Optimizer: public GradientOptimizer {
public:
set_function(TwiceDifferentiableFunction* f)=0;
}
Which I suppose makes sense from a type theoretic perspective, but the thing that is weird about it is that usually when people want to extend code, they will inherit the already existing classes. So for example, if someone else was using this library, and they wanted to create a new type of optimizer that requires more information than the hessian, they might create a class like
class ThriceDifferentiableFunction: public TwiceDifferentiableFunction }
public:
const double* thirdderivative()=0;
}
But then to create the corresponding optimizer class, we would have to make HessianOptimizer extend ThirdOrderOptimizer. But the library user would have to modify the library to do so! So while we can add on the ThriceDifferentiableFunction without having to modify the library, it seems like the contravariant types lose this property. This seems to just be an artifact of the fact the classes declare their parent types rather than their children types.
But how are you supposed to deal with this? Is there any way to do it nicely?
Since they're just interfaces, you don't have to be afraid of multiple inheritance with them. Why not make the optimiser types siblings instead of descendants?
class OptimizerBase
{
// Common stuff goes here
};
class HessianOptimizer : virtual public OptimizerBase {
public:
virtual set_function(TwiceDifferentiableFunction* f)=0;
}
class GradientOptimizer : virtual public OptimizerBase {
public:
virtual set_function(DifferentiableFunction* f)=0;
}
class Optimizer : virtual public OptimizerBase {
public:
virtual set_function(TwiceDifferentiableFunction* f)=0;
}
// impl
class MyGradientOptimizer : virtual public GradientOptimizer, virtual public HessianOptimizer
{
// ...
};
I want to extract common code from a few WinRT components to one base class so I don't need to copy&past it. I have the following base class:
[Windows::Foundation::Metadata::WebHostHidden]
ref class ExpandableView : public Windows::UI::Xaml::DependencyObject
{
public:
static void onIsExpandedChanged(Windows::UI::Xaml::DependencyObject^ object,
Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ arguments);
public:
property bool IsExpanded
{
bool get(){return (bool)GetValue(IsExpandedProperty);}
void set(bool value){SetValue(IsExpandedProperty, value);}
}
static property Windows::UI::Xaml::DependencyProperty^ IsExpandedProperty
{
Windows::UI::Xaml::DependencyProperty^ get(){return _IsExpandedProperty;}
}
protected:
ExpandableView();
virtual void viewExpanded();
virtual void viewCollapsed();
private:
void _expand();
void _collapse();
private:
static Windows::UI::Xaml::DependencyProperty^ _IsExpandedProperty;
};
And I create a few User Controls which should be somehow inherited from this base class. And it is not possible to do it the way I want because winrt class can inherit only one ref class and other should be interfaces. But I need this very class which has dependency property which has some logic when it is set and I don't want to copy&past this property across all my classes.
So the question is: how to achieve it with WinRT?
Have you tried using a template and inheritance of the specific class needed:
template<typename BaseClass>
ref class ExpandableView : public BaseClass;
Now the subclasses reusing ExpandableView can inherit whatever they need, not only Windows::UI::Xaml::DependencyObject.
I have a hierarchy of class templates. At the top of the hierarchy is an abstract base class (interface). I won't know which concrete implementation to instantiate until runtime, so it seems like the perfect situation to use the factory pattern. However, virtual member function templates are not allowed in C++.
How can I achieve a legal design similar to the below in C++?
The individual concrete implementations of the IProduct interface as well as the concrete factories will live in different dynamic libraries, one or more of which will be loaded at runtime.
template<class T> class IProduct
{
public:
virtual void doWork(const T & data) = 0;
};
template<class T> class ProductA : public IProduct<T> {/*...*/};
template<class T> class ProductB : public IProduct<T> {/*...*/};
class IProductFactory
{
public:
template<class T> virtual IProduct<T> * createProduct() = 0;
};
class ProductAFactory: public IProductFactory
{
public:
template<class T> virtual IProduct<T> * createProduct()
{
return new ProductA<T>;
}
};
class ProductBFactory: public IProductFactory
{
public:
template<class T> virtual IProduct<T> * createProduct()
{
return new ProductB<T>;
}
};
Why can't you templatize IProductFactory on T as well? That would get rid of your error, and it's no less general. The client is still going to have to know what T is in order to call thecreateProduct method.
Edit Re: comment
In order to do this, you will need to just create a templatized function to create the factory. So:
template<class T> IProductFactory<T>* getProductFactory();
Now your factory is templatized, the createProduct method is no longer a member template. Not sure what your criteria is for returning a ProductAFactory vs. a ProductBFactory but you will either have to pass in a string to choose, have this be a member function of another class that would make the decision, or have multiple free functions but only expose one version or another to a particular client.
This doesn't need a template. Does that eliminate your problem?
EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers.
I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class.
All the objects that create and use the base class objects shouldn't change the way they create or call an object, i.e. should continue calling BaseClass.Create() even when they actually create a Child class.
The Base classes know that they can be overridden, but they do not know the concrete classes that override them.
And I want the registration of all the the Child classes to be done just in one place.
Here is my implementation:
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
template<typename Class>
class CRegisteredClassFactory: public CAbstractFactory
{
public:
~CRegisteredClassFactory(){};
Class* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
Class* pClass;
};
// holds info about all the classes that were registered to be overridden
class CRegisteredClasses
{
public:
bool find(const string & sClassName);
CAbstractFactory* GetFactory(const string & sClassName)
{
return mRegisteredClasses[sClassName];
}
void RegisterClass(const string & sClassName, CAbstractFactory* pConcreteFactory);
private:
map<string, CAbstractFactory* > mRegisteredClasses;
};
// Here I hold the data about all the registered classes. I hold statically one object of this class.
// in this example I register a class CChildClass, which will override the implementation of CBaseClass,
// and a class CFooChildClass which will override CFooBaseClass
class RegistrationData
{
public:
void RegisterAll()
{
mRegisteredClasses.RegisterClass("CBaseClass", & mChildClassFactory);
mRegisteredClasses.RegisterClass("CFooBaseClass", & mFooChildClassFactory);
};
CRegisteredClasses* GetRegisteredClasses(){return &mRegisteredClasses;};
private:
CRegisteredClasses mRegisteredClasses;
CRegisteredClassFactory<CChildClass> mChildClassFactory;
CRegisteredClassFactory<CFooChildClass> mFooChildClassFactory;
};
static RegistrationData StaticRegistrationData;
// and here are the base class and the child class
// in the implementation of CBaseClass::Create I check, whether it should be overridden by another class.
class CBaseClass
{
public:
static CBaseClass* Create()
{
CRegisteredClasses* pRegisteredClasses = StaticRegistrationData.GetRegisteredClasses();
if (pRegisteredClasses->find("CBaseClass"))
{
CRegisteredClassFactory<CBaseClass>* pFac =
dynamic_cast<CRegisteredClassFactory<CBaseClass>* >(pRegisteredClasses->GetFactory("CBaseClass"));
mpInstance = pFac->CreateAndGet();
}
else
{
mpInstance = new CBaseClass;
}
return mpInstance;
}
virtual void Print(){cout << "Base" << endl;};
private:
static CBaseClass* mpInstance;
};
class CChildClass : public CBaseClass
{
public:
void Print(){cout << "Child" << endl;};
private:
};
Using this implementation, when I am doing this from some other class:
StaticRegistrationData.RegisterAll();
CBaseClass* b = CBaseClass::Create();
b.Print();
I expect to get "Child" in the output.
What do you think of this design? Did I complicate things too much and it can be done easier? And is it OK that I create a template that inherits from an abstract class?
I had to use dynamic_pointer (didn't compile otherwise) - is it a hint that something is wrong?
Thank you.
This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to know how these objects are meant to be used. Let me give you an example of how a similar task is accomplished in Java's database library (JDBC):
The system has a DriverManager which knows about JDBC drivers. The drivers have to be registered somehow (the details aren't important); once registered whenever you ask for a database connection you get a Connection object. Normally this object will be an OracleConnection or an MSSQLConnection or something similar, but the client code only sees "Connection". To get a Statement object you say connection.prepareStatement, which returns an object of type PreparedStatement; except that it's really an OraclePreparedStatement or MSSQLPreparedStatement. This is transparent to the client because the factory for Statements is in the Connection, and the factory for Connections is in the DriverManager.
If your classes are similarly related you may want to have a function that returns a specific type of class, much like DriverManager's getConnection method returns a Connection. No casting required.
The other approach you may want to consider is using a factory that has a factory-method for each specific class you need. Then you only need one factory-factory to get an instance of the Factory. Sample (sorry if this isn't proper C++):
class CClassFactory
{
public:
virtual CBaseClass* CreateBase() { return new CBaseClass(); }
virtual CFooBaseClass* CreateFoo() { return new CFooBaseClass();}
}
class CAImplClassFactory : public CClassFactory
{
public:
virtual CBaseClass* CreateBase() { return new CAImplBaseClass(); }
virtual CFooBaseClass* CreateFoo() { return new CAImplFooBaseClass();}
}
class CBImplClassFactory : public CClassFactory // only overrides one method
{
public:
virtual CBaseClass* CreateBase() { return new CBImplBaseClass(); }
}
As for the other comments criticizing the use of inheritance: in my opinion there is no difference between an interface and public inheritance; so go ahead and use classes instead of interfaces wherever it makes sense. Pure Interfaces may be more flexible in the long run but maybe not. Without more details about your class hierarchy it's impossible to say.
Usually, base class/ derived class pattern is used when you have an interface in base class, and that interface is implemented in derived class (IS-A relationship). In your case, the base class does not seem to have any connection with derived class - it may as well be void*.
If there is no connection between base class and derived class, why do you use inheritance? What is the benefit of having a factory if factory's output cannot be used in a general way? You have
class CAbstractFactory
{
public:
virtual ~CAbstractFactory()=0;
};
This is perfectly wrong. A factory has to manufacture something that can be used immediately:
class CAbstractFactory
{
public:
virtual ~CAbstractFactory(){};
public:
CBaseClass* CreateAndGet()
{
pClass = new Class;
return pClass;
}
private:
CBaseClass* pClass;
protected:
CBaseClass *create() = 0;
};
In general, you're mixing inheritance, virtual functions and templates the way they should not be mixed.
Without having read all of the code or gone into the details, it seems like you should've done the following:
make b of type CChildClass,
make CBaseClass::Print a virtual function.
Maybe I'm wrong but I didn't find any return statement in your CBaseClass::Create() method!
Personally, I think this design overuses inheritance.
"I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class." - I don't know that IS-A relationships should be that flexible.
I wonder if you'd be better off using interfaces (pure virtual classes in C++) and mixin behavior. If I were writing it in Java I'd do this:
public interface Foo
{
void doSomething();
}
public class MixinDemo implements Foo
{
private Foo mixin;
public MixinDemo(Foo f)
{
this.mixin = f;
}
public void doSomething() { this.mixin.doSomething(); }
}
Now I can change the behavior as needed by changing the Foo implementation that I pass to the MixinDemo.