UseTheRightAPI

From Buzztard

Jump to: navigation, search

Contents

[edit] glib

[edit] g_free() can accept NULL

Yes its superfluous to write if(str) g_free(str); as this becomes more of less if(str) if(str) free(str); Please just remove the extra if.

[edit] G_TYPE_INSTANCE_GET_PRIVATE

This is a common mistake. The macro looks innocent, but is quite expensive. The gobject API docs explain how to avoid it. The mistake is to call this everytime when you need to get the pointer to your private data. Instead call this one in instance_init and cache as self->priv (it is intentinally called priv, as private is a C++ keyword).

[edit] g_timeout_add -> g_timeout_add_seconds

This helps to bundle wakeups if you run multiple timeouts at the same time. Imho it also helps readability, just compare g_timeout_add(4000,...) with g_timeout_add_seconds(4,...) - the later carries the unit in the api name, for the former you will have to know that it is in milliseconds.

[edit] g_idle_add, g_timeout_add{,_seconds}

  • make sure that the callback is a gboolean function and returns FALSE when this does not need to be called again..
  • make sure the callback is liightweight, especially if its getting called a multiple times.

[edit] g_strsplit -> g_strsplit_set

g_strsplit_set only works on ascii, but it is faster as it does not need to do UTF-8 handling.

[edit] g_assert vs. g_return_{val_,}if_fail

In static functions use g_assert() instead of g_return_{val_,}if_fail to check the validity of passed parameters. Ensure the validity already when a public method was called. In the public method one should not use assert on parameters, as their validity cannot be guaranteed. In private functions one can. For a release builds one can then use CFLAGS=-DG_DISABLE_ASSERT to get rid of the asserts. I would not recommend to use CFLAGS=-DG_DISABLE_CHECKS to also disable the g_return_{val_,}if_fail macros though.

[edit] gtk

[edit] gtk_label_new (""); -> gtk_label_new (NULL);

yes, gtk_label_new is smart and only copies the text if (str && *str), but still...

Personal tools
collaboration

SourceForge Logo

GStreamer Logo

Become a Friend of GNOME

Linux Sound Logo

MediaWiki

Valgrind

GNU Library Public Licence

GNU Free Documentation License 1.2