I’m refactoring an old C code. The code has absolutely no layered architecture (everything is being accessed by everything) and I’m trying to change that.
I would like to cut direct access to structure members (at least write for now) and only allow access through access functions. Is there some tool (or perhaps directly the compiler) that could check this rule for me?
I need this since I’m maintaining a fork and the upstream isn’t very concerned with code quality.
The best way to ensure no new code accesses structures directly is to not make them available using total encapsulation. This comes at the cost of not being able to use a structure on the stack anymore. You provide a function to allocate the structure, another to free it, and all module functions accept a pointer to the structure. However, the definition of the structure itself is in the C file, and not the header file. Another disadvantage is that you may need to write a lot of functions to manipulate/query the structure.
I will provide snippets from an old code base where I’ve used this approach. The header contains:
The C file defines the structure
Queue_st, and implementations of the functions (heavily modified to highlight the approach):An alternative approach is to use
typedef struct StructName *StructHandle;, and replace all the pointers in the API withStructHandle. One less*to worry about.EDIT: If you want some members visible, and some not, it is also possible with an extension of the above approach. In your header, define:
In the C file, define the private members, and the functions that manipulate them.