## أفضل الممارسات

يجمع هذا المستند خبرات مستخدمي Claude Code في التطوير الواقعي. سواء كنت مستخدمًا جديدًا يبدأ للتو مع Claude Code أو مستخدمًا متمرسًا يسعى إلى رفع الكفاءة، ستجد هنا نصائح قيّمة.

ننظم المحتوى من المبتدئ إلى المتقدم، لذا نوصي بقراءته كاملًا مرة أولًا، ثم تطبيقه تدريجيًا في عملك اليومي.

## أفضل ممارسات تهيئة المشروع

البداية الجيدة نصف النجاح. قبل استخدام Claude Code في مشروع للمرة الأولى، خصّص 10 دقائق للتهيئة، وستكون كل تفاعلاتك اللاحقة أكثر كفاءة.

### الخطوة 1: إنشاء CLAUDE.md

هذه هي الخطوة الأهم. يمثل `CLAUDE.md` دليل المشروع الذي تكتبه لـ Claude. عند بدء تشغيل Claude Code، يقرأ هذا الملف تلقائيًا لفهم سياق مشروعك.

**لماذا تُعد هذه الخطوة مهمة إلى هذا الحد؟**

بدون CLAUDE.md، ستشرح الأشياء نفسها لـ Claude مرارًا وتكرارًا:

```
You: Install dependencies with pnpm
Claude: Okay, running npm install...
You: Not npm, pnpm!
Claude: Sorry, running pnpm install...
```

مع CLAUDE.md، تحتاج هذه الأساسيات إلى أن تُقال مرة واحدة فقط.

**مثال على قالب CLAUDE.md:**

```markdown
# My Project Name

## Overview
This is an e-commerce backend management system based on Next.js 15, written in TypeScript.

## Tech Stack
- Runtime: Node.js 22 LTS
- Framework: Next.js 15 (App Router)
- Styling: Tailwind CSS v4
- Database: PostgreSQL 16 + Prisma ORM
- Package Manager: pnpm 9
- Testing Framework: Vitest + Playwright

## Common Commands
- Install dependencies: `pnpm install`
- Development server: `pnpm dev` (port 3000)
- Run tests: `pnpm test`
- Lint code: `pnpm lint`
- Database migration: `pnpm prisma migrate dev`
- Production build: `pnpm build`

## Coding Standards
- Strictly use TypeScript, no `any` allowed
- React components use functional style with hooks
- Styles only use Tailwind, no inline styles or CSS files
- All API routes return `{ success: boolean, data?: T, error?: string }`
- Database queries go through the service layer, don't call Prisma directly in routes
- Commit message format: `feat:` / `fix:` / `docs:` / `refactor:` prefixes

## Project Structure
- `src/app/` — Pages and API routes (App Router)
- `src/components/` — Reusable UI components
- `src/components/ui/` — Base components (Button, Input, etc.)
- `src/services/` — Business logic layer
- `src/lib/` — Utility functions and configuration
- `prisma/` — Database schema and migration files

## Notes
- Don't manually modify files under `prisma/migrations/`
- Environment variables are in `.env.local` (not committed to Git)
- API authentication middleware is in `src/middleware.ts`
- Image assets go in `public/images/`, use next/image component for loading
```

**استخدام /init للإنشاء السريع:**

إذا كنت لا تريد الكتابة يدويًا، فاستخدم الأمر `/init` لجعل Claude يحلل مشروعك تلقائيًا وينشئ ملف CLAUDE.md:

```
/init
```

سيفحص Claude بنية مشروعك وpackage.json وملفات الإعداد وما إلى ذلك، وينشئ CLAUDE.md تلقائيًا. بعد ذلك يمكنك إضافة أي أعراف للفريق ربما فاتته يدويًا.

### الخطوة 2: إعداد .claudeignore

على غرار `.gitignore`، يخبر `.claudeignore` Claude بالملفات التي لا تحتاج إلى انتباه. لا يسرّع هذا البحث فحسب، بل يمنع أيضًا تشتت انتباه Claude بملفات غير ذات صلة.

```bash
# .claudeignore

# Dependency directories
node_modules/
vendor/
.venv/

# Build outputs
dist/
build/
.next/
out/

# Large data files
*.sql
*.csv
*.sqlite
data/

# Binary and media files
*.jpg
*.png
*.mp4
*.zip

# Auto-generated code
generated/
*.gen.ts
prisma/migrations/

# Logs
logs/
*.log
```

### الخطوة 3: وصف بنية الدليل في CLAUDE.md

