Re: Handling error/status messages by interface to C++ programs
Leslaw Bieniasz schrieb:
Hi,
I am writing a C++ program that does a job similar to a typical compiler:
It reads some source text, analyses it for errors, and performs some
conversion to a target format. I have a problem how to design the
communication between my code and user interfaces, to achieve
the following goals:
1) The code should be able to run either in the console mode, or
within a Windows GUI, but the kernel part of the code should be designed
in such a way so that it is independent on the interface.
You have (at least) two different solutions for this problem. You can
either create a console mode program, or put the compiler stuff into a
library. I choose to create a library such cases, with a small stub
executable for the console mode which calls the functions from the
library. The main advantage of this approach is that in the GUI the
errors from the compilation does not to be parsed, but can come from a
well specified interface. Also I use the strategy pattern[1] to notify
the GUI about the progress.
This is the outline of such a system:
class Progress
{
public:
// The function which the compiler calls when something changed
virtual void progress(int state) = 0;
// Errors callback
virtual void error(int line, std::string message) = 0;
// Always add a destructor to classes with virtual functions
~Progress();
};
class GuiProgress: public Progress
{
public:
virtual void progress( int state )
{
m_progressBar.setState( state );
}
virtual void error(int line, std::string message)
{
showDialog( message );
}
};
class GuiProgress: public Progress
{
public:
virtual void progress( int state )
{
std::cout << "progress: " << state / 100.0 << '%' << std::endl;
}
virtual void error(int line, std::string message)
{
std::cerr << "Error on line " << line << ": " << message << '\n';
}
};
class Compiler
{
public:
void compile( std::istream& input, Progress& pg );
};
bye
Rudi
[1] http://en.wikipedia.org/wiki/Strategy_pattern