C SOLID principles are five design guidelines—Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion—that help you write C code that is easier to maintain, test, and extend. This guide explains each principle with concrete C examples, common pitfalls, and how to apply them without over-engineering small projects.
Why SOLID Matters in C
SOLID is usually taught with object-oriented languages like Java or C++, but the underlying ideas apply directly to C. C programs often grow into large files with tightly coupled functions and global state, making changes risky and testing hard. SOLID gives you a checklist to keep modules independent, interfaces narrow, and dependencies pointing in a safe direction. Even if you never use OOP, these principles help you structure structs, function pointers, and header files so that a change in one part doesn’t break everything else.
Single Responsibility Principle (SRP)
SRP says a function, struct, or module should have only one reason to change. In C, this often means splitting a function that both parses input and writes output into two functions. For example, instead of one process_file() that reads a CSV, validates rows, and prints a report, create read_csv(), validate_row(), and print_report(). Each function can be tested independently and reused elsewhere.
- Sign of violation: A function with multiple unrelated parameters or several sections that change for different reasons.
- Fix: Extract each responsibility into its own function or file.
SRP doesn’t mean every function must be tiny—it means each function should have a clear, single purpose. A function that calculates both area and volume probably does two things; split them.
Open/Closed Principle (OCP)
OCP states that software should be open for extension but closed for modification. In C, you achieve this with function pointers and structs that hold behavior. For example, a sorting function can take a comparison function pointer, letting you sort integers, strings, or custom structs without changing the sort code. Similarly, a device driver can expose a struct of operations (init, read, write) that you fill in for each new device.
typedef struct {
int (*compare)(const void*, const void*);
} Sorter;
void sort(void* base, size_t n, size_t size, Sorter* s);
Now you can add a new comparison function without touching sort(). This is the essence of OCP: you extend behavior by adding new code, not by editing existing, tested code.
Liskov Substitution Principle (LSP)
LSP says that if you have a base type, you should be able to use any subtype without breaking the program. In C, this appears with inheritance-like structs: a base struct at the beginning of a derived struct, and function pointers that operate on the base. For example, a Shape struct with an area() function pointer, and a Circle struct that starts with a Shape then adds a radius. Code that takes a Shape* should work with a Circle* as long as the function pointers are set correctly.
The common violation is when a function checks the concrete type and behaves differently—like if (shape->type == CIRCLE). That breaks LSP because the caller must know the subtype. Instead, use virtual tables (vtable) or function pointers so the behavior is chosen by the object itself.
Interface Segregation Principle (ISP)
ISP says that no client should be forced to depend on methods it doesn’t use. In C, this means avoiding huge structs of function pointers that every user must fill. Instead, define smaller, focused interfaces. For example, a file I/O interface might have open, read, write, close. But a read-only client only needs read and close. If you force it to implement write (even as a stub), you violate ISP.
- Bad: One
DeviceOpsstruct with 10 function pointers, all required. - Good: Separate
ReadOpsandWriteOpsstructs, and a client takes only what it needs.
In practice, this keeps interfaces small and makes testing easier—you can mock only the functions you actually call.
Dependency Inversion Principle (DIP)
DIP says high-level modules should not depend on low-level modules; both should depend on abstractions. In C, this means your business logic should not call specific hardware or library functions directly. Instead, define an interface (function pointers) and have the low-level code implement it. For example, a logging module might define log_message(const char* msg) as a function pointer. The high-level code calls log_message(), but the actual implementation could write to a file, a serial port, or a network socket—chosen at startup.
void (*log_message)(const char*); void init_file_logger(FILE* f); void init_stdout_logger(void);
Now the high-level code doesn’t know or care where logs go. You can swap loggers without recompiling the whole program. This is the heart of DIP: depend on interfaces, not on concrete implementations.
Common Mistakes and How to Avoid Them
- Over-abstraction: Applying SOLID to a 200-line program adds complexity with little benefit. Start simple, refactor when you see actual pain.
- Function pointer overhead: Calling through a pointer is slightly slower than a direct call. For hot loops, this matters; for I/O-bound code, it doesn’t. Measure before optimizing.
- Ignoring error handling: SOLID often involves returning error codes or NULL. Make sure every function that can fail returns a status, and callers check it.
- Misunderstanding LSP: LSP is not about inheritance, it’s about behavioral compatibility. A
Circlethat setsareato NULL is not substitutable.
A common misconception is that SOLID requires OOP. It doesn’t. C’s function pointers and structs give you all the tools you need. The principles are about managing dependencies and responsibilities, not about classes.
How to Start Applying SOLID in C
- Start with SRP: Break large functions into smaller ones. This is the easiest win.
- Use function pointers for variation: When you have a switch on a type, consider a table of function pointers.
- Design interfaces by client: Ask “what does this caller need?” and define a minimal struct of function pointers.
- Inject dependencies: Pass a logger or a database handle into a function instead of using a global.
- Refactor gradually: Don’t rewrite everything. Apply a principle to the next module you touch.
For a small embedded project, you might only use SRP and DIP. For a large library, all five are valuable. The goal is maintainability, not purity.
Frequently Asked Questions
Q: Is SOLID only for object-oriented languages?
No. SOLID principles are language-agnostic. In C, you implement them with structs, function pointers, and separate compilation units. The ideas of single responsibility, open/closed, etc., apply to any code that has dependencies.
Q: How do I implement the Open/Closed Principle in C without classes?
Use function pointers. Define a struct that holds function pointers for operations, and let callers provide their own implementations. For example, a sort function takes a comparison function pointer, so you can sort any type without modifying the sort code.
Q: Does using function pointers hurt performance?
Indirect calls are slightly slower than direct calls because the CPU can’t predict the target as well. However, for most applications the difference is negligible. If you have a hot loop, you can inline or use macros, but first measure to see if it matters.
Q: What is the easiest principle to start with?
Single Responsibility. It’s straightforward: if a function does more than one thing, split it. This immediately improves readability and testability, and it’s hard to overdo.
Q: Can I use SOLID in embedded C with limited RAM?
Yes, but be mindful. Function pointers take space (4 or 8 bytes each). For a small MCU, using a few pointers is fine, but avoid large v-tables for every object. Focus on SRP and DIP, which often reduce code size by removing duplication.
Q: How do I test SOLID C code?
Because dependencies are injected via function pointers, you can pass a mock in tests. For example, a logger function pointer can be set to a test logger that records messages. This makes unit testing much easier than with global variables.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Omega ORU52X Specs: What They Mean for You42.00 cu ft
- AI Agent State Safety During Context Compaction
- Games Like Assassin’s Creed: 12 Open-World Picks
- KCD2 Blacksmith’s Son Quest Guide
- Delete Stations Pandora? How to Remove Them
- How to Play Brawl Stars Without an Emulator