Refactor code structure for improved readability and maintainability

This commit is contained in:
catlog22
2026-02-07 23:44:22 +08:00
parent 80ae4baea8
commit 41cff28799
175 changed files with 691 additions and 1479 deletions

View File

@@ -0,0 +1,91 @@
---
name: go-dev
description: Go core development principles for clean, efficient, and idiomatic code
---
# Go Development Guidelines
You are now operating under Go core development principles. Focus on essential Go idioms and practices without dictating project structure.
## Core Go Principles
### Essential Language Guidelines
- **Simplicity**: Write simple, readable code over clever solutions
- **Naming**: Use clear, descriptive names following Go conventions
- **Error Handling**: Handle errors explicitly, don't ignore them
- **Interfaces**: Keep interfaces small and focused
```go
// Core principle: Clear error handling
func GetUser(id string) (*User, error) {
if id == "" {
return nil, errors.New("user ID cannot be empty")
}
user, err := database.FindUser(id)
if err != nil {
return nil, fmt.Errorf("failed to get user %s: %w", id, err)
}
return user, nil
}
// Core principle: Small, focused interfaces
type UserReader interface {
GetUser(id string) (*User, error)
}
```
## Idiomatic Go Patterns
- **Zero Values**: Design types to be useful in their zero state
- **Receiver Types**: Use pointer receivers for methods that modify the receiver
- **Package Names**: Use short, clear package names without underscores
- **Goroutines**: Use goroutines and channels for concurrent operations
## Essential Error Handling
- **Explicit Errors**: Always handle errors explicitly
- **Error Wrapping**: Use `fmt.Errorf` with `%w` verb to wrap errors
- **Custom Errors**: Create specific error types when appropriate
- **Early Returns**: Use early returns to avoid deep nesting
```go
// Core principle: Error wrapping and context
func ProcessUserData(userID string) error {
user, err := GetUser(userID)
if err != nil {
return fmt.Errorf("processing user data: %w", err)
}
if err := validateUser(user); err != nil {
return fmt.Errorf("user validation failed: %w", err)
}
return nil
}
```
## Concurrency Guidelines
- **Channel Communication**: Use channels to communicate between goroutines
- **Context**: Use context.Context for cancellation and timeouts
- **Worker Pools**: Implement worker pools for bounded concurrency
- **Race Detection**: Run tests with `-race` flag regularly
## Testing Essentials
- **Table-Driven Tests**: Use table-driven tests for multiple test cases
- **Test Names**: Use descriptive test function names
- **Mocking**: Use interfaces for dependency injection and mocking
- **Benchmarks**: Write benchmarks for performance-critical code
## Performance Guidelines
- **Profiling**: Use Go's built-in profiling tools
- **Memory Management**: Understand Go's garbage collector behavior
- **Slice/Map Operations**: Be aware of capacity vs length for slices
- **String Operations**: Use strings.Builder for efficient string concatenation
## Code Quality Essentials
- **Go fmt**: Always format code with `gofmt` or `goimports`
- **Go vet**: Run `go vet` to catch common mistakes
- **Linting**: Use golangci-lint for comprehensive code analysis
- **Documentation**: Write clear package and function documentation
Apply these core Go principles to write clean, efficient, and maintainable Go code following language idioms and best practices.

View File

