Boost logo

Boost :

From: Gary Powell (Gary.Powell_at_[hidden])
Date: 2001-03-20 16:34:49


>>
> Taking Win32 API as an example, in theory almost every function call there
> can fail, and consistent checking for it really helps to detect induced
> errors (and their sources, of course). The problem with having only
> classic
> 'assert'-like macro as a checking tool for such errors is that consistent
> application of "check a return value of every API function call" policy
> makes your code much more bloated and clumsy, e.g.:
>
> void clipboard::put_text(std::string const& text) {
> HGLOBAL handle = ::GlobalAlloc( GHND, text.length() + 1 );
> // copy text to allocated memory
> // ..
> // copy text to clipboard
> bool result1 = ::OpenClipboard(0);
> assert(result1);
> bool result2 = ::EmptyClipboard();
> assert(result2);
> bool result3 = ::SetClipboardData(CF_TEXT, handle);
> assert(result3);
> bool result4 = ::CloseClipboard();
> assert(result4);
> }
>
> vs.
>
> void clipboard::put_text(std::string const& text) {
> HGLOBAL handle = ::GlobalAlloc( GHND, text.length() + 1 );
> // copy text to allocated memory
> // ..
> // copy text to clipboard
> sys_verify(::OpenClipboard(0));
> sys_verify(::EmptyClipboard());
> sys_verify(::SetClipboardData(CF_TEXT, handle));
> sys_verify(::CloseClipboard());
> }
>
> You can beautify the first version a little by rearranging the code like
> this:
>
> { bool result = ::OpenClipboard(0); assert(result); }
> { bool result = ::EmptyClipboard(); assert(result); }
> // etc.
>
> but IMO 'sys_verify' version is still much more appealing here.
<<
IMO this sort of API cries out for exceptions.

void foo ()
{
  try {
     put_text(TextString);
 }
 catch (TextErrors &terr)
 {
   // do something useful here with terr.
 }
 // let unknown errors percolate up the stack.

 -gary-

gary.powell_at_[hidden]


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk