What Is Clean Code?
Clean Code Principles
Clean code is code that is easy to read, understand, modify, and test. Named after Robert C. Martin's book, clean code principles emphasize meaningful names, small functions, minimal comments (the code should be self-documenting), and avoiding duplication. Code is read 10x more than it's written.
How Clean Code Works
Dirty: function calc(d, t) { return d / t * 3.6; }. Clean: function calculateSpeedKmh(distanceMeters, timeSeconds) { const METERS_PER_SEC_TO_KMH = 3.6; return (distanceMeters / timeSeconds) * METERS_PER_SEC_TO_KMH; }. The clean version explains itself — no comment needed.
Key Concepts
- Meaningful Names — Variables, functions, and classes named by what they represent — no abbreviations or single letters
- Small Functions — Functions do one thing, do it well, and do it only — typically 5-15 lines
- DRY — Don't Repeat Yourself — extract duplicated logic into shared functions
- Boy Scout Rule — Leave the code cleaner than you found it — improve a little with every change
Frequently Asked Questions
Is Clean Code always better?
Clean Code principles are guidelines, not laws. Performance-critical code may sacrifice readability. Prototype code doesn't need perfect structure. Apply clean code where it matters — production code that others maintain.