Skip to content

Commit d50ddf0

Browse files
committed
Improve Clean Code rule using template
1 parent 4785e13 commit d50ddf0

File tree

1 file changed

+133
-52
lines changed

1 file changed

+133
-52
lines changed

rules/clean-code.mdc

Lines changed: 133 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,137 @@
11
---
2-
description: Guidelines for writing clean, maintainable, and human-readable code. Apply these rules when writing or reviewing code to ensure consistency and quality.
2+
description: Comprehensive guide to Robert C. Martin's Clean Code principles for writing maintainable, readable code that expresses intent clearly
33
globs:
44
alwaysApply: false
55
---
6-
# Clean Code Guidelines
7-
8-
## Constants Over Magic Numbers
9-
- Replace hard-coded values with named constants
10-
- Use descriptive constant names that explain the value's purpose
11-
- Keep constants at the top of the file or in a dedicated constants file
12-
13-
## Meaningful Names
14-
- Variables, functions, and classes should reveal their purpose
15-
- Names should explain why something exists and how it's used
16-
- Avoid abbreviations unless they're universally understood
17-
18-
## Smart Comments
19-
- Don't comment on what the code does - make the code self-documenting
20-
- Use comments to explain why something is done a certain way
21-
- Document APIs, complex algorithms, and non-obvious side effects
22-
23-
## Single Responsibility
24-
- Each function should do exactly one thing
25-
- Functions should be small and focused
26-
- If a function needs a comment to explain what it does, it should be split
27-
28-
## DRY (Don't Repeat Yourself)
29-
- Extract repeated code into reusable functions
30-
- Share common logic through proper abstraction
31-
- Maintain single sources of truth
32-
33-
## Clean Structure
34-
- Keep related code together
35-
- Organize code in a logical hierarchy
36-
- Use consistent file and folder naming conventions
37-
38-
## Encapsulation
39-
- Hide implementation details
40-
- Expose clear interfaces
41-
- Move nested conditionals into well-named functions
42-
43-
## Code Quality Maintenance
44-
- Refactor continuously
45-
- Fix technical debt early
46-
- Leave code cleaner than you found it
47-
48-
## Testing
49-
- Write tests before fixing bugs
50-
- Keep tests readable and maintainable
51-
- Test edge cases and error conditions
52-
53-
## Version Control
54-
- Write clear commit messages
55-
- Make small, focused commits
56-
- Use meaningful branch names
6+
# Clean Code Principles
7+
8+
A comprehensive guide to writing clean, maintainable, and readable code based on Robert C. Martin's "Clean Code" principles. These rules focus on creating code that clearly expresses intent, is easy to understand, modify, and maintain over time.
9+
10+
## Context
11+
12+
Provide guidelines for writing code that prioritizes readability, simplicity, and maintainability over cleverness or optimization.
13+
14+
*Applies to:* All software development projects, code reviews, refactoring efforts
15+
*Level:* Tactical/Operational - direct application in daily coding practices
16+
*Audience:* All developers, from junior to senior levels
17+
18+
## Core Principles
19+
20+
1. *Clarity over Cleverness:* Code should be written to be read and understood by humans first, machines second
21+
2. *Express Intent:* Names, functions, and structure should clearly communicate what the code does and why
22+
3. *Simplicity:* Prefer simple, straightforward solutions over complex, over-engineered ones
23+
4. *Single Responsibility:* Each unit of code should have one clear purpose and reason to change
24+
5. *Leave it Better:* Always improve code when you touch it, following the Boy Scout Rule
25+
26+
## Rules
27+
28+
### Must Have (Critical)
29+
30+
- *RULE-001:* Use meaningful, pronounceable names for variables, functions, classes, and modules
31+
- *RULE-002:* Functions must be small (ideally <20 lines) and do one thing well
32+
- *RULE-003:* Eliminate code duplication - follow the DRY principle strictly
33+
- *RULE-004:* Remove commented-out code and dead code before committing
34+
- *RULE-005:* Use consistent formatting and indentation throughout the codebase
35+
36+
### Should Have (Important)
37+
38+
- *RULE-101:* Functions should have no more than 3 parameters; use objects for more complex parameter sets
39+
- *RULE-102:* Avoid deep nesting (>3 levels) - extract methods or use early returns
40+
- *RULE-103:* Write self-documenting code that reduces need for comments
41+
- *RULE-104:* Use intention-revealing names rather than mental mapping (avoid single-letter variables except for short loops)
42+
- *RULE-105:* Keep classes small and focused on a single responsibility
43+
44+
### Could Have (Preferred)
45+
46+
- *RULE-201:* Prefer composition over inheritance
47+
- *RULE-202:* Use descriptive error messages and proper exception handling
48+
- *RULE-203:* Order functions by level of abstraction (high-level first, details later)
49+
- *RULE-204:* Minimize dependencies between modules and classes
50+
- *RULE-205:* Use consistent verb/noun naming conventions (getUser, calculateTotal, isValid)
51+
52+
## Patterns & Anti-Patterns
53+
54+
### ✅ Do This
55+
56+
```javascript
57+
function calculateMonthlyPayment(principal, interestRate, termInYears) {
58+
const monthlyRate = interestRate / 12;
59+
const numberOfPayments = termInYears * 12;
60+
61+
return (principal * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -numberOfPayments));
62+
}
63+
64+
const userAccount = {
65+
id: userId,
66+
email: userEmail,
67+
isActive: true
68+
};
69+
```
70+
71+
### ❌ Don't Do This
72+
73+
```javascript
74+
function calc(p, r, t) {
75+
// Calculate monthly payment
76+
let mr = r / 12;
77+
let n = t * 12;
78+
return (p * mr) / (1 - Math.pow(1 + mr, -n));
79+
}
80+
81+
// TODO: fix this later
82+
// const oldUserData = getUser(id);
83+
const u = { id: uid, e: ue, a: true };
84+
```
85+
86+
## Decision Framework
87+
88+
*When rules conflict:*
89+
1. Prioritize readability and maintainability over performance optimizations
90+
2. Choose the solution that makes the code's intent most clear
91+
3. Consider the team's collective understanding and skill level
92+
93+
*When facing edge cases:*
94+
- Ask "Would a new team member understand this code in 6 months?"
95+
- Prefer explicit over implicit behavior
96+
- When in doubt, err on the side of being more verbose and clear
97+
98+
## Exceptions & Waivers
99+
100+
*Valid reasons for exceptions:*
101+
- Performance-critical code paths with demonstrated bottlenecks (document trade-offs)
102+
- Legacy system integration requiring specific patterns (temporary, with migration plan)
103+
- Third-party API constraints that force specific implementations
104+
105+
*Process for exceptions:*
106+
1. Document the exception, rationale, and performance/business justification
107+
2. Add technical debt tracking item for future refactoring
108+
3. Review exceptions quarterly to assess if constraints still apply
109+
110+
## Quality Gates
111+
112+
- *Automated checks:* Linting rules for naming conventions, function length, complexity metrics
113+
- *Code review focus:* Readability, naming clarity, function size, duplication elimination
114+
- *Testing requirements:* Unit tests must be as clean and readable as production code
115+
116+
## References
117+
118+
- [Clean Code by Robert C. Martin](https://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)
119+
- [Refactoring by Martin Fowler](https://refactoring.com/)
120+
- [The Pragmatic Programmer](https://pragprog.com/titles/tpp20/the-pragmatic-programmer-20th-anniversary-edition/)
121+
122+
---
123+
124+
## TL;DR
125+
126+
*Key Principles:*
127+
- Write code for humans to read, not just machines to execute
128+
- Use clear, descriptive names that express intent without requiring comments
129+
- Keep functions small, focused, and doing only one thing well
130+
131+
*Critical Rules:*
132+
- Must use meaningful names for all variables, functions, and classes
133+
- Must keep functions under 20 lines and eliminate all code duplication
134+
- Must remove dead code and maintain consistent formatting
135+
136+
*Quick Decision Guide:*
137+
When in doubt: Choose the option that makes the code's intent most obvious to a future reader.

0 commit comments

Comments
 (0)