C++ Output: GUI or Console? - c++

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...

Related

Class Design in C++ program

I'm currently working on a little project in C++. I'm fairly new to C++/Programming and wanted to ask how my classes should be designed.
To be specific: I want to write a little program for chatting. Just simple communication between two programs/computers. For that I want to use a good class design because, although it is only a small project (just for the sake of learning), I want it to be well designed and extensible.
My program should have about 5 classes (Handlers etc, the Updater and App - the main class only for this program).
I'll give you a few examples of ideas I have how I could design one part of the program. The first part should be the connection part (handled by Connection). The task is to build up a connection between the two programs. It will also set up local files, which will hold the information to print, and connect it to the 'server' file. Later in the program there should be access to the File_Handler class so it can edit/read the local file and read/request to write to the 'server' file. (How exactly it's gonna do it is already figured out, so as long as it is not necessary I'd like to keep this system as it is ;) ). But now let's get to the ideas I have:
Idea 1
App creates an instance of Connection to set up the connection.
Connection then creates an instance of File_Handler which will set up the files (in this case File_Hanlder would hold the paths with static variables) and then destroy that instance because it is no longer needed by Connection.
Another class (instance is held by App) then creats an own instance of File_Hanlder later and could work with the files since the variable for the path is static.
Idea 2
App creates an Instance of Connection and File_Handler (lets call them con and fil).
To set up the connection, fil is passed per reference to con to set up the variable paths for the files and create the files etc. .
For working with the files later, App would pass around fil to manage all the file handling for the other classes which would, for example, update the chat etc.
That would require a lot of classes to have a constructor or (a) function(s) which needs to have a File_Handler parameter and the same variable would be passed around a lot of times.
Idea 3
The last idea I have is that Connection, File_Handler and the other classes would be created very general without any or near to zero relation to other classes.
App then creates a lot of functions (or even 'subclasses') to work with these classes almost like working with Frameworks which were developed independently and thus could, theoraticly, be used in another program without any problems.
Which solution do you think would be the best? Or is there another solution you have for me which would be even better?

Strategy to simulate events in object under test

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!

Show value in progressbar from native method

I have some native code and want to update the progressbar from the native code. There isn't no return value because it is a long duration task.
I found a small example http://developer.android.com/reference/android/widget/ProgressBar.html but when I move the update part in a extra method I get a NullPointerException.
It seems that this part must be in the thread of the progressbar.
I tried another way by using the AsyncTask as nested class, but I haven't access on the method publishProgress from anywhere outside the class itself.
Is there any possibility to get it working?
If it is possible to break your long task into multiple incremental calls then I'd recommend doing that. Then you can make those calls from a loop inside AsyncTask.doInBackground(), just like in the SDK examples.
If that's not possible, you'll need a progress variable in your native code that can safely be accessed from multiple threads: Write to it from your worker code and read it from a new "getProgress()" JNI function, with the appropriate synchronisation done in native code. You would then be able to call your getProgress() function from AsyncTask.doInBackground(), or whatever UI scheme you choose to use.

How to de-GUI a complex tanglewad C++/Qt4 app?

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.

Keeping the GUI separate

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.