C++ Notes: Idiom: Separate User Interface from Logic
User interface I/O (eg, cin
or cout
) should be
restricted to only a few functions which are specifically
designed for that purpose. For small programs it may be
restricted to the main()
function. There may be
utility functions which are used primarily for I/O.
Debugging code is allowed. While you are debugging a program,
it may be useful to put output statements at various points to monitor
the execution.
GUI and CLI
One test to apply to your program is whether the essential
logic or model of your program could be
attached to a GUI (Graphical User Interface) just as easily
as to the CLI (Command Line Interface).
A yes answer goes a long way toward a well organized
program.
If the answer is no, perhaps the program can
be improved. If "the medium is the message", or in other words,
the program is about creating an interface experience, then
there may be no way separte the presentation from the logic.
Handling deep errors - exceptions
When an error is discovered many function calls deep in a program,
an effective way to produce an error message without I/O is by
throwing an exception. Don't print an error message;
always imagine that the program might have a GUI interface and
there is no console window for the user.