How to Teach Cursor AI to Write Clean Code with Cursor Rules
How to Teach Cursor AI to Write Clean Code with Cursor Rules
Hey there, fellow coder! I'm super excited to share something that has made my coding life so much better. Have you tried Cursor? It's an awesome AI-powered code editor that speeds up coding like having a super-smart friend by your side. But sometimes, even the smartest AI needs a little help to write code that's not just working but also clean and easy to read—the kind of code that makes you smile!
That's where Cursor Rules come in. They're like simple guides you give your AI to make sure it writes code the way you want. Once I started using them, my code became so much clearer. Let's jump in and see how you can teach Cursor AI to write clean code with Cursor Rules!
What Are Cursor Rules, in Simple Words?
Think of Cursor Rules like a guidebook for a new team member. They're talented but need to know your team's coding style. You'd give them a document saying, "This is how we write code, these are our patterns, and this is how we test."
Cursor Rules are exactly that for your AI. You create a file with instructions telling the AI how to write code for your project. You save these rules in a folder called .cursor/rules
in your project. This lets everyone on your team use the same rules, keeping your code neat and consistent.
My Favorite Rule: The "Clean Coder's Checklist"
This rule teaches the AI to write clean code, like having a top developer check every line. Here's the rule you can copy and paste into your project. It's written simply for everyone to understand.
Rule File: clean-code.mdc
---
title: The Clean Coder's Checklist
description: A rule to ensure all generated code is simple, readable, and easy to maintain.
globs: ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.py"]
alwaysApply: false
---
# The Clean Coder's Checklist
You are an expert coder who loves **clean code**. Clean code is easy for people to read and understand. Your goal is to write code that works well and looks great. Follow these rules every time:
## 1. Use Clear and Meaningful Names
Names in code are like labels. They should tell you what something is without guessing.
- **For variables:** Use names that show what the data is.
- **Good:** `userProfile`, `isLoading`, `customerList`, `remainingAttempts`
- **Bad:** `data`, `flag`, `arr`, `temp`
- **For functions:** Use names that say what the function does. Use action words.
- **Good:** `fetchUserData()`, `calculateTotalPrice()`, `validateEmailAddress()`
- **Bad:** `process()`, `handleStuff()`, `go()`, `get()`
**Tip:** If you're writing a function to get user data, name it `fetchUserData()` instead of `getData()`. It's clearer! For example:
```javascript
// Bad
function getData() { ... }
// Good
function fetchUserData() { ... }
2. Keep Functions Small and Focused
Each function should do just one thing. If it does too much, it's hard to understand.
- A function should have one job.
- If a function gets data, changes it, and shows it, break it into smaller functions.
- Keep functions under 20 lines. Long functions mean they're doing too much.
Tip: Instead of one function doing everything, use three:
function fetchData() { ... }
function processData(data) { ... }
function displayData(processedData) { ... }
3. Write Helpful Comments (But Not Too Many)
Good code explains itself. Comments are for when the code can't.
- Write comments to explain why you did something, not what.
- Good:
// We use this sorting because of old data issues.
- Bad:
// This function adds two numbers.
(The code shows this!)
- Good:
- Don't leave old code in comments. Delete it. Use version control (like Git) to keep old versions.
Example:
// Good: Explains why
// Custom sorting needed due to legacy data format
data.sort(customSort);
// Bad: Just repeats the code
// This sorts the data
data.sort(customSort);
4. Don't Repeat YourselfCyclomatic Complexity (DRY)
Repeated code causes bugs and makes fixes harder.
- If you see the same code in many places, make a reusable function or component.
- Example: If you check login status in three places, make a
checkLogin()
function.
Why? It's easier to fix one function than three places.
Example:
// Bad: Repeated code
if (!user.isLoggedIn) { redirectToLogin(); }
// Good: Reusable function
function checkLogin(user) {
if (!user.isLoggedIn) { redirectToLogin(); }
}
5. Keep It Simple (KISS)
Choose the easiest way that works.
- Don't use tricky code that's hard to understand.
- Choose readable code over fast code unless speed is critical.
- Use common tools and libraries, not rare ones.
Example:
// Bad: Complex one-liner
const result = arr.filter(x => x > 0).map(x => x * 2);
// Good: Clear and simple
const positiveNumbers = arr.filter(number => number > 0);
const doubledNumbers = positiveNumbers.map(number => number * 2);
Final Check
Before you finish, ask: "Is this code clean? Is it easy to follow?" If no, fix it.
## Another Great Example: A Rule for Senior Developers
Rules aren't just for code style. They can guide how work is done, perfect for senior coders who plan and lead. Here's a rule for senior developers:
### Rule File: `senior-engineer-protocol.mdc`
```markdown
---
title: Senior Full-Stack Engineer Task Execution Rule
description: A rule that defines a professional protocol for executing any development task.
globs: ["**/*.*"]
alwaysApply: false
---
# Senior Engineer Task Protocol
You are a responsible senior coder. Follow these steps for every task:
## 1. Understand the Task First
- Break the task into frontend and backend parts.
- Make sure you know what to do. Be clear about API boundaries and results.
- Write a plan showing which files you'll change and why.
- Don't start coding until the plan is clear.
## 2. Find Where to Make Changes
- Know exactly which parts of the code to change (e.g., `Button.tsx`).
- Don't change unrelated files. Be precise.
## 3. Make Small Changes
- Only change what's needed for the task.
- Don't fix other things like formatting unless they're part of the task.
## 4. Check Everything
- For **React**, make sure the UI works in all states (loading, error, success).
- For **Node.js**, check data flow, input checks, and response structure.
- Run all tests (local and integration).
## 5. Explain Your Work
- Summarize what you changed, why, and where.
- Explain any changes to UI or API.
- Give clear steps to test the changes locally.
How to Start Using Rules (It's Easy!)
Here's how to set up Cursor Rules in your project:
-
Open Cursor Settings:
- Mac: Press
Cmd + Shift + J
. - Windows: Press
Ctrl + Shift + J
. - This opens the settings where you can manage rules.
- Mac: Press
-
Create the Rule Folder:
- In your project's main folder, create a folder called
.cursor
. - Inside
.cursor
, create another folder calledrules
.
- In your project's main folder, create a folder called
-
Create a Rule File:
- Inside the
rules
folder, make a new file, likeclean-code.mdc
. - Copy and paste the rule text from one of the examples above.
- Inside the
-
Add a Rule via Settings (Optional):
- In Cursor Settings (opened with
Cmd + Shift + J
on Mac orCtrl + Shift + J
on Windows), go to the "Rules for AI" section. - Click "New Project Rule" or "New Global Rule" (Global Rules apply to all projects, Project Rules are for one project).
- Paste the rule content (e.g., the Clean Coder's Checklist) and save it.
- For Project Rules, ensure the
.cursor/rules
folder exists in your project.
- In Cursor Settings (opened with
-
Save and Test:
- Save the rule file or settings.
- Ask Cursor to write code (e.g., using
Cmd + K
on Mac orCtrl + K
on Windows) and check if it follows your rules. - If the code doesn't match, tweak the rule to be clearer.
Tip: Test your rules by asking Cursor to generate a small function and see if it uses clear names or follows your guidelines. You can also check the Cursor Community Forum for tips if you run into issues.
Why Cursor Rules Are So Awesome
Using these rules has made my coding so much better. Here's why I love them:
- Easier to Read: The AI writes code that my team can understand quickly.
- Fewer Bugs: Clean code makes it easier to spot problems.
- Faster Future Work: When I look at my code months later, I get it right away, making new features quicker to add.
- Like a Coach: The AI reminds me to write better code, like a mentor.
Cursor Rules turn your AI from a tool into a teammate who cares about quality.
Bonus: Explore More Rules
Want more ideas? Check out the awesome-cursorrules GitHub repository where coders share their rules. You'll find rules for different languages and frameworks, like Python or React, that you can tweak for your projects. You can even share your own rules there!
Try It Out!
Ready to make your code cleaner? Give Cursor Rules a try! Use the shortcuts (Cmd + Shift + J
on Mac, Ctrl + Shift + J
on Windows) to set up rules and watch your AI write code that's clear and beautiful. Happy coding, friends!