@@ -0,0 +1,107 @@
---
name: java-dev
description: Java core development principles for robust, maintainable enterprise applications
---
# Java Development Guidelines
You are now operating under Java core development principles. Focus on essential Java practices without dictating specific frameworks or project structure.
## Core Java Principles
### Essential Language Guidelines
- **Object-Oriented Design**: Use proper encapsulation, inheritance, and polymorphism
- **Naming Conventions**: Follow Java naming standards (camelCase, PascalCase)
- **Immutability**: Favor immutable objects when possible
- **Exception Handling**: Use specific exceptions and proper exception handling
```java
// Core principle: Proper exception handling and immutability
public final class User {
private final String id;
private final String name;
private final String email;
public User(String id, String name, String email) {
this.id = Objects.requireNonNull(id, "User ID cannot be null");
this.name = Objects.requireNonNull(name, "Name cannot be null");
this.email = Objects.requireNonNull(email, "Email cannot be null");
}
public String getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
}
// Core principle: Specific exceptions
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message);
}
}
```
## Essential Object-Oriented Patterns
- **Single Responsibility**: Each class should have one reason to change
- **Dependency Injection**: Use constructor injection for required dependencies
- **Interface Segregation**: Keep interfaces focused and minimal
- **Composition over Inheritance**: Favor composition for flexibility
## Error Handling Essentials
- **Checked vs Unchecked**: Use checked exceptions for recoverable conditions
- **Exception Hierarchy**: Create meaningful exception hierarchies
- **Resource Management**: Use try-with-resources for automatic resource cleanup
- **Logging**: Log exceptions appropriately with context
```java
// Core principle: Resource management and exception handling
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = Objects.requireNonNull(userRepository);
}
public User findUser(String id) throws UserNotFoundException {
try {
Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() ->
new UserNotFoundException("User not found with id: " + id));
} catch (DataAccessException e) {
throw new UserNotFoundException("Error retrieving user: " + e.getMessage(), e);
}
}
}
```
## Modern Java Features
- **Optional**: Use Optional to handle null values safely
- **Streams**: Use streams for data processing and filtering
- **Lambda Expressions**: Use lambdas for functional programming patterns
- **Records**: Use records for simple data carriers (Java 14+)
## Testing Essentials
- **Unit Tests**: Use JUnit 5 for unit testing
- **Test Organization**: Follow Given-When-Then or Arrange-Act-Assert patterns
- **Mocking**: Use Mockito for mocking dependencies
- **Integration Tests**: Test component interactions properly
## Performance Guidelines
- **String Handling**: Use StringBuilder for string concatenation in loops
- **Collection Choice**: Choose appropriate collection types for use cases
- **Memory Management**: Understand garbage collection behavior
- **Profiling**: Use profiling tools to identify performance bottlenecks
## Concurrency Guidelines
- **Thread Safety**: Design for thread safety when needed
- **Concurrent Collections**: Use concurrent collections appropriately
- **ExecutorService**: Use thread pools instead of creating threads manually
- **Synchronization**: Use proper synchronization mechanisms
## Code Quality Essentials
- **Code Formatting**: Use consistent code formatting and style
- **Static Analysis**: Use tools like SpotBugs, PMD, and Checkstyle
- **Documentation**: Write clear Javadoc for public APIs
- **Clean Code**: Follow clean code principles and naming conventions
Apply these core Java principles to write robust, maintainable, and efficient Java applications following language best practices and modern Java idioms.

View File

@@ -0,0 +1,58 @@
---
name: javascript-dev
description: JavaScript and Node.js core development principles and essential practices
---
# JavaScript Development Guidelines
You are now operating under JavaScript/Node.js core development principles. Focus on essential practices without dictating project structure.
## Core Language Principles
### Naming Conventions
- **Variables/Functions**: camelCase (`getUserData`, `isValid`)
- **Constants**: SCREAMING_SNAKE_CASE (`API_ENDPOINT`, `MAX_RETRIES`)
- **Classes**: PascalCase (`UserService`, `ApiClient`)
### Essential Function Guidelines
- **Pure Functions**: Prefer functions that don't mutate inputs
- **Async/Await**: Use instead of Promises for better readability
- **Error Handling**: Always handle errors explicitly, never silently fail
```javascript
// Core principle: Clear error handling
async function fetchData(id) {
try {
const response = await api.get(`/data/${id}`);
return response.data;
} catch (error) {
throw new DataFetchError(`Failed to fetch data for ${id}: ${error.message}`);
}
}
```
## Essential Testing Practices
- **Test Names**: Describe behavior clearly (`should return user when ID exists`)
- **Arrange-Act-Assert**: Structure tests consistently
- **Mock External Dependencies**: Isolate units under test
- **Test Edge Cases**: Include error conditions and boundary values
## Code Quality Essentials
- **Consistent Formatting**: Use automated formatting (Prettier)
- **Linting**: Catch common errors early (ESLint)
- **Type Safety**: Consider TypeScript for larger projects
- **Input Validation**: Validate all external inputs
## Security Core Principles
- **Input Sanitization**: Never trust user input
- **Environment Variables**: Keep secrets out of code
- **Dependency Management**: Regularly audit and update packages
- **Error Messages**: Don't expose internal details to users
## Performance Guidelines
- **Avoid Premature Optimization**: Write clear code first
- **Use Modern Array Methods**: `map`, `filter`, `reduce` over manual loops
- **Template Literals**: For string formatting over concatenation
- **Object Destructuring**: For cleaner variable extraction
Apply these core JavaScript principles to ensure clean, maintainable, and secure code without imposing specific project structures or tool choices.

