Inherit C++ class from protobuf - c++

I have objects of two types: TActionInfo and TActionStats. The first one describes action's characteristics and the second one can "eat" the first one and maintain some statistics based on many actions.
It is very convenient to use a protobuf in my task, because these objects are frequently serialized and deserialized.
It seems to be a good idea that TActionStats should have a method like
bool AddAction(const TActionInfo& action);
Is it a good idea to inherit a class from from google-protobuf TActionStats class?
It is a good idea to inherit smth from protobuf in general?

No, you should not subclass protobuf types.
Consider what would happen if you embedded a TActionStats inside some other message type:
message TEnvelope {
optional TActionStats stats = 0;
optional string recipient = 1;
}
Now when you call stats() or mutable_stats() on a TEnvelope, you will receive a TActionStats, not your subclass. If you have a bunch of code that expects specifically to receive your subclass, you won't be able to call that code (without making a copy), so now you have to rewrite everything.
Instead, write your helper methods as independent, free-standing functions.

Related

Creating a "Publisher->Dispatcher->Subscriber" pattern event system?

Edit: TL;DR
I guess my main problem is I don't know how to store a list of functions that all take one argument, where the argument type is different between each function, but always extends from EventBase, for calling later.
i.e: EventChild extends from EventBase. A function with the signature
<void (EventChild&)>
will not fit into a variable of type
std::function<void(EventBase&)>
How do I store functions like this, knowing that a user shouldn't have to modify the class where they are stored each time they create a new event extending from our EventBase class?
Note: I had previously been told I could use a dynamic_cast to accomplish this. I have been trying to do exactly that, but it hasn't been working. I imagine for that to work I would have to use pointers somehow, but I am new enough to C++ that I'm not sure how to do it. Maybe that should be the starting point?
One of the problems with dynamic casting pointers I have been having is 'I can convert a pointer of type:
(Subbscriber*)(getDemoEvent(EventDemo&)
to type:
void(EventBase&)
or something along those lines. (not at my computer right now to try it)
This is obviously a problem limited to member functions, I assume.
I recently posted a question on here with the intention of solving an issue for a C++ Event system based on a "Publisher->Dispatcher->Subscriber" pattern. I don't know the exact name of this pattern, but I hear that it is a variant on the Observer pattern with an added "middle-man."
I have been trying to get this system to work for a while now and I am completely stuck. It was suggested in the comments of the previous question that for what I was trying to accomplish, my program layout is incorrect. This is very likely the case since I had been researching other event systems that were close to what I am after trying to modify them for use they were unintended for. So I figured I would describe what I am after, and ask the more general question of "How would you go about structuring and creating this?"
So here is my general idea of how the system should be laid out and how it should operate in a basic example:
Starting with the idea of 5 different files (plus headers and maybe some subclasses):
main.cpp
dispatcher.cpp
publisher.cpp
subscriber.cpp
eventbase.cpp
publishers and subscribers could be anything, and they only serve as an example here.
The first order of business would be to create an instance of our Dispatcher class.
Following that, we create instances of our publisher/subscriber classes. These 2 classes could be a part of the same file, different files, multiples of each, or not event be classes at all but simply free functions. For the sake of simplicity and testing, they are 2 separate classes that know nothing about each other.
When these 2 classes are created, they should be passed a reference or pointer to our dispatcher instance.
This is easy enough. Now let's get to how you should use the system.
A user of the system should be able to create a class that inherits from our EventBase class. Ideally, there should be no requirement on variables or functions to override from the base class.
Let's say we have created a new event class called EventDemo, with a public const char* demoString = "I am a Demo Event";.
From our subscriber class, we should be able to tell our dispatcher that we want to listen for and receive some events. The syntax for doing so should be as simple as possible.
Lets create a member function in our subscriber that looks like this:
void Subscriber::getDemoEvent(const EventDemo &ev) {
std::cout << ev.demoString;
}
Now we need a way to bind that member function to our dispatcher. We should probably do that in our constructor. Let's say that the reference to our dispatcher that we passed to our subscriber when we created it is just called 'dispatcher'.
The syntax for subscribing to an event should look something like this:
dispatcher->subscribe("EventToSubTo", &getDemoEvent);
Now since we are in a class trying to pass a member function, this probably isn't possible, but it would work for free functions.
For member functions we will probably need and override that looks like this:
dispatcher->subscribe("EventToSubTo", &Subscriber::getDemoEvent, this);
We use 'this' since we are inside the subscribers constructor. Otherwise, we could use a reference to our subscriber.
Notice that I am simply using a string (or const char* in c++ terms) as my "Event Key". This is on purpose, so that you could use the same event "type" for multiple events. I.E: EventDemo() can be sent to keys "Event1" and "Event2".
Now we need to send an event. This can be done anywhere we have a reference to our dispatcher. In this case, somewhere in our publisher class.
The syntax should look something like this to send our EventDemo:
dispatcher->emit("EventToSubTo", EventDemo());
Super simple. It's worth noting that we should be able to assign data to our event through it's constructor, or even template the event. Both of these cases are only valid if the event created by the user supports it.
In this case, the above code would look something like this:
dispatcher->emit("EventToSubTo", EventDemo(42));
or
dispatcher->emit("EventToSubTo", EventDemo<float>(3.14159f));
It would be up to the user to create a member function to retrieve the data.
OK, so, all of that should seem pretty simple, and in fact, it is, except for one small gotcha. There are already systems out there that store functions in a map with a type of .
And therein lies the problem...
We can store our listener functions, as long as they accept a type of EventBase as their argument. We would then have to type cast that argument to the type of event we are after. That's not overly difficult to do, but that's not really the point. The point is can it be better.
Another solution that was brought up before was the idea of having a separate map, or vector, for each type of event. That's not bad either, but would require the user to either modify the dispatcher class (which would be hard to do when this is a library), or somehow tell the dispatcher to "create this set of maps" at compile time. That would also make event templating a nightmare.
So, the overly generalized question: How do we do that?
That was probably a very long winded explanation for something seemingly simple, but maybe someone will come along not not know about it.
I am very interested to hear thoughts on this. The core idea is that I don't want the 2 communicators (publisher and subscriber) to have to know anything about each other (no pointers or references), but still be able to pass arbitrary data from one to the other. Most implementations I have seen (signals and slots) require that there be some reference to each other. Creating a "middle-man" interface feels much more flexible.
Thank you for your time.
For reference to my last question with code examples of what I have so far:
Store a function with arbitrary arguments and placeholders in a class and call it later
I have more samples I could post, but I think it's highly likely that the structure of the system will have to change. Waiting to hear thoughts!

How many listeners are too many observer pattern?

My class were inheriting from two Listeners already. And I need to add one more listener. It became something like below:
class DatabaseManager : public DatabaseChangeListener,
public PropertyChangeListener,
public RenumberListener
Should I avoid too many observers? Even though listeners are abstract classes it bothers me a bit that I am using multiple inheritance. I am curious has any one had experienced something like; because too many observers code became complex and buggy ?
The major signs of smell here are the fact that your class is called DatabaseManager (sounds like a god-object), and also the specialized tone that the interfaces have to them (e.g.RenumberListener).
There's nothing inherently wrong with supporting several event hooks, nor with multiple inheritance in and of itself. You might just need to group some interfaces into one clear one that describes what your class does, its basic right to exist, who uses it, and for what purpose.
Also note, implementing an interface is a type of functionality directed at the consumers of the class. If there's no need for generic interfaces, it's better not to have them, for otherwise you might find yourself with an interface per member function in the system at one extreme, and at the other, no clear guideline on what makes an interface and what doesn't.
If you want to reduce the number of classes, you can try to abstract away the different type of messages your listening to by creating a basic listener interface, e.g.,
virtual void onEvent(Subject * subject, Message * message) = 0;
Then you register your DatabaseManager for different type of events? This way you can still use single inheritance. I know that system like Qt etc use this for dispatching events.
But as far as I know, if your base classes (DatabaseChangeListener, PropertyChangeListener and RenumberListener) are pure abstract, you will not encounter problems with multiple inheritance.
Don't use inheritance. Implement one listener interface and use onEvent method to handle it passing event to different handlers. Subscribe your object on different event types. This way you can easily change any events and handlers without changing your DatabaseManager. Even new events doesn't require much from DatabaseManager.
Consider using something like Chain of Responsibility to make your manager class fully undependable of event types. It could use just a chain of IHandler objects, which can be injected in constructor

C/C++: Should serialization methods be class members?

Suppose we have a complex (i.e. non-primitive) class ComplexObject defined below:
class A{...};
class B{...};
class C{...};
class ComplexObject
{
private:
A _fieldA;
B _fieldB;
C _fieldC;
};
I would like to implement a serializer that serializes instances of ComplexObject into binary form. From my experience in C#, I have seen essentially 3 distinct ways to implement a serializer.
Define a serialize(binarystream&) method in ComplexObject's definition and those of the "child" classes, A, B, and C. The serialize method defined in ComplexObject will recursively call those of the child members.
Create a separate class that contains methods to serialize each of ComplexObject, A, B, and C. The method used to serialize ComplexObject will recursively call those of the child members. Of course, getters will have to be defined in the classes to retrieve private fields for the serializer.
Use reflection to generate a template of the object and to write all serializable fields into a table according to the generated template.
Unfortunately I believe reflection will be extremely hard to utilize in C++, so I shall stay away from the third option. I have seen options 1 and 2 both been used very often (in C#).
An advantage that option 1 possess over option 2 is that it allows for classes that derive from ComplexObject, by marking the serilalize(binarystream&) method virtual. However, it would add to the list of member functions of an object and confuse programmers. You don't see a serialize method being defined in std::string, do you?
On the other hand, option 2 takes out and groups all serialization methods together to make things a bit neater. However, I suppose it isn't as easy to accommodate for derived classes of ComplexObject.
Under which circumstances should each of the options (1 and 2) be used?
I choose "both". Serialization has components in the object and (templated) free standing functions.
For example:
class Serialization_Interface
{
public:
virtual void load_from_buffer(uint8_t*& buffer_ptr) = 0;
};
void Load_From_Buffer(unsigned int& number, uint8_t*& buffer_pointer)
{
number = *((unsigned int *) buffer_ptr);
buffer_pointer += sizeof(unsigned int);
}
template <class Object>
void Load_From_Buffer(Object& obj, uint8_t*& buffer_pointer)
{
obj.load_from_buffer(buffer_pointer);
}
Don't limit yourself to two choices. There's always a third alternative. :-)
Also, don't reinvent the wheel, check out Boost::serialization.
C++ doesn't have reflection, but that doesn't mean serialization code needs to be written by hand.
You can use a code generator (for example, protocol buffers) to create the serialization code from a simple description. Of course, that description format doesn't support the rich C++ features for creating your public API, but you can take the data structure type created by the code generator and embed that inside your "real" class, either directly embedded or via pimpl. That way you write all non-serialization behavior in your class, but it doesn't have any data of its own, it relies on the serialization object to store the data.
It's basically like your method #2, but applying inversion of control. The serializer logic doesn't reach into your class to get access to the data, instead it becomes responsible for storing the data where your class also can use it.
I wold not bother with self-made serializer.
(Notice that designing deserialization is harder than serialization...)
I would rather use something line:
https://code.google.com/p/protobuf/
http://android-developers.blogspot.com/2014/06/flatbuffers-memory-efficient.html
or boost (you can also check how they solved similar problem)
http://www.boost.org/doc/libs/1_56_0/libs/serialization/doc/index.html
Getting back to your dilemma.
Grouping all serialization code in a single class is a bad idea, because this class would grown with each new serializable object. You could use friend "serializer" class for each "serializable" class,
or use friend method / operator<<.
But there is no perfect solution and it is not easy task. If you can, use lib.

Retrieving values of collection from multiple classes, what's the correct way?

Before anything, thanks for reading!
I'm developing an application in C++ and I want an advice about a design issue. Let me explain:
The main class of my application has some collections, but other classes eventually need to get a value from one of those collections. Something like this:
class MainClass {
private:
// Collections are internally implemented as QHash
Collection<Type1> col1;
Collection<Type2> col2;
};
class RosterUnit {
public:
RosterUnit() {
/* This method needs to get a specific value from col1 and
initialize this class with that data */
}
};
class ObjectAction {
public:
virtual void doAction() = 0;
};
class Action1 : public ObjectAction {
public:
void doAction() {
// This needs a specific value from col2
}
};
class Action2 : public ObjectAction {
public:
void doAction() {
// This needs a specific value from col1
}
};
My first approach was passing the whole collection as parameter when needed, but it is not so good for ObjectAction subclasses, because I would have to pass the two collections and if I later create another subclass of ObjectAction and it needs to get an element from other collection (suppose col3), I would have to modify the doAction() signature of every ObjectAction subclass, and I think that is not too flexible. Also, suppose I have a Dialog and want to create a RosterUnit from there. I would have to pass the collection to the dialog just to create the RosterUnit.
Next I decided to use static variables in RosterUnit and ObjectAction that pointed to the collections, but I'm not very happy with that solution. I think it is not flexible enough.
I have been reading about design patterns and I first thought a Singleton with get functions could be a good choice, but after some more investigation I think it isn't a proper design for my case. It would be easier and more or less the same if I use global variables, which don't seem to be the right way.
So, could you give some advices, please?
Thank you very much!
As mentioned previously, Iterators are good for abstracting away the details of the Collection. But going this route implies that the objects that use the Iterators will need to know about what's inside the Collection. Meaning they will need to know how to decide which object in the Collection they need, thus increasing the coupling. (more details below in the Factory paragraph) This is something you need to consider.
Another approach would be to create accessor methods on the MainClass that take some sort of key and return an object from the Collection (findObject(key)). Internally the MainClass methods would search through the container(s) and return the appropriate object. To use this approach, you will however need access to the MainClass, either by dependancy injection as mentioned before, or possibly making it a Singleton (not recomended in this scenario, though).
With the info provided so far, it may even be better for your ObjectAction Factory to have a reference to the MainClass, and as a part of the ObjectAction creation logic, call the appropriate MainClass accessor and pass the result into the ObjectAction, thus decoupling the ObjectAction Objects from the MainClass.
You probably want to use iterators, they exist exactly for the purpose of abstracting away sequences from specific containers.
If your issue is how to pass the iterators to the code that needs them in the first place, do not give in to the temptation to use globals. It may look more convoluted if you have to pass parameters in, but your code is that much more decoupled for it. "Dependency Injection" is a good keyword if you want to read more about this topic.
I would also advise you to check out std::function or boost::function instead of inheriting from ObjectAction. Functional style is getting more common in modern C++, as opposed to how it's usually done in languages like Java.
There's not enough information here of what you are trying to do. You make it sound like 'at some point in the future, this statically created action needs this data that was left behind.' How does that make any sense? I would say either construct the actions with the data, as you would for instance with a Future or Callable), or have the command ask for the next piece of data, in which case you are just implementing a Work queue.
Sounds like you are trying to do something like a thread pool. If these actions are in any way related, then you should have then in some composing object, implementing something like the Template Method pattern, e.g. execute() is abstract and calls a few other methods in a fixed sequence and that cannot be overridden, the other methods must be (protocol enforcement).

C++/Qt, getting a derived objects variable name as list?

I'm not too sure how to explain this, but I will try.
I have a object A which has a rownr and partition nr. B, C inherits from A and adds a few other variables (and get/setters for them)
I then have a function which takes a variable that is derived from A (B, C... etc) that will create an record in a database/table with the same columns as the variables the object has.
For example:
class A {
int paritionKey;
int rowKey;
set/get for them both
}
class B : A {
string color;
...
}
One table will then be called "B" and have 3 columns, partitionKey, rowKey and color.
Is there any way of not hard coding this? Or would the best way be to create a toString method in the classes that returns a part of the xml request body that will be used to construct the new row in the table? (using REST)
It sounds like you are asking if there is a way to do automated marshalling of C++ objects into a database. The short answer is no, there is no built-in way in the C++ language to do this. Your toString() method isn't a bad approach, although it does require you to write toString() (and likely at some point also fromString()) methods for each of your classes... whether that is too much work or not would depend on how many such classes you need to support.
Alternatively you might also take a look at Qt's property system -- if you don't mind subclassing your data objects from QObject, you can decorate your class definitions with Q_PROPERTY declarations, along with getter methods for each property, and then you can write generic code that uses Qt's QMetaObject class to iterate over all declared properties of any given QObject in a generic fashion. This works because Qt's moc preprocessor (which you will be running anyway if you are using Qt) will parse the Q_PROPERTY macros and it can auto-generate a lot of the necessary glue code for you. You'll still have to write the last step (converting the QObject's data to XML or SQL commands by iterating over myObject->metaObject()->property(int) and calling myObject->property(propName) for each property) yourself, but at least you can do that in a generic fashion, without having to write a separate marshalling routine for each class.
The approach I'm using is indeed a "toString" or rather "toXml", the hierachical nature of xml being perfect for this. Schematically:
void A::toXml(QDomElement *parentEl)
{
QDomeElement* el = parentEl->ownerDocument()->createElement("A");
parentEl->apeendChild(el);
el->setAttribute("paritionKey", paritionKey);
el->setAttribute("rowKey", rowKey);
}
void B::toXml(QDomElement *parentEl)
{
QDomeElement* el = parentEl->ownerDocument()->createElement("B");
parentEl->apeendChild(el);
el->setAttribute("color", color);
A::toXml(el);
}
Which gives e.g.:
[...]
<B color="blue">
<A partitionKey=2 rowKey=25/>
</B>
[...]
Same logic for class "C".