C++ pointer collection class for easier communication - c++

Is there anything wrong with having a central resource of pointers to act as a communication exchange within a project?
Im currently working on a multi component application in JUCE, learning C++ as I bumble along. Its gotten unwieldy and im looking to clean it up, both to decouple the components from each other and simplify / standardise communication.
The solution that seems most obvious / elegant to me would be to have a pointer manager object holding pointers to all components that need to receive external input, and just have classes reference the manager object, calling the component they need, when they need. Objects would be owned by their parents, and register themselves to the pointer manager in their constructor.
Is there anything wrong with this? Ive not seen any design pattern take this approach, which kind of suggests im about to put a lot of work into doing something stupid.
Does anyone have any downsides or alternatives to consider?

This should be actually a comment but I can't add comments.
What you are trying to do seems like something similar to observer or reactor design patter.
I've seen such solution in real live systems and it worked well. I'll also seen such address bus architecture in inter process communication solution.
Remember about providing good solution for unregistering from your dispatcher.

Related

Does it make sense to put everything in a subclass of QApplication?

In my plugin-based architecture, the plugins must have access to all core components of the application, e.g. the main window, the settingswidget, the settings, the tray icon and several global immutable variables.
Since the application is a global singleton it is straight forward to subclass it and make all those components members of the application. This way I can 1. easily access them from everywhere 2. I can facade their API for the plugins 3. it feels natural that the components are members of the "app".
However reading the lessons on SO about singletons and globals it feels like bad design, but otherwise I'd have to implement a core facade and pass it around, which feels like bad design as well and is definitively less straight forward.
Your description looks like a God object. That is indeed the sign of a potentially bad design.
Depending on what your plugins actually do, things like Observer pattern may be a solution. Instead of giving access to the resources, make your objects suscribe to a mediator and let it make the connections to the resources.
Take also a look to Inversion of control.
I think it's best to take the distinction between IS A and HAS A (inheritance vs. containment) seriously in this case.
A plug-in isn't a QApplication. It uses a QApplication. I don't see any reason to make it a subclass. Just give it a pointer or reference to QApplication.
This is one of the things the observer pattern does for you, subjects (QApplication) have references to their observers (Plugin). You also can use this in a symmetric way.
But using the observer pattern isn't always necessary. Main thing is your Plugins have a reference or pointer to the QApplication instance.
Not sure how it helps but it seems singleton classes are sometimes used to access them from the outside.
In KDE they seem to be refereed to as Conltroler, and seem to be used over Plugin-Boundarys. (KDE is QT based, so i assume a KDEPlugin is similar to a QT one.)
PS: This is in answer form, because i don't have "Comment everywhere".

What is a good way to serialize remote commands?

I've been working into a small game just for learning.
The intent of the game is that it is going to be online, but I have some trouble on how to serialize the commands sent from server to client.
There is a lot of different commands that can be sent, and handling this manually is driving me insane. At the moment I'm using lots of 'ifs' to do this, but I hope there is a Design Pattern that helps.
I would like to unpack the message in different kinds of objects so I could get them from some kind of queue and treat them efficiently... But I would like to do it partially or completely automatic.
Is there a good practice to solve this kind of problem? It would be good if it was efficient too.
Thanks in advance.
PS: Although this is a conceptual question, I'm using C++, so some specific solution would be fine too.
Try a Factory pattern. Something along these lines is a useful factory model.
Make a base class that provides methods for serialising and deserialising data from a stream, and register your derived types by name or some other identifier with the factory.
You can package up a command in a bundle with a header that tells the receiver what type to create. When you read a command, you ask the factory to create the correct type. Then returned type can then be called to deserialise its data.
Here, I'm assuming that some commands have extra data.
Once you have popped the command out of the queue for processing, you can call its 'Execute' method.
There is a design pattern called "actors", which might be what you want. Features:
natual and simplified concurrency model.
could be used together with pattern matching over messages (eliminate "ifs").
Language 'scala' provides good support for this design pattern and perfectly meet your need. However, I don't know whether there is similar solution in C++.

Accessing other program and altering its behavior (Mainly about unofficial multiplayer mods for games)

So I've studied some reverse engineering lately and I'd really like to have a more better idea about how things like sa-mp and mafia 2 multiplayer are actually made. When I connect to a server in sa-mp and it starts the game. Does it inject a dll or something at this point to control the flow of the game and remove all the npcs from the cities etc? I am not really asking anything really specific but just the idea. I looked at the source codes of a few similar projects but didn't really get how it all starts. I would appreciate that someone who has knowledge about these things could enlighten me.
This is really something that has interested me since I discovered these mods so I look forward to hearing from you.
A big part of the work that needs to be done when developing such software is reverse-engineering.
This includes figuring out how the game client works and how you will be able to perform tasks with it. Things to generally look for may include:
the data structure / container that holds all entities of the game
the structure of important classes from which you will need to read information (positions, health, ammunition... )
ways to control the client. This starts with simple stuff like emulating key presses to calling controlling functions of the game or to directly manipulate the network traffic.
After that the preferred way to interact with the target process is to write a dynamic library (DLL). This has the main advantage that you have shared virtual memory with the target and therefore are able to dereference pointers like you would own all the data. You can directly read and write memory, call functions, detour functions etc.
If you have enough understanding of the client you can modify it up to the limits of you imagination.
It seems to me that the mod you linked also created its own server. The server will just be a regular game server (built with the information you gathered) which you have full control over. The client side needs to be implemented inside the DLL.

c++ exception-like message passing

