Node:How to Implement, Next:How to Code, Previous:Introduction, Up:Top
While it is good to believe that there is good in everybody, it is better to not rely on that.
Virtually every piece of code depends on underlying systems, either soft- or hardware. Software can have bugs, hardware can fail. Even your own code can have bugs. You can't do anything against that. But you can reduce the impact bugs and hardware failures have on the system.
Many functions provide return values that tell about success or failure of the function. If a function fails, react reasonably. Ignoring return values from a function can be like Russian roulette.
Every function you write (especially the external ones) carry the risk of being called with invalid parameters. A good function always behaves correct, even when it is called incorrectly.
If you use the glib library, the macros g_return_if_fail()
and
g_return_val_if_fail()
provide a good way of checking parameters.
But what is correct behaviour when parameters make no sense? The answer is clear:
Provide a means for the caller of your function to perceive failure. Make it possible to distinguish between different reasons of failure, if it could make sense for the caller to react differently. If your function fails, do not (besides the error code) return something that could look like a reasonable result (for example, if your function should return a pointer to a newly-allocated dynamic variable, always return a NULL pointer if it fails. Never return a random pointer, or a pointer to a improperly initalized data structure).
In a switch
statement, always use default
. If only specific
cases are valid, place an assertion after the default
.
If you use the glib library, use g_assert_not_reached()
.