Development basics
Master code conventions, tool configurations, and best practices for different languages, build professional development habits, and improve code quality and team collaboration efficiency.
Learn development fundamentals using Sequential Thinking
Development common sense involves many aspects, usingStructured thinking methodsCan help you systematically master:
Coding conventions
A unified code style makes code easier to read and maintain, and is the foundation of team collaboration. Different languages have different conventions, so below we introduce them by language.
Naming conventions
ESLint configuration
Recommended Airbnb or TypeScript ESLint Configuration.
{
"extends": [
"airbnb-base",
"airbnb-typescript/base",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/explicit-function-return-type": "warn",
"import/prefer-default-export": "off",
"max-len": ["error", { "code": 100 }]
}
}Prettier configuration
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"arrowParens": "always"
}TypeScript strict mode
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
}React conventions
- • Use function components and Hooks, avoiding class components
- • Props are defined using TypeScript interfaces
- • Component names use PascalCase
- • Use React.memo to optimize performance (if needed)
- • Custom Hooks start with `use`
Quick reference for other languages
- • rustfmt (formatting)
- • clippy (code checking)
- • snake_case naming
- • dotnet format
- • EditorConfig
- • PascalCase naming
- • Swift: SwiftLint
- • Kotlin: ktlint
- • Dart: dart format
Version control
Git is the standard tool for modern development. Mastering Git workflows, branching strategies, and code review processes is the foundation of team collaboration.
Branch strategy
Commit message convention (Conventional Commits)
Git Hooks configuration
npm run lint
npm run format:check
npx commitlint --edit $1
💡 Use husky(Node.js) or pre-commit(Python) Manage Git Hooks
Code review process
Dependency management
Manage project dependencies properly to ensure maintainability and security. Different languages have different dependency management approaches.
Semantic Versioning (SemVer)
Locked file management
- • package-lock.json(npm)
- • yarn.lock(yarn)
- • pnpm-lock.yaml(pnpm)
- • Commit to version control to ensure consistency
- • requirements.txt(pip)
- • poetry.lock(Poetry)
- • Pipfile.lock(Pipenv)
- • Use virtual environments to isolate dependencies
Dependency security audit
💡 Use Dependabot or Renovate Automatically update dependencies and security patches
Dependency update strategy
- • Update regularly: Check outdated dependencies once a month
- • Security first: Prioritize updating dependencies with security vulnerabilities
- • Test-driven: run the full test suite after updates
- • Progressive update: Update one major dependency at a time to avoid large-scale changes
- • Documentation record: Record major dependency updates and migration steps
Error handling guidelines
Good error handling makes programs more robust and improves the user experience. Different languages have different error-handling patterns.
Error type classification
- • User input errors
- • Business rule violations
- • Return friendly error messages
- • Database connection failed
- • File system error
- • Record detailed logs
- • API call failed
- • Timeout error
- • Implement a retry mechanism
Error handling modes
try {
const result = await riskyOperation();
return result;
} catch (error) {
logger.error('Operation failed', { error });
throw new BusinessError('User-friendly error message');
}Error handling best practices
- • Clarify the error type: Define clear error types and error codes
- • Record error logs: Record complete error information and context
- • User-friendly prompts: display friendly error messages to users, hiding technical details
- • Error recovery: Provide recovery mechanisms such as retries and fallbacks
- • Error boundary: use error boundaries (React) or middleware (Express) to handle errors centrally
Logging conventions
Good logging is the foundation of debugging and monitoring. Structured logs make logs easier to analyze and process.
Log level
Structured logging (JSON format)
{
"timestamp": "2025-01-27T10:30:00Z",
"level": "ERROR",
"message": "User login failed",
"context": {
"userId": "12345",
"ip": "192.168.1.1",
"userAgent": "Mozilla/5.0..."
},
"error": {
"type": "AuthenticationError",
"message": "Incorrect password",
"stack": "..."
},
"requestId": "req-abc123"
}Log context
- • timestamp: timestamp
- • level: log level
- • message: log message
- • requestId: request ID (tracking)
- • userId: User ID
- • operation: operation type
- • duration: operation time
- • metadata: additional metadata
Sensitive information masking
- • Password: never log passwords, use
***Alternative - • Token: Record only the first few and last few characters of the token
- • ID number: anonymization processing, only part of the numbers are displayed
- • Bank card number: Show only the last 4 digits
- • Email: partial masking can be considered (for example: u***@example.com)
Performance optimization
Performance optimization is an ongoing process. There is room for optimization from the code level to the architectural level.
Code performance optimization
- • Choose the appropriate data structure (HashMap vs List)
- • Avoid nested loops; use indexes or a Map
- • Use caching to avoid repeated calculations
- • Time complexity analysis (O(n) vs O(n²))
- • Code splitting and lazy loading
- • Image optimization (WebP, lazy loading)
- • Use React.memo to avoid unnecessary re-renders
- • Virtual scrolling (long lists)
Database query optimization
- • Add indexes to commonly queried fields
- • Avoid excessive indexing (affects write performance)
- • Use composite indexes to optimize multi-field queries
- • Regularly analyze query plans (EXPLAIN)
- • Avoid SELECT *, query only the fields you need
- • Use pagination to avoid loading large amounts of data at once
- • Use JOIN instead of multiple queries
- • Avoid N+1 query problems
Cache strategy
- • Local cache (Map, LRU Cache)
- • Suitable for hot data
- • Pay attention to memory limits
- • Distributed caching
- • Set expiration time
- • Cache penetration / breakdown / avalanche protection
- • Static asset acceleration
- • Images, CSS, JS files
- • Edge node caching
Performance monitoring
- • APM tools:New Relic, Datadog, Sentry (performance monitoring)
- • Performance Analysis:Chrome DevTools、Python cProfile、Go pprof
- • Metrics monitoring: response time, throughput, error rate, resource utilization
- • Alert mechanism: Set performance thresholds and automatically alert when thresholds are exceeded
Security best practices
Security is not optional; it is mandatory. From the code level to the deployment level, security must be considered at every stage.
Input validation and sanitization
- • Validate form inputs using libraries such as Zod and Yup
- • Client-side validation improves the user experience
- • But never rely solely on frontend validation
- • All inputs must be validated
- • Use a whitelist instead of a blacklist
- • Clean and escape user input
Protection against common attacks
- • Use parameterized queries (Prepared Statements)
- • Use ORM (Prisma, TypeORM)
- • Never concatenate SQL strings
- • Output escaping (React automatic escaping)
- • Use Content Security Policy (CSP)
- • Avoid using dangerouslySetInnerHTML
- • Use CSRF Token
- • SameSite Cookie attribute
- • Validate the Referer header
- • Passwords are hashed using bcrypt and Argon2
- • Transport uses HTTPS (TLS)
- • Encrypt sensitive data at rest
Key management
- • Use a .env file (do not commit to Git)
- • Use .env.example as a template
- • Use a key management service in production
- • AWS Secrets Manager
- • HashiCorp Vault
- • Azure Key Vault
- • Rotate keys regularly
OWASP Top 10 protection
Code review
Code review is an important part of ensuring code quality. Establish clear review processes and checklists to make reviews more efficient.
Review checklist
- ☐ Does the feature meet the requirements
- ☐ Are edge cases handled
- ☐ Is error handling complete
- ☐ Are the tests sufficient
- ☐ Are there performance issues?
- ☐ Are database queries optimized
- ☐ Is there a memory leak
- ☐ Is cache usage reasonable
- ☐ Input validation is complete
- ☐ Has sensitive information been leaked
- ☐ Is the permission check correct?
- ☐ Do dependencies have any security vulnerabilities?
- ☐ Is the code clear and easy to read?
- ☐ Is the naming convention appropriate?
- ☐ Are the comments sufficient
- ☐ Whether project guidelines are followed
Review best practices
Continuous improvement
Code quality is not a one-time task, but a process of continuous improvement. Establish quality metrics and monitoring mechanisms.
Code quality metrics
- • Measure code complexity
- • Goal: < 10
- • Tools: SonarQube, CodeClimate
- • The proportion of code covered by tests
- • Goal: > 80%
- • Tools: Jest, Coverage.py, JaCoCo
- • Code smells, duplicate code
- • Refactor regularly
- • Tool: SonarQube
Automated checks (CI/CD integration)
name: Code Quality
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test
- name: Check coverage
run: npm run test:coverageTechnical debt management
- • Identify debt: Use tools to automatically identify code smells and duplicate code
- • Priority ranking: Prioritize based on impact scope and fix cost
- • Regular refactoring: Allocate a certain amount of time in each sprint for refactoring
- • Record debt: Record it in an Issue or technical debt list
- • Avoid new debt: pay attention to technical debt during code reviews
Learning outcomes
After completing this chapter, you will:
- 1Master code conventions in different languages (TypeScript, Python, Java, Go, etc.) and tool configuration
- 2Be proficient in version control with Git, and master branching strategies and code review workflows
- 3Understand the importance of dependency management and master security auditing and update strategies
- 4Master error handling and logging conventions to improve code robustness
- 5Understand performance optimization and security best practices, and write high-quality code
- 6Establish a code review and continuous improvement mechanism to improve the team's code quality