Objects in C

    

Naming conventions can convey semantic conventions both of which can help APIs easier to understand, remember and even design. The following describes some conventions I've adopted for writing C code in an object oriented style.


Structures      Member names are words that begin with a lower case character with successive words each having their first charater upper cased. Acronyms are capitalized. Structure names are words with first character capitalized. An example:
typdef struct 
{
  char *firstName;
  char *lastName;
  char *address;
} Person;


Functions      Function names begin with the name of structure they operate on followed by an underscore and the method name. Each structure has a new and free function. An example:
List *List_new(void);
void List_free(List *self);
Example implementation of new and free functions:
List *List_new(void)
{
  List *self = (List *)calloc(1, sizeof(List));
  self->items = malloc(LIST_DEFAULT_SIZE);
  return self;
}

void List_free(List *self)
{
  free(self->items);
  free(self);
}
Aside from new methods, all methods pass a pointer to the object as the first argument and name this argument "self". Method names are in keyword format. That is, for each argument, the method name has a description followed by an underscore. The casing of the descriptions follow that of structure member names. Examples:
int List_count(List *self); /* no argument */
void List_add_(List *self, void *item); /* one argument */
void Dictionary_key_value_(Dictionary *self, char *key, char *value); 


Defines      Defines are all caps words that are seperated by underscores. Define names always begin with the name of the structure that they are most closely related to. Examples:
#define LIST_DEFAULT_SIZE 8
#define LIST_RESIZE_FACTOR 2


File Names      Each structure has it's own seperate .h and .c files. The names of the files are the same as the name of the structure. These files contain all the functions(methods) that operate on the given structure.