c - Make sure bad patterns don't come back after refactoring -


i'm refactoring old c code. code has absolutely no layered architecture (everything being accessed everything) , i'm trying change that.

i cut direct access structure members (at least write now) , allow access through access functions. there tool (or perhaps directly compiler) check rule me?

i need since i'm maintaining fork , upstream isn't concerned code quality.

the best way ensure no new code accesses structures directly not make them available using total encapsulation. comes @ cost of not being able use structure on stack anymore. provide function allocate structure, free it, , module functions accept pointer structure. however, definition of structure in c file, , not header file. disadvantage may need write lot of functions manipulate/query structure.

i provide snippets old code base i've used approach. header contains:

#ifndef inc_queue_h #define inc_queue_h  typedef enum {     que_ok,     que_bad_param,     que_no_memory,     que_sys_error } que_rv;  typedef struct queue_st queue_t;  que_rv que_new(queue_t **ppqueue); que_rv que_put(queue_t *pqueue, int priority, void *pdata); que_rv que_get(queue_t *pqueue, int *priority, void **ppdata); void que_free(queue_t *pqueue);  #endif /* inc_queue_h */ 

the c file defines structure queue_st, , implementations of functions (heavily modified highlight approach):

#include "queue.h" #include "log.h"  #define que_initial_capacity 128  struct queue_st {     /* snip: structure contents go here */ };  que_rv que_new(queue_t **ppqueue) {     que_rv rv;      *ppqueue = malloc(sizeof(queue_t));      /* snip: check malloc, initialize structure here ... */      return que_ok; }  void que_free(queue_t *pqueue) {     if (pqueue != null)     {         /* snip: free contents of structure before free below... */         free(pqueue);     } } 

an alternative approach use typedef struct structname *structhandle;, , replace pointers in api structhandle. 1 less * worry about.


edit: if want members visible, , not, possible extension of above approach. in header, define:

typedef struct structpriv structpriv;  typedef struct {     /* public members go here */      structpriv *private; } struct;  struct *struct_create(); void struct_free(); 

in c file, define private members, , functions manipulate them.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -