I have a program that (amongst other things) has a command line interface that lets the user enter strings, which will then be sent over the network. The problem is that I'm not sure how to connect the events, which are generated deep inside the GUI, to the network interface. Suppose for instance that my GUI class hierarchy looks like this:
GUI -> MainWindow -> CommandLineInterface -> EntryField
Each GUI object holds some other GUI objects and everything is private. Now the entryField object generates an event/signal that a message has been entered. At the moment I'm passing the signal up the class hierarchy so the CLI class would look something like this:
public:
sig::csignal<void, string> msgEntered;
And in the c'tor:
entryField.msgEntered.connect(sigc::mem_fun(this, &CLI::passUp));
The passUp function just emits the signal again for the owning class (MainWindow) to connect to until I can finally do this in the main loop:
gui.msgEntered.connect(sigc::mem_fun(networkInterface, &NetworkInterface::sendMSG));
Now this seems like a real bad solution. Every time I add something to the GUI I have to wire it up all through the class hierarchy. I do see several ways around this. I could make all objects public, which would allow me to just do this in the main loop:
gui.mainWindow.cli.entryField.msgEntered.connect(sigc::mem_fun(networkInterface, &NetworkInterface::sendMSG));
But that would go against the idea of encapsulation. I could also pass a reference to the network interface all over the GUI, but I would like to keep the GUI code as seperate as possible.
It feels like I'm missing something essential here. Is there a clean way to do this?
Note: I'm using GTK+/gtkmm/LibSigC++, but I'm not tagging it as such because I've had pretty much the same problem with Qt. It's really a general question.
The root problem is that you're treating the GUI like its a monolithic application, only the gui is connected to the rest of the logic via a bigger wire than usual.
You need to re-think the way the GUI interacts with the back-end server. Generally this means your GUI becomes a stand-alone application that does almost nothing and talks to the server without any direct coupling between the internals of the GUI (ie your signals and events) and the server's processing logic. ie, when you click a button you may want it to perform some action, in which case you need to call the server, but nearly all the other events need to only change the state inside the GUI and do nothing to the server - not until you're ready, or the user wants some response, or you have enough idle time to make the calls in the background.
The trick is to define an interface for the server totally independently of the GUI. You should be able to change GUIs later without modifying the server at all.
This means you will not be able to have the events sent automatically, you'll need to wire them up manually.
Try the Observer design pattern. Link includes sample code as of now.
The essential thing you are missing is that you can pass a reference without violating encapsulation if that reference is cast as an interface (abstract class) which your object implements.
Short of having some global pub/sub hub, you aren't going to get away from passing something up or down the hierarchy. Even if you abstract the listener to a generic interface or a controller, you still have to attach the controller to the UI event somehow.
With a pub/sub hub you add another layer of indirection, but there's still a duplication - the entryField still says 'publish message ready event' and the listener/controller/network interface says 'listen for message ready event', so there's a common event ID that both sides need to know about, and if you're not going to hard-code that in two places then it needs to be passed into both files (though as global it's not passed as an argument; which in itself isn't any great advantage).
I've used all four approaches - direct coupling, controller, listener and pub-sub - and in each successor you loosen the coupling a bit, but you don't ever get away from having some duplication, even if it's only the id of the published event.
It really comes down to variance. If you find you need to switch to a different implementation of the interface, then abstracting the concrete interface as a controller is worthwhile. If you find you need to have other logic observing the state, change it to an observer. If you need to decouple it between processes, or want to plug into a more general architecture, pub/sub can work, but it introduces a form of global state, and isn't as amenable to compile-time checking.
But if you don't need to vary the parts of the system independently it's probably not worth worrying about.
As this is a general question I’ll try to answer it even though I’m “only” a Java programmer. :)
I prefer to use interfaces (abstract classes or whatever the corresponding mechanism is in C++) on both sides of my programs. On one side there is the program core that contains the business logic. It can generate events that e.g. GUI classes can receive, e.g. (for your example) “stringReceived.” The core on the other hand implements a “UI listener” interface which contains methods like “stringEntered”.
This way the UI is completely decoupled from the business logic. By implementing the appropriate interfaces you can even introduce a network layer between your core and your UI.
[Edit] In the starter class for my applications there is almost always this kind of code:
Core core = new Core(); /* Core implements GUIListener */
GUI gui = new GUI(); /* GUI implements CoreListener */
core.addCoreListener(gui);
gui.addGUIListener(core);
[/Edit]
You can decouple ANY GUI and communicate easily with messages using templatious virtual packs. Check out this project also.
In my opinion, the CLI should be independant from GUI. In a MVC architecture, it should play the role of model.
I would put a controller which manages both EntryField and CLI: each time EntryField changes, CLI gets invoqued, all of this is managed by the controller.
Related
When we are testing Rx.NET code we can use TestScheduler that is implementing VirtualTimeScheduler and it allow us to create virtual timeline of events (CreateColdObservable) that occur in system and than test the state of the system in some point of times using methods like AdvanceTo.
I’m wondering if there is some equivalent in Akka.Net for testing system using some king of virtual timeline like in Rx.Net?
While testing your actors using Akka.TestKit, your actor system is configured to make use of TestScheduler, which has Advance/AdvanceTo methods allowing moving forward in time. It's directly inspired by the VirtualTimeScheduler known from the Rx.NET.
Keep in mind that TestScheduler has limited usage: AFAIK it's only used in context of scheduling future events using i.e. Context.System.Scheduler.ScheduleTellxxx methods. It doesn't affect other time-based actions happening inside actor system.
I'm developing an updater for my application in Qt, primarily to get to know the framework (I realize there are multiple ready-made solutions available, that's not relevant here). It is a basic GUI application using a QMainWindow subclass for its main window and an MyAppUpdater class to perform the actual program logic.
The update information (version, changelog, files to be downloaded) is stored on my server as an XML file. The first thing the updater should do after it sets up the UI is query that server, get the XML file, parse it and display info to the user. Here's where I have a problem though; coming from a procedural/C background, I'd initiate a synchronous download, set a timeout of maybe 3 seconds, then see what happens - if I manage to download the file correctly, I'll parse it and carry on, otherwise display an error.
However, seeing how inconvenient something like that is to implement in Qt, I've come to believe that its network classes are designed in a different way, with a different approach in mind.
I was thinking about initiating an asynchronous download in, say, InitVersionInfoDownload, and then connecting QNetworkReply's finished signal to a slot called VersionInfoDownloadComplete, or something along these lines. I'd also need a timer somewhere to implement timeout checks - if the slot is not invoked after say 3 seconds, the update should be aborted. However, this approach seems overly complicated and in general inadequate to the situation; I cannot proceed without retrieving this file from the server, or indeed do anything while waiting for it to be downloaded, so an asynchronous approach seems inappropriate in general.
Am I mistaken about that, or is there a better way?
TL;DR: It's the wrong approach in any GUI application.
how inconvenient something like that is to implement in Qt
It's not meant to be convenient, since whenever I see a shipping product that behaves that way, I have an urge to have a stern talk with the developers. Blocking the GUI is a usability nightmare. You never want to code that way.
coming from a procedural/C background, I'd initiate a synchronous download, set a timeout of maybe 3 seconds, then see what happens
If you write any sort of machine or interface control code in C, you probably don't want it to be synchronous either. You'd set up a state machine and process everything asynchronously. When coding embedded C applications, state machines make hard things downright trivial. There are several solutions out there, QP/C would be a first class example.
was thinking about initiating an asynchronous download in, say, InitVersionInfoDownload, and then connecting QNetworkReply's finished signal to a slot called VersionInfoDownloadComplete, or something along these lines. I'd also need a timer somewhere to implement timeout checks - if the slot is not invoked after say 3 seconds, the update should be aborted. However, this approach seems overly complicated
It is trivial. You can't discuss such things without showing your code: perhaps you've implemented it in some horribly verbose manner. When done correctly, it's supposed to look lean and sweet. For some inspiration, see this answer.
I cannot proceed without retrieving this file from the server, or indeed do anything while waiting for it to be downloaded
That's patently false. Your user might wish to cancel the update and exit your application, or resize its window, or minimize/maximize it, or check the existing version, or the OS might require a window repaint, or ...
Remember: Your user and the environment are in control. An application unresponsive by design is not only horrible user experience, but also makes your code harder to comprehend and test. Pseudo-synchronous spaghetti gets out of hand real quick. With async design, it's trivial to use signal spy or other products to introspect what the application is doing, where it's stuck, etc.
I am making an application in C++ that runs a simulation for a health club. The user simply enters the simulation data at the beginning (3 integer values) and presses run. After that there is no user input - so very simple.
After starting the simulation a lot of the logic is deep down in lower classes but a lot of them need to print simple output messages to the UI. Returning a message is not possible as objects need to print to the UI but keep working.
I was going to pass a reference to the UI object to all classes that need it but I end up passing it around quite a lot - there must be a better way.
What I really need is something that can make calling the UI's printOutput(string) function as easy (or not much more difficult) than cout << string;
The UI also has a displayConnectionStatus(bool[] connections) method.
Bear in mind the UI inherits an abstract 'UserInterface' class so simple console UIs and GUIs can be changed in and out easily.
How do you suggest I implement this link to the UI?
If I were to use a global function, how can I redirect it to call methods of the UserInterface implementation that I selected to use?
Don't be afraid of globals.
Global objects hurt encapsulation, but for a targeted solution with no concern for immediate reusability, globals are just fine.
Expose a global object that processes events from your simulation. You can then choose to print the events, send them by e-mail, render them with OpenGL or whatever you fancy. Make a uniform interface that catches what happens inside the simulation via report callbacks, and then you can subclass this global object to suit your needs.
If the object wasn't global, you'd be passing a pointer around all the codebase.
I would suggest to go for logging framework i.e. your own class LogMessages, which got functions which get data and log the data, it can be to a UI, file, over network or anything.
And each class which needs logging, can use your logging class.
This way you can avoid globals and a generic solution , also have a look at http://www.pantheios.org/ which is open source C/C++ Diagnostic Logging API library, you may use that also...
BRAND NEW to unit testing, I mean really new. I've read quite a bit and am moving slowly, trying to follow best practices as I go. I'm using MS-Test in Visual Studio 2010.
I have come up against a requirement that I'm not quite sure how to proceed on. I'm working on a component that's responsible for interacting with external hardware. There are a few more developers on this project and they don't have access to the hardware so I've implemented a "dummy" or simulated implementation of the component and moved as much shared logic up into a base class as possible.
Now this works fine as far as allowing them to compile and run the code, but it's not terrible useful for simulating the events and internal state changes needed for my unit tests (don't forget I'm new to testing)
For example, there are a couple events on the component that I want to test, however I need them to be invoked in order to test them. Normally to raise the event I would push a button on the hardware or shunt two terminals, but in the simulated object (obviously) I can't do that.
There are two concerns/requirements that I have:
I need to provide state changes and raise events for my unit tests
I need to provide state changes and raise events for my team to test dependencies on the component (e.g. a button on a WPF view becomes enabled when a certain hardware event occurs)
For the latter I thought about some complicated control panel dialog that would let me trigger events and generally simulate hardware operation and user interaction. This is complicated as it requires a component with no message pump to provide a window with controls. Stinky. Or another approach could be to implement the simulated component to take a "StateInfo" object that I could use to change the internals of the object.
This can't be a new problem, I'm sure many of you have had to do something similar to this and I'm just wondering what patterns or strategies you've used to accomplish this. I know I can access private fields with a n accessor, but this doesn't really provide an interactive (in the case of runtime simulation) changes.
If there is an interface on the library you use to interact with the external hardware you can just create a mock object for it and raise events from that in your unit tests.
If there isn't, then you'll need to wrap the hardware calls in a wrapper class so you mock it and provide the behaviours you want in your test.
For examples of how to raise events from mock objects have a look at Mocking Comparison - Raising Events
I hope that helps!
We have a large messy app written in C++ and Qt4, many library dependencies, hundreds of classes and no coherent structure. It normally runs as a GUI app manipulated interactively, but sometimes it's launched in a hands-off way from another program that feeds it command line options and communicates with it by dbus. The GUI still shows, but no human or trained monkey is there to click anything. "Relaxen und watch das blinkenlights" Whether interactively or automatically, when run the app writes image files.
My job the next few weeks is to add an "no gui" feature, such that the app can run in the hands-off way and write its image files, without ever showing its GUI. Internally, the images to be written are made using QImage and other non-GUI Qt objects, but these are possessed by other objects that do involve the GUI classes of Qt. After several attempts to understand the mess, I cannot find a way to disentangle things such as to have the app create images w/o the whole full-blown GUI running. At one time, I was hoping I could just set xxx.visible= false; for all xxx that are GUI objects, but this is not practical or possible (AFIK).
Are there any general strategies to follow to add this no-gui feature to this app? Some technique that won't require deep redesign of the class hierarchy?
The long and hard way is finding out what and how the logic is executed, extract the logic to some QObject based classes (with signals and slots) and make it a QtCore app. I know this doesn't help, but that's the correct way.
If setting all GUI elements to hidden (or perhaps only the QMainWindow?) is not an option, this is the only thing you can do.
Qt allows you to do this, but if the original coder did not plan this in, you've got a lot of refactoring/recoding to do.
This really depends on how the program is written. If the logic is somewhat seperated from the interface, then it could be as simple as finding out what class inherits from the QMainWindow class and making sure that is never initialised.
In the case where the logic is all over the place, I'd strongly suggest trying to get all the logic into a form of signal or slot (which has probably already happened considering that it's a GUI app), then just not initialising the QMainWindow instance and calling these manually.
Try to subclass interface classes (QMainWindow, QDialog, etc), and implement your logic there.