غالبًا ما تُغفل هذه الخطوة، لكنها فعالة جدًا. بمجرد أن يفهم Claude بنية الدليل لديك، سيعرف أين يجد الملفات وأين ينشئ ملفات جديدة:

```markdown
## Project Structure
src/
├── app/                 # Next.js App Router
│   ├── (auth)/          # Pages requiring authentication
│   ├── (public)/        # Public pages
│   └── api/             # API routes
├── components/
│   ├── ui/              # Base UI components (shadcn/ui)
│   ├── forms/           # Form components
│   └── layouts/         # Layout components
├── services/            # Business logic (one file per module)
├── hooks/               # Custom React hooks
├── lib/                 # Utility functions
│   ├── auth.ts          # Authentication related
│   ├── db.ts            # Database connection
│   └── validators.ts    # Zod schema definitions
└── types/               # TypeScript type definitions
```
## أفضل ممارسات البرمجة اليومية

بعد التهيئة، ستساعدك هذه العادات اليومية على العمل بفعالية أكبر.

### صف المتطلبات بوضوح، لا بتعليمات غامضة

هذا هو المبدأ الأساسي والأهم. Claude ليس قارئ أفكار — فكلما زاد وضوحك، تحسّن أداؤه.

| تعليمات غامضة (غير فعّالة) | أوصاف واضحة (فعّالة) |
|---|---|
| «أصلح ميزة تسجيل الدخول» | «أضف تحديدًا لمعدل فشل تسجيل الدخول في src/app/api/auth/login/route.ts: اقفل لمدة 15 دقيقة بعد 5 إخفاقات من IP نفسه خلال 5 دقائق، واستخدم Redis لتخزين العدد» |
| «ساعدني في كتابة مكوّن» | «أنشئ مكوّن UserAvatar في src/components/ui/. يجب أن يقبل خاصيتين: name وimageUrl. اعرض الأحرف الأولى من name عند عدم توفير صورة. استخدم rounded-full من Tailwind للصور الرمزية الدائرية» |
| «هناك خطأ، أصلحه» | «يبلغ المستخدمون عن فقدان شروط التصفية بعد النقر على ترقيم الصفحات في صفحة قائمة المنتجات. يرجى التحقق من منطق ترقيم الصفحات في src/app/products/page.tsx للتأكد من الحفاظ على معاملات استعلام URL أثناء ترقيم الصفحات» |

### استخدم مراجع @ لتوفير السياق

عندما تحتاج إلى أن يشير Claude إلى ملفات محددة، استخدم الرمز `@` للإشارات المباشرة — فهو أسرع وأدق من تركه يبحث:

```
Look at @src/services/order-service.ts and @src/types/order.ts,
then add a cancel order method to order-service, checking if the order status allows cancellation.
```

**طرق متعددة للإشارة باستخدام @:**

```bash
@src/services/auth.ts       # Reference a single file
@src/components/            # Reference an entire directory
@package.json               # Reference a config file
@https://nextjs.org/docs    # Reference online docs (will fetch content)
```

> **نصيحة لتوفير التكلفة**: استخدم `@` بفاعلية للإشارة إلى الملفات ذات الصلة بدلًا من ترك Claude يبحث في المشروع بأكمله. عندما يبحث Claude، فإنه يقرأ ملفات كثيرة، مما يستهلك tokens إضافية.

### أنجز شيئًا واحدًا في كل مرة

تجنّب حشر مهام كثيرة جدًا في prompt واحد. يقدّم Claude أفضل أداء عندما يركز على شيء واحد:

```
# Not recommended: asking for too much at once
"Add avatar upload to the user module, and while you're at it tweak the login page styles,
also add debounce to that search box, and oh, update the password reset email template too."

# Recommended: do it step by step
Step 1: "Add avatar upload to UserProfile component, use S3 for storage"
Step 2: "Update login page styles, refer to @docs/design-spec.md for the design"
Step 3: "Add 300ms debounce to the search box using a custom hook"
Step 4: "Update password reset email template, match the style of @src/templates/welcome.html"
```

### اجعل Claude يقرأ قبل التعديل

عند العمل على شيفرة موجودة، فإن جعل Claude يفهم الشيفرة أولًا قبل إجراء التغييرات أكثر فعالية بكثير من الانتقال مباشرة إلى التعديلات:

```
# Step 1: Understand first
"Read @src/services/payment-service.ts and explain the current payment flow processing logic,
especially error handling and retry mechanisms. Don't modify any code."

# Step 2: Plan next
"Based on your understanding, I want to add WeChat Pay as a payment channel.
Please create a modification plan, listing what needs to be changed."

# Step 3: Execute modifications
"The plan looks good, let's start. Modify payment-service.ts first."
```

