I implemented a class which depended on an interface for sending data.
Concrete versions of the interface were implemented for testing and for production and they were injected at construction (depending if the class was being tested or used in production)
This works but there is a maintainence overhead on maintaining multiple overloaded send functions that do very similiar things.
I would like to template the send function however that is impossible on an overriden function.
My next idea is rather than the class depending on an interface, it will contain a map of datatypes to callbacks. This means I can specify the functionality for each datatype and inject it into the class depending on if I want test functionality or real functionality.
The difficulty comes because the map has to store functions with different signatures because the paramter type is different for every function.
How best can I do this? Is the idea sound or is there a better design?
Related
I am trying to implement a system where I have a template class which implements a Serializable interface.
Right now, the interface contains serialize/deserialize methods while the template Setting class has get/set, and private members settingName, settingValue and a template function T adaptType() to adapt string to correct type using the >> operator (https://gist.github.com/mark-d-holmberg/862733). The file also contains a custom struct with << and >> operators overloaded for everything to work.
Settings are serialized in form of settingName:settingValue or settingName:val1;val2;val3 in case of the struct.
There are two problems I'm facing with this design:
I want to hold all these setting objects in a map<string, ISerializable*(?)> to access them but then I can't call other functions get/set on these objects because the interface doesn't define the methods (they must be in Setting class because their type depends on the template type), if I switch the second type in map to template class, I must define a concrete type
When deserializing there's no way to know which type it is and ISerializable can't be instantiated since it's an abstract class, again I need to know which type I'm deserializing and instantiate the Setting class with appropriate type
Is there a better way to design this or something I'm missing, note that I am not very proficient with c++
Bit of a background for the problem:
I'm working on an embedded device where settings need to be loaded/saved to flash memory but there's also another framework running on the device which holds these settings in RAM and serves them on a webserver to be edited, I cannot change this part. My goal is to manually save these settings to my custom class that manages settings and save/load to flash so it is persistent between reboots and synced with the web framework.
Any help or advice is welcome
As far as I understand your problem it is similar to what the Oops library is doing. It creates a Type Descriptor class for all types having similar functionality: giving some description of the type and provide text and binary serialization for them. It is also designed to handle configuration, so it even may help to solve your problem.
It worth to have a look at least for getting some ideas: https://bitbucket.org/barczpe/oops
I've had this problem tickling me for the past weeks; my current implementation works, but I'm curious to know if there is a "good way" to do this. I'm new to design patterns, so this might be a stupid question.
Put simply, you have:
An object prototype providing an interface (let's call it abstract kernel);
Specific kernels implementing the above interface in various ways;
A concrete kernel Factory;
Another object Foo, which stores a pointer to an abstract kernel, as is returned by the Factory.
My problem is this; specific kernels implementations may define their own set of parameters, which differ from one kernel to another.
Foo uses kernels to do some processing, but this processing ultimately depends on these parameters, and I don't know how to configure those in a nice way.
I don't want to go for an abstract factory, and configure the concrete factory before building, because this seems wrong to me; it's not the factory that has parameters, it's the kernel.
But on the other hand, even if I set the kernel pointer in Foo as public, I can't access the parameters of the underlying kernel since they're not part of the prototype's interface... I'm sure other people had this problem before, maybe there's a simple solution I don't see. :S
Thanks in advance!
NOTE: In my current implementation, there is no kernel Factory. I put the kernel concrete type as a template of Foo, and set the kernel as a public member, which allows me to configure the kernel after the declaration, and before to start the processing.
If a piece of code knows what concrete kind of kernel it works with, it should have a pointer to that specific concrete kernel type. If it doesn't, it cannot access its specific parameters (but can possibly access all parameters in a generic way as suggested by #Jaywalker).
Your current implementation seems to go the first route, which is perfectly OK.
I have very limited info about your design, but it looks like you have several concrete kernel types, a separate builder for each type, and a separate configurator for each type. Packing all the builders into a Factory is problematic, as there's no clean and elegant way to forward concrete kernel types to their respective configurators (without things like *_cast<> or double dispatch). There are at least two ways to solve this and still have a Factory:
Bundle each builder with its respective configurator, and pack all the bundles into a Factory that churns out configured kernels.
Bundle each kernel with its configurator and make a Factory producing these bundles (this way a kernel may be configured any number of times during its life cycle).
Anything which is not part of the prototype interface will not be available in Foo, as you have said. It simply doesn't make sense to use the factory pattern if Foo knows the specifics of each kernel implementation.
In some limited circumstances, adding something like following getters and setters in the prototype interface could get your work done:
virtual bool setParameter (const string &key, const string &value) = 0;
virtual string getParameter (const string &key) = 0;
I have several modules (mainly C) that need to be redesigned (using C++). Currently, the main problems are:
many parts of the application rely on the functions of the module
some parts of the application might want to overrule the behavior of the module
I was thinking about the following approach:
redesign the module so that it has a clear modern class structure (using interfaces, inheritence, STL containers, ...)
writing a global module interface class that can be used to access any functionality of the module
writing an implementation of this interface that simply maps the interface methods to the correct methods of the correct class in the interface
Other modules in the application that currently directly use the C functions of the module, should be passed [an implementation of] this interface. That way, if the application wants to alter the behavior of one of the functions of the module, it simply inherits from this default implementation and overrules any function that it wants.
An example:
Suppose I completely redesign my module so that I have classes like: Book, Page, Cover, Author, ... All these classes have lots of different methods.
I make a global interface, called ILibraryAccessor, with lots of pure virtual methods
I make a default implementation, called DefaultLibraryAccessor, than simply forwards all methods to the correct method of the correct class, e.g.
DefaultLibraryAccessor::printBook(book) calls book->print()
DefaultLibraryAccessor::getPage(book,10) calls book->getPage(10)
DefaultLibraryAccessor::printPage(page) calls page->print()
Suppose my application has 3 kinds of windows
The first one allows all functionality and as an application I want to allow that
The second one also allows all functionality (internally), but from the application I want to prevent printing separate pages
The third one also allows all functionality (internally), but from the application I want to prevent printing certain kinds of books
When constructing the window, the application passes an implementation of ILibraryAccessor to the window
The first window will get the DefaultLibraryAccessor, allowing everything
I will pass a special MyLibraryAccessor to the second window, and in MyLibraryAccessor, I will overrule the printPage method and let it fail
I will pass a special AnotherLibraryAccessor to the third window, and in AnotherLibraryAccessor, I will overrule the printBook method and check the type of book before I will call book->print().
The advantage of this approach is that, as shown in the example, an application can overrule any method it wants to overrule. The disadvantage is that I get a rather big interface, and the class-structure is completely lost for all modules that wants to access this other module.
Good idea or not?
You could represent the class structure with nested interfaces. E.g. instead of DefaultLibraryAccessor::printBook(book), have DefaultLibraryAccessor::Book::print(book). Otherwise it looks like a good design to me.
Maybe look at the design pattern called "Facade". Use one facade per module. Your approach seems good.
ILibraryAccessor sounds like a known anti-pattern, the "god class".
Your individual windows are probably better off inheriting and overriding at Book/Page/Cover/Author level.
The only thing I'd worry about is a loss of granularity, partly addressed by suszterpatt previously. Your implementations might end up being rather heavyweight and inflexible. If you're sure that you can predict the future use of the module at this point then the design is probably ok.
It occurs to me that you might want to keep the interface fine-grained, but find some way of injecting this kind of display-specific behaviour rather than trying to incorporate it at top level.
If you have n number of methods in your interface class, And there are m number of behaviors per each method, you get m*(nC1 + nC2 + nC3 + ... + nCn) Implementations of your interface (I hope I got my math right :) ). Compare this with the m*n implementations you need if you were to have a single interface per function. And this method has added flexibility which is more important. So, no - I don't think a single interface would do. But you don't have to be extreme about it.
EDIT: I am sure the math is wrong. :(
I am developing a C++ application used to simulate a real world scenario. Based on this simulation our team is going to develop, test and evaluate different algorithms working within such a real world scenrio.
We need the possibility to define several scenarios (they might differ in a few parameters, but a future scenario might also require creating objects of new classes) and the possibility to maintain a set of algorithms (which is, again, a set of parameters but also the definition which classes are to be created). Parameters are passed to the classes in the constructor.
I am wondering which is the best way to manage all the scenario and algorithm configurations. It should be easily possible to have one developer work on one scenario with "his" algorithm and another developer working on another scenario with "his" different algorithm. Still, the parameter sets might be huge and should be "sharable" (if I defined a set of parameters for a certain algorithm in Scenario A, it should be possible to use the algorithm in Scenario B without copy&paste).
It seems like there are two main ways to accomplish my task:
Define a configuration file format that can handle my requirements. This format might be XML based or custom. As there is no C#-like reflection in C++, it seems like I have to update the config-file parser each time a new algorithm class is added to project (in order to convert a string like "MyClass" into a new instance of MyClass). I could create a name for every setup and pass this name as command line argument.
The pros are: no compilation required to change a parameter and re-run, I can easily store the whole config file with the simulation results
contra: seems like a lot of effort, especially hard because I am using a lot of template classes that have to be instantiated with given template arguments. No IDE support for writing the file (at least without creating a whole XSD which I would have to update everytime a parameter/class is added)
Wire everything up in C++ code. I am not completely sure how I would do this to separate all the different creation logic but still be able to reuse parameters across scenarios. I think I'd also try to give every setup a (string) name and use this name to select the setup via command line arg.
pro: type safety, IDE support, no parser needed
con: how can I easily store the setup with the results (maybe some serialization?)?, needs compilation after every parameter change
Now here are my questions:
- What is your opinion? Did I miss
important pros/cons?
- did I miss a third option?
- Is there a simple way to implement the config file approach that gives
me enough flexibility?
- How would you organize all the factory code in the seconde approach? Are there any good C++ examples for something like this out there?
Thanks a lot!
There is a way to do this without templates or reflection.
First, you make sure that all the classes you want to create from the configuration file have a common base class. Let's call this MyBaseClass and assume that MyClass1, MyClass2 and MyClass3 all inherit from it.
Second, you implement a factory function for each of MyClass1, MyClass2 and MyClass3. The signatures of all these factory functions must be identical. An example factory function is as follows.
MyBaseClass * create_MyClass1(Configuration & cfg)
{
// Retrieve config variables and pass as parameters
// to the constructor
int age = cfg->lookupInt("age");
std::string address = cfg->lookupString("address");
return new MyClass1(age, address);
}
Third, you register all the factory functions in a map.
typedef MyBaseClass* (*FactoryFunc)(Configuration *);
std::map<std::string, FactoryFunc> nameToFactoryFunc;
nameToFactoryFunc["MyClass1"] = &create_MyClass1;
nameToFactoryFunc["MyClass2"] = &create_MyClass2;
nameToFactoryFunc["MyClass3"] = &create_MyClass3;
Finally, you parse the configuration file and iterate over it to find all the entries that specify the name of a class. When you find such an entry, you look up its factory function in the nameToFactoryFunc table and invoke the function to create the corresponding object.
If you don't use XML, it's possible that boost::spirit could short-circuit at least some of the problems you are facing. Here's a simple example of how config data could be parsed directly into a class instance.
I found this website with a nice template supporting factory which I think will be used in my code.
I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like play(), stop(), pause(), record() etc... Then I have workhorse classes which do the video decoding and video encoding.
I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine.
The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use, and to avoid any possible naming conflicts? I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue.
I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure.
My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem.
I would reference something like a QTextDocument in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to an object like a QTextEdit to do the manipulation.
You would use a nested class to create a (small) helper class that's required to implement the main class. Or for example, to define an interface (a class with abstract methods).
In this case, the main disadvantage of nested classes is that this makes it harder to re-use them. Perhaps you'd like to use your VideoDecoder class in another project. If you make it a nested class of VideoPlayer, you can't do this in an elegant way.
Instead, put the other classes in separate .h/.cpp files, which you can then use in your VideoPlayer class. The client of VideoPlayer now only needs to include the file that declares VideoPlayer, and still doesn't need to know about how you implemented it.
One way of deciding whether or not to use nested classes is to think whether or not this class plays a supporting role or it's own part.
If it exists solely for the purpose of helping another class then I generally make it a nested class. There are a whole load of caveats to that, some of which seem contradictory but it all comes down to experience and gut-feeling.
sounds like a case where you could use the strategy pattern
Sometimes it's appropriate to hide the implementation classes from the user -- in these cases it's better to put them in an foo_internal.h than inside the public class definition. That way, readers of your foo.h will not see what you'd prefer they not be troubled with, but you can still write tests against each of the concrete implementations of your interface.
We hit an issue with a semi-old Sun C++ compiler and visibility of nested classes which behavior changed in the standard. This is not a reason to not do your nested class, of course, just something to be aware of if you plan on compiling your software on lots of platforms including old compilers.
Well, if you use pointers to your workhorse classes in your Interface class and don't expose them as parameters or return types in your interface methods, you will not need to include the definitions for those work horses in your interface header file (you just forward declare them instead). That way, users of your interface will not need to know about the classes in the background.
You definitely don't need to nest classes for this. In fact, separate class files will actually make your code a lot more readable and easier to manage as your project grows. it will also help you later on if you need to subclass (say for different content/codec types).
Here's more information on the PIMPL pattern (section 3.1.1).
You should use an inner class only when you cannot implement it as a separate class using the would-be outer class' public interface. Inner classes increase the size, complexity, and responsibility of a class so they should be used sparingly.
Your encoder/decoder class sounds like it better fits the Strategy Pattern
One reason to avoid nested classes is if you ever intend to wrap the code with swig (http://www.swig.org) for use with other languages. Swig currently has problems with nested classes, so interfacing with libraries that expose any nested classes becomes a real pain.
Another thing to keep in mind is whether you ever envision different implementations of your work functions (such as decoding and encoding). In that case, you would definitely want an abstract base class with different concrete classes which implement the functions. It would not really be appropriate to nest a separate subclass for each type of implementation.