Connect Coding Standards & Refactoring Habits
This skill defines the coding principles and refactoring patterns used throughout the Connect project. Apply these standards when writing new code, reviewing existing code, or refactoring.
Core Principles
1. Separation of Concerns
- API Endpoints: Each endpoint should have a single, well-defined responsibility
- Services: Business logic separated from API routes and data models
- Models: Pure data structures with validation, no business logic
- Frontend Components: Single responsibility - one component, one purpose
- Example: Topic creation should be a separate endpoint (
/topics/create), not mixed into chat endpoint (/chat)
2. Clean Code
- DRY (Don't Repeat Yourself): Extract common patterns into reusable functions
- SOLID Principles: Especially Single Responsibility and Dependency Inversion
- No Magic Numbers/Strings: Use constants or configuration
- Explicit over Implicit: Make intentions clear in code
- Fail Fast: Validate inputs early, return errors immediately
- Expressive naming: Use expressive function name rather than redundant docstring or comment
3. Expressive Naming
- Functions: Use verb phrases that describe what they do
- ✅
get_relevant_context() instead of get_context()
- ✅
create_topic() instead of create()
- ✅
merge_nodes() instead of merge()
- Variables: Use nouns that describe what they represent
- ✅
selectedCategoryIds instead of cats
- ✅
memory_context instead of ctx
- ✅
isNewSession instead of new
- Classes: Use nouns describing the entity
- ✅
MemoryRetriever instead of Retriever
- ✅
GraphService instead of Service
- Boolean variables: Use
is_, has_, should_, can_ prefixes
- ✅
isLoading, hasPermission, shouldCreateCategory
4. Simplicity
- Avoid Over-Engineering: Solve the problem at hand, not hypothetical future problems
- Prefer Simple Solutions: If a simple approach works, use it
- Remove Unused Code: Delete dead code, don't comment it out
- Minimize Dependencies: Only add dependencies when necessary
- Clear Flow: Code should read like a story from top to bottom
5. Generalization vs Specificity
- General Methods: Create reusable, parameterized functions when patterns repeat
- ✅
update_node_properties(node_id, label, properties) instead of separate methods for each node type
- ✅
get_nodes_by_label(label, filters) instead of type-specific methods
- Specific When Needed: Don't over-generalize - keep it practical
- Constants for Magic Values: Extract repeated strings/numbers into class constants
- ✅
LABEL_KNOWLEDGE = "Knowledge" instead of hardcoded strings
6. Error Handling
- Graceful Degradation: Non-critical operations (like caching) should fail silently with logging
- Explicit Error Messages: Provide context in error messages
- Logging Levels: Use appropriate levels (debug, info, warning, error)
- Transaction Safety: Ensure database operations are atomic where needed
7. Code Organization
- Logical Grouping: Group related methods together with section comments
- Example:
# ========== Node Creation ==========
- Consistent Patterns: Use the same patterns throughout the codebase
- File Structure: One class per file, related utilities grouped together
- Import Organization: Group imports (stdlib, third-party, local)
8. Type Safety
- Type Hints: Use type hints in Python for clarity
- Pydantic Models: Use for data validation and serialization
- TypeScript: Use strict types, avoid
any when possible
- Optional Types: Use
| None or ? to indicate nullable values
9. Documentation
- Docstrings: Use for public functions/classes explaining what and why
- Comments: Explain "why" not "what" - code should be self-documenting
- README: Keep updated with architecture decisions
- Inline Comments: Only when code intent isn't obvious
10. Testing Considerations
- Testable Code: Write code that's easy to test (dependency injection, pure functions)
- Edge Cases: Consider edge cases during implementation
- Integration Tests: Test full flows, not just units
Refactoring Patterns
When Refactoring:
- Identify Duplication: Look for repeated patterns
- Extract Common Logic: Create general helper methods
- Simplify Conditionals: Use early returns, guard clauses
- Remove Dead Code: Delete unused functions/variables
- Rename for Clarity: Improve names to match current understanding
- Consolidate Similar Operations: Merge related functions
Refactoring Checklist:
Project-Specific Patterns
Backend (Python/FastAPI)
- Use
async/await consistently for I/O operations
- Use dependency injection (
Depends()) for services
- Group endpoints logically in
main.py
- Use Pydantic models for request/response validation
- Use
logger from logging module, not print()
Frontend (React/TypeScript)
- Use functional components with hooks
- Extract reusable logic into custom hooks
- Use TypeScript interfaces for props and data structures
- Use TanStack Query for data fetching and caching
- Use Tailwind CSS utility classes, avoid inline styles
- Keep components small and focused
Database Operations
- Use transactions for multi-step operations
- Handle connection errors gracefully
- Use parameterized queries (prevent SQL injection)
- Batch operations when possible (Redis pipeline, Neo4j batch)
Anti-Patterns to Avoid
- ❌ Mixing business logic in API endpoints
- ❌ Creating endpoints that do multiple unrelated things
- ❌ Using generic names like
data, item, result without context
- ❌ Hardcoding values that might change
- ❌ Creating overly specific methods when a general one would work
- ❌ Ignoring errors silently without logging
- ❌ Premature optimization
- ❌ Over-abstracting simple operations
Example: Good vs Bad
Bad:
async def chat(request: ChatRequest):
session_id = request.session_id or str(uuid.uuid4())
session = await session_manager.get_session(session_id)
if not session:
# Creates topic, creates category, creates sub-categories, etc.
# 50+ lines of mixed concerns
# Then handles chat logic
Good:
@app.post("/topics/create")
async def create_topic(request: CreateTopicRequest):
# Only handles topic creation
...
@app.post("/chat")
async def chat(request: ChatRequest):
# Only handles chat messaging
...
When to Use This Skill
- When writing new code - ensure it follows these standards
- When reviewing code - check against these principles
- When refactoring - use these patterns to improve code quality
- When debugging - consider if code organization could be improved
- When adding features - ensure proper separation of concerns
Instructions
- Before Writing Code: Review relevant sections of this skill
- While Coding: Apply naming conventions, separation of concerns, and simplicity principles
- After Coding: Review against the refactoring checklist
- When Refactoring: Identify patterns, extract common logic, improve names
- Ask Questions: Use the ask questions tool if you need to clarify requirements with the user
Remember
- Code is read more than written - prioritize readability
- Simple solutions are often the best solutions
- Names are the most important form of documentation
- Separation of concerns makes code maintainable
- Refactor incrementally - small improvements add up
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: connect-coding-standards3description: Coding standards and refactoring habits for the Connect project. Apply when writing, reviewing, or refactoring code to ensure consistency, maintainability, and clean architecture. Use when this capability is needed.4---56# Connect Coding Standards & Refactoring Habits78This skill defines the coding principles and refactoring patterns used throughout the Connect project. Apply these standards when writing new code, reviewing existing code, or refactoring.910## Core Principles1112### 1. Separation of Concerns13- **API Endpoints**: Each endpoint should have a single, well-defined responsibility14- **Services**: Business logic separated from API routes and data models15- **Models**: Pure data structures with validation, no business logic16- **Frontend Components**: Single responsibility - one component, one purpose17- **Example**: Topic creation should be a separate endpoint (`/topics/create`), not mixed into chat endpoint (`/chat`)1819### 2. Clean Code20- **DRY (Don't Repeat Yourself)**: Extract common patterns into reusable functions21- **SOLID Principles**: Especially Single Responsibility and Dependency Inversion22- **No Magic Numbers/Strings**: Use constants or configuration23- **Explicit over Implicit**: Make intentions clear in code24- **Fail Fast**: Validate inputs early, return errors immediately25- **Expressive naming**: Use expressive function name rather than redundant docstring or comment2627### 3. Expressive Naming28- **Functions**: Use verb phrases that describe what they do29 - ✅ `get_relevant_context()` instead of `get_context()`30 - ✅ `create_topic()` instead of `create()`31 - ✅ `merge_nodes()` instead of `merge()`32- **Variables**: Use nouns that describe what they represent33 - ✅ `selectedCategoryIds` instead of `cats`34 - ✅ `memory_context` instead of `ctx`35 - ✅ `isNewSession` instead of `new`36- **Classes**: Use nouns describing the entity37 - ✅ `MemoryRetriever` instead of `Retriever`38 - ✅ `GraphService` instead of `Service`39- **Boolean variables**: Use `is_`, `has_`, `should_`, `can_` prefixes40 - ✅ `isLoading`, `hasPermission`, `shouldCreateCategory`4142### 4. Simplicity43- **Avoid Over-Engineering**: Solve the problem at hand, not hypothetical future problems44- **Prefer Simple Solutions**: If a simple approach works, use it45- **Remove Unused Code**: Delete dead code, don't comment it out46- **Minimize Dependencies**: Only add dependencies when necessary47- **Clear Flow**: Code should read like a story from top to bottom4849### 5. Generalization vs Specificity50- **General Methods**: Create reusable, parameterized functions when patterns repeat51 - ✅ `update_node_properties(node_id, label, properties)` instead of separate methods for each node type52 - ✅ `get_nodes_by_label(label, filters)` instead of type-specific methods53- **Specific When Needed**: Don't over-generalize - keep it practical54- **Constants for Magic Values**: Extract repeated strings/numbers into class constants55 - ✅ `LABEL_KNOWLEDGE = "Knowledge"` instead of hardcoded strings5657### 6. Error Handling58- **Graceful Degradation**: Non-critical operations (like caching) should fail silently with logging59- **Explicit Error Messages**: Provide context in error messages60- **Logging Levels**: Use appropriate levels (debug, info, warning, error)61- **Transaction Safety**: Ensure database operations are atomic where needed6263### 7. Code Organization64- **Logical Grouping**: Group related methods together with section comments65 - Example: `# ========== Node Creation ==========`66- **Consistent Patterns**: Use the same patterns throughout the codebase67- **File Structure**: One class per file, related utilities grouped together68- **Import Organization**: Group imports (stdlib, third-party, local)6970### 8. Type Safety71- **Type Hints**: Use type hints in Python for clarity72- **Pydantic Models**: Use for data validation and serialization73- **TypeScript**: Use strict types, avoid `any` when possible74- **Optional Types**: Use `| None` or `?` to indicate nullable values7576### 9. Documentation77- **Docstrings**: Use for public functions/classes explaining what and why78- **Comments**: Explain "why" not "what" - code should be self-documenting79- **README**: Keep updated with architecture decisions80- **Inline Comments**: Only when code intent isn't obvious8182### 10. Testing Considerations83- **Testable Code**: Write code that's easy to test (dependency injection, pure functions)84- **Edge Cases**: Consider edge cases during implementation85- **Integration Tests**: Test full flows, not just units8687## Refactoring Patterns8889### When Refactoring:901. **Identify Duplication**: Look for repeated patterns912. **Extract Common Logic**: Create general helper methods923. **Simplify Conditionals**: Use early returns, guard clauses934. **Remove Dead Code**: Delete unused functions/variables945. **Rename for Clarity**: Improve names to match current understanding956. **Consolidate Similar Operations**: Merge related functions9697### Refactoring Checklist:98- [ ] Are concerns properly separated?99- [ ] Are function/variable names expressive?100- [ ] Is the code simple and readable?101- [ ] Are there any hardcoded values that should be constants?102- [ ] Is there duplication that can be extracted?103- [ ] Are error cases handled gracefully?104- [ ] Is the code organized logically?105- [ ] Are types properly annotated?106107## Project-Specific Patterns108109### Backend (Python/FastAPI)110- Use `async/await` consistently for I/O operations111- Use dependency injection (`Depends()`) for services112- Group endpoints logically in `main.py`113- Use Pydantic models for request/response validation114- Use `logger` from `logging` module, not `print()`115116### Frontend (React/TypeScript)117- Use functional components with hooks118- Extract reusable logic into custom hooks119- Use TypeScript interfaces for props and data structures120- Use TanStack Query for data fetching and caching121- Use Tailwind CSS utility classes, avoid inline styles122- Keep components small and focused123124### Database Operations125- Use transactions for multi-step operations126- Handle connection errors gracefully127- Use parameterized queries (prevent SQL injection)128- Batch operations when possible (Redis pipeline, Neo4j batch)129130## Anti-Patterns to Avoid131132- ❌ Mixing business logic in API endpoints133- ❌ Creating endpoints that do multiple unrelated things134- ❌ Using generic names like `data`, `item`, `result` without context135- ❌ Hardcoding values that might change136- ❌ Creating overly specific methods when a general one would work137- ❌ Ignoring errors silently without logging138- ❌ Premature optimization139- ❌ Over-abstracting simple operations140141## Example: Good vs Bad142143### Bad:144```python145async def chat(request: ChatRequest):146 session_id = request.session_id or str(uuid.uuid4())147 session = await session_manager.get_session(session_id)148 if not session:149 # Creates topic, creates category, creates sub-categories, etc.150 # 50+ lines of mixed concerns151 # Then handles chat logic152```153154### Good:155```python156@app.post("/topics/create")157async def create_topic(request: CreateTopicRequest):158 # Only handles topic creation159 ...160161@app.post("/chat")162async def chat(request: ChatRequest):163 # Only handles chat messaging164 ...165```166167## When to Use This Skill168169- When writing new code - ensure it follows these standards170- When reviewing code - check against these principles171- When refactoring - use these patterns to improve code quality172- When debugging - consider if code organization could be improved173- When adding features - ensure proper separation of concerns174175## Instructions1761771. **Before Writing Code**: Review relevant sections of this skill1782. **While Coding**: Apply naming conventions, separation of concerns, and simplicity principles1793. **After Coding**: Review against the refactoring checklist1804. **When Refactoring**: Identify patterns, extract common logic, improve names1815. **Ask Questions**: Use the ask questions tool if you need to clarify requirements with the user182183## Remember184185- **Code is read more than written** - prioritize readability186- **Simple solutions are often the best solutions**187- **Names are the most important form of documentation**188- **Separation of concerns makes code maintainable**189- **Refactor incrementally** - small improvements add up190191---192> Converted and distributed by [TomeVault](https://tomevault.io/claim/yenlianglai) — claim your Tome and manage your conversions.193<!-- tomevault:4.0:skill_md:2026-04-14 -->