Chapter 7

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:

1
Coding conventions
Naming, formatting, and comment conventions across different languages
2
Tool configuration
Practical configuration of ESLint, Prettier, and formatting tools
3
Best practices
Practices for error handling, logging, performance, security, etc.
4
Continuous improvement
Code reviews, quality metrics, technical debt management

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

Variables/functions
camelCase
getUserName, calculateTotal
Class/Component
PascalCase
UserProfile, LoginForm
Constant
UPPER_SNAKE_CASE
MAX_RETRY_COUNT, API_BASE_URL
File
kebab-case
user-service.ts, login-form.tsx

ESLint configuration

Recommended Airbnb or TypeScript ESLint Configuration.

.eslintrc.json(Airbnb + TypeScript):
{
  "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

.prettierrc:
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "always"
}

TypeScript strict mode

tsconfig.json (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

Rust
  • • rustfmt (formatting)
  • • clippy (code checking)
  • • snake_case naming
C#
  • • dotnet format
  • • EditorConfig
  • • PascalCase naming
Swift/Kotlin/Dart
  • • 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

Git Flow
• main: production environment
• develop: development branch
• feature/*: feature branch
• release/*: release branches
• hotfix/*: hotfix
GitHub Flow
• main: main branch
• feature/*: feature branch
• Merge through PR
• Suitable for continuous deployment
GitLab Flow
• main: main branch
• Environment branches (staging, production)
• Upstream-first principle

Commit message convention (Conventional Commits)

Format: <type>(<scope>): <subject>
feat(auth): Add user login functionality
fix(api): Fix data query performance issue
docs(readme): Update installation instructions
refactor(utils): Refactor date formatting function
feat
New feature
fix
Fix bugs
docs
Document update
style
Code format
refactor
Refactoring
test
Test
chore
Build/Tools
perf
Performance optimization

Git Hooks configuration

pre-commit Hook
# Run lint and formatting checks before submitting
npm run lint
npm run format:check
commit-msg Hook
# Check commit message format
npx commitlint --edit $1

💡 Use husky(Node.js) or pre-commit(Python) Manage Git Hooks

Code review process

1Create a feature branch, complete development, and commit the code
2Create a Pull Request and fill in the PR description and checklist
3Code reviewers review the code (functionality, performance, security, maintainability)
4Modify the code based on feedback and resubmit
5Merge into the main branch after review approval

Dependency management

Manage project dependencies properly to ensure maintainability and security. Different languages have different dependency management approaches.

Semantic Versioning (SemVer)

Major version (MAJOR)
Incompatible API changes
2.0.0
Minor version number (MINOR)
Backward-compatible feature additions
1.2.0
Revision number (PATCH)
Backward compatibility issue fixes
1.2.3
Version range: ^1.2.3 (allows 1.x.x, not 2.0.0), ~1.2.3 (allows 1.2.x, not 1.3.0)

Locked file management

Node.js
  • • package-lock.json(npm)
  • • yarn.lock(yarn)
  • • pnpm-lock.yaml(pnpm)
  • • Commit to version control to ensure consistency
Python
  • • requirements.txt(pip)
  • • poetry.lock(Poetry)
  • • Pipfile.lock(Pipenv)
  • • Use virtual environments to isolate dependencies

Dependency security audit

Node.js
npm audit
npm audit fix
yarn audit
pnpm audit
Python
pip-audit
safety check
bandit (code security checks)

💡 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

Business error
  • • User input errors
  • • Business rule violations
  • • Return friendly error messages
System error
  • • Database connection failed
  • • File system error
  • • Record detailed logs
Network error
  • • API call failed
  • • Timeout error
  • • Implement a retry mechanism

Error handling modes

TypeScript/JavaScript/Python/Java:
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

DEBUG
Detailed debug information
Development debugging
INFO
General information
Normal operation
WARN
Warning message
Potential issues
ERROR
Error message
Error but recoverable
FATAL
fatal error
The system cannot continue

Structured logging (JSON format)

Example:
{
  "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

Required field
  • • timestamp: timestamp
  • • level: log level
  • • message: log message
  • • requestId: request ID (tracking)
Optional field
  • • 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

Algorithm 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²))
Front-end optimization
  • • 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

Index 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)
Query optimization
  • • 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

Memory cache
  • • Local cache (Map, LRU Cache)
  • • Suitable for hot data
  • • Pay attention to memory limits
Redis
  • • Distributed caching
  • • Set expiration time
  • • Cache penetration / breakdown / avalanche protection
CDN
  • • 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

Frontend validation
  • • Validate form inputs using libraries such as Zod and Yup
  • • Client-side validation improves the user experience
  • • But never rely solely on frontend validation
Backend validation
  • • All inputs must be validated
  • • Use a whitelist instead of a blacklist
  • • Clean and escape user input

Protection against common attacks

SQL injection
  • • Use parameterized queries (Prepared Statements)
  • • Use ORM (Prisma, TypeORM)
  • • Never concatenate SQL strings
XSS (Cross-Site Scripting)
  • • Output escaping (React automatic escaping)
  • • Use Content Security Policy (CSP)
  • • Avoid using dangerouslySetInnerHTML
CSRF (Cross-Site Request Forgery)
  • • Use CSRF Token
  • • SameSite Cookie attribute
  • • Validate the Referer header
Sensitive data encryption
  • • Passwords are hashed using bcrypt and Argon2
  • • Transport uses HTTPS (TLS)
  • • Encrypt sensitive data at rest

Key management

Environment variables
  • • Use a .env file (do not commit to Git)
  • • Use .env.example as a template
  • • Use a key management service in production
Key management service
  • • AWS Secrets Manager
  • • HashiCorp Vault
  • • Azure Key Vault
  • • Rotate keys regularly

OWASP Top 10 protection

1.Injection attacks (SQL, NoSQL, command injection)
2.Failed authentication
3.Sensitive data leakage
4.XML External Entity (XXE)
5.Broken access control
6.Security misconfiguration
7.XSS cross-site scripting
8.Insecure deserialization
9.Use components with known vulnerabilities
10.Insufficient logging and monitoring

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

Feature
  • ☐ Does the feature meet the requirements
  • ☐ Are edge cases handled
  • ☐ Is error handling complete
  • ☐ Are the tests sufficient
Performance
  • ☐ Are there performance issues?
  • ☐ Are database queries optimized
  • ☐ Is there a memory leak
  • ☐ Is cache usage reasonable
Safe
  • ☐ Input validation is complete
  • ☐ Has sensitive information been leaked
  • ☐ Is the permission check correct?
  • ☐ Do dependencies have any security vulnerabilities?
Maintainability
  • ☐ 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

Timely review: review as soon as possible after PR creation to avoid blocking development
Constructive feedback: point out issues and provide improvement suggestions, rather than just criticizing
Small-batch review: keep the amount of code reviewed per review within 400 lines
Automation check: Use CI/CD to automatically check formatting, tests, and security

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

Cyclomatic complexity
  • • Measure code complexity
  • • Goal: < 10
  • • Tools: SonarQube, CodeClimate
Code coverage
  • • The proportion of code covered by tests
  • • Goal: > 80%
  • • Tools: Jest, Coverage.py, JaCoCo
Technical debt
  • • Code smells, duplicate code
  • • Refactor regularly
  • • Tool: SonarQube

Automated checks (CI/CD integration)

GitHub Actions example:
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:coverage

Technical 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