Are there any known design principles, best-practices and design patterns that one can follow while designing a C project? Or useful design principles for procedural (imperative) programming in general?
(I'm child of the 'object-oriented generation' and have to design a large C project for the first time)
Software Design Principles are a set of guidelines that helps developers to make a good system design. In the development process, the time for writing code will only consume from 20 to 40 percent, remaining we will read code and maintain the system. So, Making a good system design is very important.
Yes, there are. Lazy initialization, singleton, object pool, object state etc. are easily implemented in pure C.
One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic. The only problem with a factory method is it relies on the concrete component.
Design Patterns in the object-oriented world is a reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description of how to solve problems that can be used in many situations. "A pattern is a recurring solution to a problem in a context."
Information hiding - as espoused by Parnas (Software Fundamentals).
Careful management of headers and visibility:
The header is self-protected - so it does not matter if it is included multiple times.
#ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED ...rest of header contents, including other #include lines if necessary #endif /* HEADER_H_INCLUDED */
Design sets of functions to work on 'objects' (usually structures) - and use those functions rather than poking around the innards of the structure in the code that is using it. Think of it as self-imposed encapsulation.
My three advices:
Here's an example:
typedef struct Vector { int size; int limit; int* ints; } Vector; Vector* Vector_new() { Vector* res = (Vector*) malloc(sizeof(Vector)); res->limit = 10; res->size = 0; res->ints = (int*) malloc(sizeof(int) * res.limit); return res; } void Vector_destroy(Vector* v) { free(v->ints); free(v); } void Vector_add(Vector* v, int n) { if(v->size == v->limit) { v->limit = v->limit * 2 + 10; v->ints = realloc(v->ints, v->limit); } v->ints[v->size] = n; ++v->size; } int Vector_get(Vector* v, int index) { if(index >= 0 && index < v->size) return v->ints[index]; assert false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With