link: https://www.youtube.com/watch?v=YMPlQCYp7xg

The 3 Laws of Writing Bug-Free Code

1. Modularize Your Code

  • Separate Concerns: Split your code into small, modular functions, each handling a specific responsibility. This avoids jumbled code that is difficult to manage and test.
  • Bug Detection: Modular code makes it easier to spot bugs, as each part can be isolated and tested independently.
  • Professional Workflow: By organizing code into distinct functions, professionals ensure each section’s functionality is clear and maintainable before even reaching code review.

2. Write Unit Tests

  • Test Individual Components: Each function should be covered by a unit test, ensuring its behavior is correct in isolation.
  • Documentation Through Tests: Instead of adding lengthy comments in the code, unit tests serve as live documentation. They define the expected functionality, making the code self-explanatory.
  • Avoid Integration Testing for Simple Tasks: If code isn’t modular, testing one component (e.g., email validation) may require running the entire function and its dependencies (like databases), making it an expensive integration test rather than a simple unit test.

3. Regression Testing

  • Catch Bugs Early: Once modularization and unit testing are in place, tests will automatically catch bugs before code review. In a Continuous Integration/Continuous Deployment (CI/CD) pipeline, tests will fail if any component is broken, saving time and effort.
  • Fix and Validate Changes: After fixing issues that caused test failures, it is important to run the tests again to ensure nothing else breaks.
  • Regression Testing Defined: When a previously working behavior no longer works after making changes, it is called regression. Running tests after changes is known as regression testing and helps catch these kinds of issues.

Conclusion

  • Three Laws of Bug-Free Code:
    1. Write modular, maintainable code.
    2. Write unit tests for individual components.
    3. Conduct regression testing frequently.