### استخدم Plan Mode للمهام المعقدة

للمهام الكبيرة التي تشمل ملفات متعددة، استخدم Plan Mode (اضغط `Shift+Tab` للتبديل) لجعل Claude ينشئ خطة أولًا:

```
[Plan Mode]
I need to add an RBAC (Role-Based Access Control) permission system to the existing system.
Currently users only have admin and user roles. I need to support custom roles and fine-grained permissions.
Please analyze the existing code first and create a detailed implementation plan.
```

سينشئ Claude خطة خطوة بخطوة. بعد تأكيدك، بدّل مرة أخرى إلى الوضع العادي ونفّذ خطوة بخطوة.

### استخدم /clear و/compact بحكمة

هذان الأمران أداتان أساسيتان لإدارة السياق:

```bash
/compact    # Compress current conversation history, keeping key information, freeing up context space
/clear      # Completely clear conversation history, start fresh

# When to use:
# - Switching to a completely different task → /clear
# - Same task but conversation is too long → /compact
# - Feeling Claude's responses are getting worse (context overload) → /compact
# - Just finished one feature, starting the next → /clear
```

> **مبدأ مهم**: عند تبديل الموضوعات، استخدم /clear أولًا بالتأكيد. إن السياق القديم المتبقي يهدر tokens وقد يتداخل مع استجابات Claude.
## أفضل ممارسات مراجعة الكود

لا يقتصر Claude Code على كتابة الكود، بل يساعدك أيضًا على مراجعته.

### استخدم الأمر /review

راجع تغييرات Git الحالية بسرعة:

```
/review
```

سيتحقق Claude من جميع التغييرات غير المُودَعة ويشير إلى المشكلات المحتملة:
- أخطاء المنطق والحالات الحدّية
- مخاوف أمنية (حقن SQL، وXSS، وما إلى ذلك)
- مشكلات الأداء
- أسلوب كود غير متسق
- غياب معالجة الأخطاء

### اطلب من Claude كتابة اختبارات للتحقق من التغييرات

بعد تعديل الكود، اطلب من Claude كتابة اختبارات للتحقق:

```
I just modified the cancel order logic in @src/services/order-service.ts.
Please write unit tests for this method, covering the following scenarios:
1. Normal cancellation of an unshipped order
2. Attempt to cancel a shipped order (should fail)
3. Cancel a non-existent order
4. Concurrent cancellation of the same order
```

### سير عمل المراجعة متعددة الجولات

بالنسبة إلى تغييرات الكود المهمة، يمكنك إجراء مراجعات متعددة الجولات:

```
# Round 1: Overall review
"Review the latest changes to @src/services/payment-service.ts,
focusing on security and error handling."

# After making changes based on feedback, round 2:
"Please review the modified code again, this time focusing on performance and edge cases."

# Round 3 (optional): Comparison review
"Compare the code before and after changes to confirm all issues are fixed and no new problems were introduced."
```

## أفضل ممارسات تصحيح الأخطاء

إصلاح الأخطاء إحدى نقاط قوة Claude Code. وإتقان أسلوب التصحيح الصحيح يساعد Claude على تحديد المشكلات بسرعة أكبر.

### قدّم سجلات أخطاء كاملة

لا تعرض على Claude السطر الأخير فقط من رسالة الخطأ، بل قدّم السياق الكامل:

````
Got an error when running pnpm build, full error log below:

```
Type error: Argument of type 'string | undefined' is not assignable
to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.
  > 42 |   const user = await getUser(session.userId)
       |                                      ^^^^^^^
  43 |   return NextResponse.json(user)
```

This error occurs in @src/app/api/user/route.ts.
I suspect it's a session type definition issue, please check.
````

### صحّح الأخطاء خطوة بخطوة: شخّص أولًا، ثم أصلح

لا تتعجل بجعل Claude يصلح مباشرة، بل اطلب منه التشخيص أولًا:

```
# Step 1: Diagnose
"Users report that they occasionally get redirected to a 404 page after logging in.
Please check @src/middleware.ts and @src/app/(auth)/layout.tsx,
and analyze what might be causing this issue. Don't modify code yet."

# Step 2: Confirm the cause, then fix
"Your analysis makes sense—it's indeed a redirect logic issue when the session expires.
Please fix this issue and add appropriate error logging to help with future troubleshooting."
```

### استخدم لقطات الشاشة للمساعدة