View File

@@ -0,0 +1,79 @@
---
name: python-dev
description: Python core development principles following PEP 8 and essential practices
---
# Python Development Guidelines
You are now operating under Python core development principles. Focus on essential PEP 8 practices without dictating project structure.
## Core Language Principles
### Naming Conventions (PEP 8)
- **Variables/Functions**: snake_case (`get_user_data`, `is_valid`)
- **Constants**: SCREAMING_SNAKE_CASE (`API_ENDPOINT`, `MAX_RETRIES`)
- **Classes**: PascalCase (`UserService`, `ApiClient`)
- **Private**: Single underscore prefix (`_private_method`)
### Essential Function Guidelines
- **Type Hints**: Use for parameters and return values when helpful
- **Single Responsibility**: Each function should do one thing well
- **Explicit Error Handling**: Create specific exception classes
- **Context Managers**: Use `with` statements for resource management
```python
from typing import List, Optional
def calculate_total(items: List[dict]) -> float:
"""Calculate total price of items."""
if not items:
raise ValueError("Items list cannot be empty")
return sum(item.get('price', 0) for item in items)
# Core principle: Specific exceptions
class UserNotFoundError(Exception):
"""Raised when user cannot be found."""
pass
```
## Essential Testing Practices
- **Test Structure**: Given-When-Then pattern
- **Descriptive Names**: Test names should describe behavior
- **Mock External Dependencies**: Isolate units under test
- **Edge Cases**: Test error conditions and boundary values
## Code Quality Essentials
- **PEP 8 Compliance**: Follow standard Python style guide
- **Type Checking**: Use mypy or similar for type safety
- **Automated Formatting**: Use Black or similar formatter
- **Import Organization**: Keep imports organized and minimal
## Security Core Principles
- **Input Validation**: Validate all external inputs
- **Parameterized Queries**: Never use string interpolation for SQL
- **Environment Variables**: Keep secrets out of code
- **Dependency Management**: Regularly audit packages for vulnerabilities
```python
# Core principle: Safe database queries
from sqlalchemy import text
def get_user_by_email(email: str) -> Optional[User]:
query = text("SELECT * FROM users WHERE email = :email")
result = db.execute(query, {"email": email})
return result.fetchone()
```
## Modern Python Features
- **F-strings**: Use for string formatting (`f"Hello {name}"`)
- **Pathlib**: Use `pathlib.Path` instead of `os.path`
- **Dataclasses**: Use for simple data containers
- **List/Dict Comprehensions**: Use appropriately for clarity
## Performance Guidelines
- **Avoid Premature Optimization**: Write clear code first
- **Use Built-in Functions**: Leverage Python's built-in efficiency
- **Generator Expressions**: For memory efficiency with large datasets
- **Context Managers**: Ensure proper resource cleanup
Apply these core Python principles to ensure clean, maintainable, and Pythonic code without imposing specific frameworks or project structures.

View File

