Saturday, February 17, 2018

Some rules for designing libc style APIs

  1. Identifiers should not have vowels; they are expensive and difficult to type.
  2. An identifier must not be longer than 8 characters. The only exception are functions intended for standardization like sched_ss_init_budget.
  3. Functions must not be reentrant. Relying on internal state means you can avoid allocating memory.
  4. Functions should take at least two parameters. The second parameter should be a "flags" parameter which causes the function to do entirely different things.
  5. Flags should be passed as macros with unspecified values. These macros must not have reasonable values.
  6. Error handling must be done in one of two ways. The choice must not be consistent with other functions in the library:
    1. The real return value should be stored in an "out" parameter. The return value must only determine if an error has occurred or not.
    2. If an error occurs, the return value must be undefined. The return value can't be safely used without checking for errors using a separate function (e.g., fgets).
  7. The error code should be in errno, requiring the setting of `errno = 0` beforehand and checking after an error occurs. However, the return value should be a value legally allowed to be in errno, so that initial attempts to use the function appear to work.
  8. If the function returns a string, it must do so by modifying a memory location given as a parameter. Whether or not the string is terminated with a null must be determined solely based on the length of the output, a user supplied parameter, and choice of compiler.
Thanks to jp, okdana for the inspiration and review; thanks to gonzo, arbrock for review.

No comments:

Post a Comment

Have something you want to say? You think I'm wrong? Found something I said useful?
Leave a comment!