| name | clean-code-functions |
| description | Use when designing, reviewing, or refactoring functions — applies Clean Code function principles for small, focused, well-argumented functions |
Clean Code: Functions
Based on Robert C. Martin's Clean Code, Chapter 3: Functions.
When to Use This Skill
Trigger on:
- Writing or reviewing function design
- Functions that are too long, do too much, or have too many arguments
- "Should I extract this into a function?" questions
- Debates about function size and structure
Rules
1. Functions Should Be Small
The first rule of functions is they should be small. The second rule is they should be smaller than that. Functions should rarely be longer than 20 lines.
2. Do One Thing
A function should do one thing, do it well, and do it only. If you can extract another function with a meaningful name, the original is doing more than one thing.
def process_user(user):
if not user.email:
raise ValueError("Email required")
db.save(user)
def validate_user(user):
if not user.email:
raise ValueError("Email required")
def save_user(user):
db.save(user)
3. One Level of Abstraction
All statements in a function should be at the same level of abstraction. Don't mix high-level business logic with low-level implementation details.
4. The Stepdown Rule
We want every function to be followed by those at the next level of abstraction, reading top-down like a newspaper article.
5. Use Descriptive Names
A long descriptive name is better than a short enigmatic name. If you have a well-named function, comments are often redundant.
6. Function Arguments
The ideal number of arguments is zero (niladic). One is fine (monadic). Two is ok (dyadic). Three should be avoided (triadic). More than three requires special justification.
def make_circle(x, y, radius, color, stroke_width, fill): ...
def make_circle(center: Point, radius: float, style: CircleStyle): ...
7. Avoid Flag Arguments
Boolean arguments loudly declare the function does more than one thing.
def render_page(is_uppercase):
if is_uppercase:
...render uppercase...
def render_uppercase_page():
...
def render_lowercase_page():
...
8. No Side Effects
A function should do what its name says. Hidden side effects create temporal couplings and order dependencies.
9. Command Query Separation
A function should either do something or answer something, but not both. Either change state or return data.
10. Extract Try/Catch Blocks
Try/catch bodies are ugly. Extract the body into a function of its own.
Quick Checklist
Source
Distilled from Clean Code by Robert C. Martin, Chapter 3: Functions.