@@ -0,0 +1,103 @@
---
name: react-dev
description: React core development principles with hooks and modern patterns
---
# React Development Guidelines
You are now operating under React core development principles. Focus on essential React patterns without dictating project structure.
## Core React Principles
### Component Guidelines
- **Functional Components**: Use functional components with hooks over class components
- **Component Naming**: PascalCase for components (`UserProfile`, `NavigationBar`)
- **Single Responsibility**: Each component should have one clear purpose
- **Props Interface**: Define clear prop types (TypeScript when possible)
### Essential Hook Patterns
- **useState**: For component-level state management
- **useEffect**: Handle side effects with proper cleanup
- **useCallback**: Memoize functions to prevent unnecessary re-renders
- **useMemo**: Memoize expensive calculations
- **Custom Hooks**: Extract reusable stateful logic
```jsx
// Core principle: Custom hooks for reusable logic
function useUser(userId) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (!userId) return;
const fetchUser = async () => {
try {
setLoading(true);
const userData = await api.getUser(userId);
setUser(userData);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchUser();
}, [userId]);
return { user, loading, error };
}
```
## Essential Testing Practices
- **Test Behavior**: Test what users see and interact with, not implementation
- **React Testing Library**: Preferred over enzyme for component testing
- **Mock External Dependencies**: Keep tests isolated and fast
- **Accessibility Testing**: Include accessibility assertions in tests
## Performance Core Principles
- **Avoid Premature Optimization**: Write clear code first
- **React.memo**: Only when profiling shows unnecessary re-renders
- **useCallback/useMemo**: Use judiciously based on actual performance needs
- **Key Props**: Always provide stable, unique keys for list items
## State Management Guidelines
- **Local State First**: Use useState for component-specific state
- **Lift State Up**: When multiple components need the same data
- **Context Sparingly**: Only for truly global state (theme, auth, etc.)
- **External Libraries**: Consider Redux Toolkit, Zustand for complex global state
```jsx
// Core principle: Context with proper error boundaries
const UserContext = createContext();
export const useUser = () => {
const context = useContext(UserContext);
if (!context) {
throw new Error('useUser must be used within UserProvider');
}
return context;
};
```
## Error Handling Essentials
- **Error Boundaries**: Implement to catch React component errors
- **Async Error Handling**: Use try-catch in useEffect and event handlers
- **User-Friendly Messages**: Show helpful error states to users
- **Error Recovery**: Provide ways for users to recover from errors
## Accessibility Core Principles
- **Semantic HTML**: Use appropriate HTML elements first
- **ARIA Labels**: Add when semantic HTML isn't sufficient
- **Keyboard Navigation**: Ensure all interactive elements are keyboard accessible
- **Focus Management**: Handle focus properly for dynamic content
## Code Quality Essentials
- **ESLint React Rules**: Use React-specific linting rules
- **TypeScript**: Use for prop types and state management
- **Consistent Formatting**: Use Prettier or similar
- **Component Composition**: Favor composition over complex inheritance
Apply these core React principles to ensure maintainable, performant, and accessible components without imposing specific architectural decisions.

View File

@@ -0,0 +1,83 @@
---
name: typescript-dev
description: TypeScript core principles for type safety and maintainable code
---
# TypeScript Development Guidelines
You are now operating under TypeScript core principles. Focus on essential type safety practices without dictating project structure.
## Core TypeScript Principles
### Essential Type Guidelines
- **Strict Configuration**: Enable strict TypeScript settings for maximum type safety
- **Explicit Typing**: Type function parameters and return values explicitly
- **Interface vs Type**: Use interfaces for objects, types for unions and computations
- **Generic Constraints**: Use generics for reusable, type-safe components
```typescript
// Core principle: Clear type definitions
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
}
// Core principle: Generic constraints
function findById<T extends { id: string }>(items: T[], id: string): T | undefined {
return items.find(item => item.id === id);
}
// Core principle: Union types for controlled values
type Status = 'pending' | 'approved' | 'rejected';
```
## Type Safety Essentials
- **No Any**: Avoid `any` type, use `unknown` when type is truly unknown
- **Null Safety**: Handle null/undefined explicitly with strict null checks
- **Type Guards**: Use type predicates and guards for runtime type checking
- **Assertion Functions**: Create functions that narrow types safely
```typescript
// Core principle: Type guards for runtime safety
function isUser(value: unknown): value is User {
return typeof value === 'object' &&
value !== null &&
typeof (value as User).id === 'string';
}
// Core principle: Never use any, use unknown
function processApiResponse(response: unknown): User | null {
if (isUser(response)) {
return response;
}
return null;
}
```
## Essential Error Handling
- **Typed Errors**: Create specific error types for different failure modes
- **Result Types**: Consider Result/Either patterns for error handling
- **Promise Typing**: Properly type async functions and error states
- **Error Boundaries**: Type error boundary props and state properly
## Performance Guidelines
- **Avoid Excessive Generics**: Don't over-engineer type parameters
- **Compile-Time Checks**: Leverage TypeScript for compile-time validation
- **Type Inference**: Let TypeScript infer types when obvious
- **Utility Types**: Use built-in utility types (Partial, Pick, Omit, etc.)
## Testing with Types
- **Test Type Assertions**: Ensure tests validate both runtime and compile-time behavior
- **Mock Typing**: Properly type test mocks and fixtures
- **Type-Only Tests**: Use TypeScript compiler API for pure type testing
- **Coverage**: Include type coverage in your quality metrics
## Configuration Essentials
- **Strict Mode**: Always enable strict mode in tsconfig.json
- **Path Mapping**: Use path mapping for cleaner imports
- **Incremental Compilation**: Enable for faster builds
- **Source Maps**: Generate source maps for debugging
Apply these core TypeScript principles to ensure type-safe, maintainable code without imposing specific architectural patterns or tooling choices.