يدعم Claude Code قراءة لقطات الشاشة، وهو أمر مفيد بخاصة لأخطاء واجهة المستخدم:

```
Look at this screenshot @screenshot.png—the last column text in the table is being cut off.
Please check the styles in @src/components/DataTable.tsx and fix this issue.
```

في الطرفية، يمكنك سحب صورة وإفلاتها مباشرةً في منطقة الإدخال لدى Claude Code، وسيعالجها تلقائيًا.
## أفضل ممارسات سير عمل Git

Claude Code مدمج بعمق مع Git. ويؤدي الاستفادة من هذه الميزات إلى تسهيل إدارة الإصدارات.

### دع Claude يولّد رسائل الإيداع تلقائيًا

سيحلل Claude تغييرات الشيفرة لديك ويولّد رسائل إيداع موحّدة تلقائيًا:

```
Commit these changes
```

ملاحظة: `/commit` ليس أمرًا مدمجًا في Claude Code (وهو غير موجود في قائمة الأوامر المدمجة الرسمية). ولا يعمل إلا إذا وفّرت أنت أو إضافة أمرًا مخصصًا أو مهارة. وإلا فاطلب من Claude تنفيذ الإيداع بلغة طبيعية فحسب.

تتضمن رسائل الإيداع المولّدة عادةً:
- بادئة نوع التغيير (feat، fix، refactor، إلخ)
- وصفًا موجزًا للتغيير
- النطاق المتأثر

إذا لم تكن راضيًا عن الرسالة المولّدة تلقائيًا، فيمكنك طلب تعديلها:

```
Commit these changes
# Claude's generated message not good enough?
"Please make the commit message more detailed, explaining why this logic was changed"
```

### فروع الميزات + سير عمل PR

سير العمل الموصى به:

```bash
# 1. Create feature branch
git checkout -b feature/order-cancel

# 2. Start Claude Code development
claude

# 3. Multiple small commits during development
> "Implement basic order cancellation logic"
> Commit these changes

> "Add cancel reason field and validation"
> Commit these changes

> "Add unit tests for order cancellation"
> Commit these changes

# 4. Finish development, create PR
> Create a Pull Request for the current branch, summarize all commit changes, generate a standardized PR description
```

### تجنّب التعديلات المباشرة على الفرع الرئيسي

```
# Add this rule in CLAUDE.md:
## Git Standards
- All modifications must be done on feature branches, don't modify main branch directly
- Branch naming: feature/xxx, fix/xxx, refactor/xxx
- Run `pnpm lint && pnpm test` before committing to ensure everything is fine
```

بعد كتابة ذلك في CLAUDE.md، سيتبع Claude هذه القواعد تلقائيًا. وإذا طلبت من Claude بالخطأ تعديل الشيفرة على الفرع الرئيسي، فسيذكّرك بإنشاء فرع أولًا.

## أفضل ممارسات التعاون ضمن الفريق

عند استخدام Claude Code ضمن فريق، تجعل المعايير الموحّدة التعاون أكثر سلاسة.

### مشاركة معايير CLAUDE.md

أودِع CLAUDE.md في مستودع Git كي يتشارك أعضاء الفريق إعدادات المشروع نفسها:

```bash
# CLAUDE.md in project root → commit to Git
git add CLAUDE.md
git commit -m "docs: add CLAUDE.md project configuration"

# Personal preference configs → put in .claude/CLAUDE.md, add to .gitignore
echo ".claude/CLAUDE.md" >> .gitignore
```

**ينبغي أن يتضمن CLAUDE.md الخاص بالفريق:**
- التقنيات المستخدمة في المشروع وشرح البنية المعمارية
- معايير كتابة الشيفرة واصطلاحات التسمية
- الأوامر والسكربتات الشائعة
- شرح بنية المجلدات
- اتفاقات الفريق (استراتيجية الفروع، معايير الإيداع، عملية المراجعة)

**يمكن أن يتضمن .claude/CLAUDE.md الشخصي:**
- تفضيلات كتابة الشيفرة الشخصية
- مقاطع شيفرة شائعة
- إعدادات بيئة تطوير محددة

### توحيد مراجعة PR

حدّد معايير مراجعة PR في CLAUDE.md كي يجري Claude مراجعات متسقة:

```markdown
## PR Review Standards
When reviewing code, check the following aspects:
1. **Functional correctness**: Does it fully implement the requirements?
2. **Error handling**: Are edge cases covered?
3. **Security**: Any risks of SQL injection, XSS, permission bypass?
4. **Performance**: Any unnecessary database queries or memory leaks?
5. **Test coverage**: Do new code changes have corresponding tests?
6. **Code style**: Does it conform to project standards?
7. **Documentation**: Do public APIs have JSDoc comments?
```

