[Vala] [Fwd: Re: g_assert vs. g_return_if_fail]



I think this might also be of interest to people here.

-------- Přeposlaná zpráva --------
Od: Robert Pearce <rob bdt-home demon co uk>
Komu: gtk-list gnome org
Předmět: Re: g_assert vs. g_return_if_fail
Datum: Wed, 20 Jan 2010 23:00:58 +0000

Hi Jiří,

On Wed, 20 Jan 2010 23:04:34 +0100 you wrote:

No problem. I'm just wondering why there are two methods that do the
same thing just slightly differently, 

They're not the same thing - one of them gives up on a particular function, the other aborts the 
application.

while one of them shouldn't be
used.

I don't believe anyone said that. Somebody did say that g_assert should not be used where g_return_if_fail 
is used, because they do different things.

So I guess my question is: What are the use cases for
g_return_if_fail and what are the use cases for g_assert? (GLib newbie
here)

You should use g_assert in code under development to make explicit the assumptions of that code. So if your 
function does not handle the case of SomeVariable being negative, because you cannot envisage a case where 
it could ever be negative, then it is appropriate to add g_assert ( SomeVariable >= 0 ) at that point. If 
your assumption turns out to be wrong then it will become obvious during development.

You should use g_return_if_fail to cope with bad arguments to functions when you don't have control of the 
caller. This is the case in library functions, of course, which is why Gtk widget implementations use it a 
lot. For example, in the gtk_label_set_text implementation there's several g_return_if_fail tests of the 
first argument being a pointer to a GtkLabel, and the second being some text. If the programmer using the 
library gets this wrong it's not up to the library to crash his program for him; that would be damned 
annoying at the very least. But if the check wasn't there and the programmer got it wrong then the library 
probably would crash with a mystery segfault. So writers of libraries should use g_return_if_fail 
liberally, because it protects the user of the library and provides more helpful responses to mistakes.
_______________________________________________
gtk-list mailing list
gtk-list gnome org
http://mail.gnome.org/mailman/listinfo/gtk-list

Attachment: signature.asc
Description: Toto je digitálně podepsaná část zprávy



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