glib dependency for the X Server

Bernardo Innocenti bernie at develer.com
Thu Apr 6 19:35:39 PDT 2006


Carsten Haitzler (The Rasterman) wrote:

> yeah- BUT for me - i tend to DESIGN my code where "0" is a plausible and
> DESIREABLE "default starting" value OR an invalid value (eg a NULL pointer -
> see above - i know about its caveats that it may NOT be 0)  so i wont
> de-reference a pointer if its null (ie the object hasn't been attached yet for
> example or its in a "created but not initialised state -

Such intermediate initialization states are a no-no since the RAII
concept was invented.  Forgetting to initialize stuff is one of the
most common sources of problems that are difficult to reproduce and
debug.

Sane C++ libraries (this would rule out MFC and its two-stage construction)
use constructors to make sure objects are either fully usable or don't
exist at all.

C programs can be designed to do the same by providing constructor
functions that do both the allocation and the initialization of
objects with a single call:

  foobar *fb = foobar_new();
  ...use fb...
  foobar_delete(fb);

This suggestion may seem very trivial, but there are far too
many APIs around that don't follow this simple pattern.

When static allocation is also needed, a second function
could do just the initialization step on an existing buffer:

  foobar fb;
  foobar_ctor(&fb);
  ...use fb...
  foobar_dtor(&fb);

In C, one would still have to be careful about destroying all
objects manually, but that's very difficult to do without C++.


> eg an image object
> would have a struct for its control info and properties but may not alloc the
> pixel data until needed - i.e. i may load an image file header and get its
> width, height, colorspace info etc., but not decode pixel data until demanded,
> saving a fair bit of work when you just want to create objects that don't become
> visible until later - or never)

There is a GoF pattern for safe lazy initialzation, but I can't
remember if it's called Proxy, Flyweight or something else.

Basically, the object acts as if it was fully initialized, but
the slow part of the initialization only happens the first time
a method needs to access the data.

The basic idea for robust APIs is to try as much as possible
to shield client code from implementation details such as these.

-- 
  // Bernardo Innocenti - Develer S.r.l., R&D dept.
\X/  http://www.develer.com/




More information about the xorg mailing list