Re: Quick question on Glib style/design


Keith Sharp <kms passback co uk> writes:

> I would go with:
> - Create an object Foo using GObject (and all the convenience macros)
> - Create an object Bar that inherits from FOO, again using GObject
> - You can then define methods/functions such as:
> 	foo_do_action (Foo *obj);
> 	bar_do_action (Bar *obj);
> - Inside foo_do_action you would check:
> 	g_assert (FOO_IS (obj));

For the record, Keith meant `IS_FOO' -- or `ACME_IS_FOO', had the full
class name been `AcmeFoo'.

Also, `g_return_if_fail' or `g_return_val_if_fail' should be used
instead of `g_assert' to check preconditions, except when

  a) carrying on running the application is actually more dangerous
     than immediately crashing it (which is a rare case); or

  b) the function can only be called from local code, so that it's
     relatively easy to prove that the check will never actually fail.

This leads to more stable applications.  For instance, a bug in a
rarely used and unimportant part of a text editor will not cause the
application to crash before the user gets a chance to save their work.
Instead, the application will just make a hiccup, and loud and ugly
warnings will be printed to the terminal (or, if so configured,
displayed in a message box, logged to a file, etc.).

I don't remember where I first heard someone describe the symptom of a
programming error as the application ``making a hiccup'', but I love
the imagery.  :-)

> - You can use these:
> 	Bar *example;
> 	foo_do_action (FOO (example));

It's also common to use multiple, differently typed pointers to the
same object, in the same scope:

	Bar *bar;
	Foo *foo;

	foo = FOO (bar);

	foo_do_action (foo);
	bar_do_action (bar);

This is useful for things like widgets, where a large part of the API
belongs to a superclass.


Daniel Brockman
drlion deepwood net

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]