This is what i learned about C Clean Code from Uncle Bob’s seminar.
2 min readJul 16, 2023
Uncle Bob, also known as Robert C. Martin, is a renowned software engineer and author who has contributed significantly to the software development community. He is an advocate of clean code practices and has written extensively on the subject.
Here are some key pointers from Uncle Bob regarding writing clean code in C:
- SRP (Single Responsibility Principle): Ensure that each function and module in your C code has a single responsibility. This makes the code easier to understand, test, and maintain.
- DRY (Don’t Repeat Yourself): Avoid duplicating code. Duplication leads to maintenance issues and increases the chances of introducing bugs. Encapsulate common functionality in functions or macros.
- Avoid Deep Nesting: Similar to the previous list, Uncle Bob emphasizes the importance of avoiding deep nesting of code. It makes the code harder to read and understand. Aim for a maximum nesting level of 2 or 3.
- Meaningful Names: Use descriptive and meaningful names for variables, functions, and other identifiers. This improves the readability of your code and helps other developers understand your intentions.
- Consistent Formatting: Consistency in formatting is crucial for clean code. Follow a standard indentation style, brace placement, and spacing throughout your codebase.
- Function Length: Keep functions short and focused on doing one thing well. Short functions are easier to comprehend, test, and maintain.
- Use Appropriate Data Types: Choose the right data types for your variables and function parameters. This promotes clarity and ensures that your code is robust and safe.
- Comments and Documentation: Add comments where necessary to explain complex algorithms or any non-obvious logic. However, the code should be self-explanatory with meaningful names and a clear structure.
- Error Handling: Handle errors properly, and don’t ignore return values or error codes. Always check for errors and handle them appropriately.
- Avoid Global State: Minimize the use of global variables and mutable shared state. Global state can lead to unexpected side effects and make code harder to reason about.
- TDD (Test-Driven Development): Uncle Bob is a strong advocate of Test-Driven Development. Write tests first and then implement the code to make the tests pass. This ensures that your code is correct and maintains its correctness over time.
- Refactoring: Continuously refactor your code to improve its design and maintainability. Refactoring is a natural part of the development process and should be embraced.
- Use Version Control: Utilize version control systems like Git to track changes and collaborate with other developers effectively.
Uncle Bob’s principles on clean code are applicable not only to C but to software development in general. Following these guidelines will lead to more maintainable, readable, and robust code in any programming language, including C.