### اتساق نمط الشيفرة

فرّض نمط شيفرة موحّدًا من خلال CLAUDE.md:

```markdown
## Code Style
- Naming: Components use PascalCase, functions/variables use camelCase, constants use UPPER_SNAKE_CASE
- File names: Component files use PascalCase (e.g., UserAvatar.tsx), others use kebab-case
- Import order: React → third-party libraries → internal modules → types → styles
- Maximum function length: 50 lines, split if exceeded
- Define interface when component props exceed 3
```
## ملخص النصائح المتقدمة

فيما يلي بعض النصائح المتقدمة التي جمعها مستخدمون ذوو خبرة:

### أوامر الشرطة المائلة المخصصة

أنشئ قوالب أوامر مخصصة في الدليل `.claude/commands/`:

```bash
# .claude/commands/review-security.md
Please conduct a security review of the following code, focusing on:
1. SQL injection risks
2. XSS attack surface
3. CSRF protection
4. Completeness of permission checks
5. Whether sensitive data is encrypted
6. Whether sensitive information is leaked in logs

Review scope: $ARGUMENTS
```

عند الاستخدام:

```
/review-security @src/app/api/
```

### تعديلات منسقة لملفات متعددة

عندما تحتاج إلى تعديل ملفات متعددة في الوقت نفسه، امنح Claude رؤية عامة واضحة:

```
I need to add a coupon feature to the order system, involving the following files:
- @src/types/coupon.ts — new, define coupon types
- @src/services/coupon-service.ts — new, coupon business logic
- @src/services/order-service.ts — modify, apply coupon during checkout
- @src/app/api/coupons/route.ts — new, coupon API
- @prisma/schema.prisma — modify, add Coupon model

Please handle them in the order above, and tell me after completing each file.
```

### الاستفادة من Extended Thinking

بالنسبة إلى قرارات معمارية معقدة، دع Claude يستخدم Extended Thinking:

```
[Using Opus model]
I'm considering migrating the current REST API to GraphQL.
Please analyze the pros and cons in depth, considering the following factors:
1. Migration cost for existing 50+ API endpoints
2. Benefits of frontend query optimization
3. Changes in caching strategy
4. Team learning curve
5. Integration plan with existing React Query

No need to write code, give me a detailed technical analysis report.
```

### اجعل Claude يتحقق من تعديلاته

طوّر عادة أن يتحقق Claude بنفسه من تعديلاته:

```
After completing the modifications, please:
1. Run pnpm lint to check for formatting issues
2. Run pnpm test to confirm existing tests still pass
3. If there are type errors, fix them yourself
```

## المزالق الشائعة

أخيرًا، فيما يلي بعض الممارسات التي ينبغي تجنّبها:

| المزلق | النهج الصحيح |
|------|---------|
| لصق محتويات الملف بالكامل في المحادثة | استخدم `@file path` للإشارة إلى الملف |
| أن تطلب من Claude تنفيذ 5 أشياء في prompt واحد | نفّذ شيئًا واحدًا في كل مرة، وقسّم المهمة |
| أن تكون غامضًا عند وصف المتطلبات | حدّد الملفات والسلوكيات والنتائج المتوقعة |
| عدم استخدام CLAUDE.md | خصّص 10 دقائق لكتابته، ووفّر ساعات لا تُحصى لاحقًا |
| عدم استخدام /clear أو /compact مطلقًا | استخدم /clear عند تغيير الموضوع، و/compact عندما تطول المحادثة |
| أن تجعل Claude يعدّل دون الفهم أولًا | اقرأ الكود أولًا، ثم خطّط، ثم نفّذ |
| استخدام Opus لكل شيء | استخدم Sonnet للمهام اليومية، وOpus فقط للقرارات المعقدة |
| إعادة محاولة الأمر نفسه مرارًا عند فشله | جرّب نهجًا مختلفًا، وقدّم سياقًا أكبر |

يستغرق إتقان أفضل الممارسات هذه وقتًا. نوصي بالبدء بأكثر النقاط جوهرية: أنشئ CLAUDE.md، وصف المتطلبات بوضوح، ونفّذ شيئًا واحدًا في كل مرة. هذه النقاط الثلاث وحدها ستحسّن تجربتك بشكل ملحوظ. مع تعمّق استخدامك، طبّق التقنيات الأكثر تقدمًا تدريجيًا.