UseTheRightAPI

From Buzztrax

Jump to: navigation, search


glib

g_free() can accept NULL

Yes, it is 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.

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).

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.

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 lightweight, especially if its getting called a multiple times.

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.

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.

use g_error_free() for GError and not g_free()

Check your code that you use the right free func!

gtk

gtk_label_new (""); -> gtk_label_new (NULL);

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

Support Us

Collaboration

GStreamer Logo
Become a Friend of GNOME
Linux Sound Logo
MediaWiki
Valgrind
GNU Library Public Licence
GNU Free Documentation License 1.2