I'm working on developing a fairly robust 2D game engine as a base that other games can be built off of as a for-fun project (I know theres already things that do this, but that's no fun).
I'm trying to figure out a good way to do message-passing between classes within the engine. At first I was thinking about using a heirarchy of exceptions and throwing them whenever something required it. But as I was developing that way, I realized that there was quite a large number of exceptions being thrown, as they were being used for fairly common things (part of subroutines that handle pathfinding and unit locating and things that need to test the state of the game board alot). The exceptions were being used for things like the pathfinding came across a unit in the way and needed to go around it, it would throw a TileOccupied exception and the pathfinding could gracefully handle that and continue. As can be expected, this created a lot of exceptions.
The internet has told me that exceptions are expensive due to all the run-time processing they need to do. But they handle what I need perfectly, which is being able to propogate a message back to the caller even through branching subroutines to indicate when something has happened or something was not as expected.
Is there any clean/efficient way to do this in c++? Or am I structuring things very wrongly if I am using this type of notification? I'm still learning, so any suggestions would be greatly appreciated (and I'm willing to read / learn any references you can throw my way)
Edit
I'm trying to do this in standard c++ btw. I am writing it on linux, and want it to compile and be runnable platform-independent. I'm currently using Boost in it.
Although this requires explicit registration, this sounds like you want callbacks (eased by e.g. Boost.Function) or signals (like Boost.Signals/Signals2).
Is there any reason you haven't used an event queue and/or observer setup?
Exceptions are the wrong way of doing this. Usual suggestion would be direct events/listeners design, but that quickly gets out of hand within any non-trivial system. I'd point you to a whiteboard design for loose communications.

What's a pattern for getting two "deep" parts of a multi-threaded program talking to each other?

I have this general problem in design, refactoring or "triage":
I have an existing multi-threaded C++ application which searches for data using a number of plugin libraries. With the current search interface, a given plugin receives a search string and a pointer to a QList object. Running on a different thread, the plugin goes out and searches various data sources (locally and on the web) and adds the objects of interest to the list. When the plugin returns, the main program, still on the separate thread, adds this data to the local data store (with further processing), guarding this insertion point using a mutex. Thus each plugin can return data asynchronously.
The QT-base plugin library is based on message passing. There are a fair number of plugins which are already written and tested for the application and they work fairly well.
I would like to write some more plugins and leverage the existing application.
The problem is that the new plugins will need more information from the application. They will to need intermittent access to the local data store itself as they search. So to get this, they would need direct or indirect access both the hash array storing the data and the mutex which guards multiple access to the store. I assume the access would be encapsulated by adding an extra method in a "catalog" object.
I can see three ways to write these new plugins.
When loading a plugin, pass them
a pointer to my "catalog" at the
start. This becomes an extra,
"invisible" interface for the new
plugins. This seems quick, easy,
completely wrong according to OO but
I can't see what the future problems would be.
Add a method/message to the
existing interface so I have a
second function which could be
called for the new plugin libraries,
the message would pass a pointer to
the catalog to the plugins. This
would be easy for the plugins but it
would complicate my main code and
seems generally bad.
Redesign the plugin interface.
This seems "best" according to OO,
could have other added benefits but
would require all sorts of
rewriting.
So, my questions are
A. Can anyone tell me the concrete dangers of option 1?
B. Is there a known pattern that fits this kind of problem?
Edit1:
A typical function for calling the plugin routines looks like:
elsewhere(spec){
QList<CatItem> results;
plugins->getResult(spec, &results);
use_list(results);
}
...
void PluginHandler::getResults(QString* spec, QList<CatItem>* results)
{
if (id->count() == 0) return;
foreach(PluginInfo info, plugins) {
if (info.loaded)
info.obj->msg(MSG_GET_RESULTS, (void*) spec, (void*) results);
}
}
It's a repeated through-out the code. I'd rather extend it than break it.
Why is it "completely wrong according to OO"? If your plugin needs access to that object, and it doesn't violate any abstraction you want to preserve, it is the correct solution.
To me it seems like you blew your abstractions the moment you decided that your plugin needs access to the list itself. You just blew up your entire application's architecture. Are you sure you need access to the actual list itself? Why? What do you need from it? Can that information be provided in a more sensible way? One which doesn't 1) increase contention over a shared resource (and increase the risk of subtle multithreading bugs like race conditions and deadlocks), and 2) doesn't undermine the architecture of the rest of the app (which specifically preserves a separation between the list and its clients, to allow asynchronicity)
If you think it's bad OO, then it is because of what you're fundamentally trying to do (violate the basic architecture of your application), not how you're doing it.
Well, option 1 is option 3, in the end. You are redesigning your plugin API to receive extra data from the main app.
It's a simple redesign that, as long as the 'catalog' is well implemented and hide every implementation detail of your hash and mutex backing store, is not bad, and can serve the purpose well enough IMO.
Now if the catalog leaks implementation details then you would better use messages to query the store, receiving responses with the needed data.
Sorry, I just re-read your question 3 times and I think my answer may have been too simple.
Is your "Catalog" an independent object? If not, you could wrap it as it's own object. The Catalog should be completely safe (including threadsafe)--or better yet immutable.
With this done, it would be perfectly valid OO to pass your catalog to the new plugins. If you are worried about passing them through many layers, you can create a factory for the catalog.
Sorry if I'm still misunderstanding something, but I don't see anything wrong with this approach. If your catalog is an object outside your control, however, such as a database object or collection then you really HAVE to encapsulate it in something you can control with a nice, clean interface.
If your Catalog is used by many pieces across your program, you might look at a factory (which, at it's simplest degrades to a Singleton). Using a factory you should be able to summon your Catalog with a Catalog.getType("Clothes"); or whatever. That way you are giving out the same object to everyone who wants one without passing it around.
(this is very similar to a singleton, by the way, but coding it as a factory reminds you that there will almost certainly be more than one--also remember to allow a Catalog.setType("Clothes", ...); for testing.