android-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Android Development Best Practices

Android开发最佳实践

General Kotlin Guidelines

通用Kotlin指南

Basic Principles

基本原则

  • Use English for all code and documentation
  • Always declare variable and function types explicitly
  • Avoid the
    any
    type; create necessary custom types
  • Eliminate blank lines within function bodies
  • 所有代码和文档均使用英文
  • 始终显式声明变量和函数类型
  • 避免使用
    any
    类型;创建必要的自定义类型
  • 移除函数体内的空行

Naming Standards

命名规范

  • PascalCase: Classes, interfaces, enums
  • camelCase: Variables, functions, methods
  • underscores_case: Files and directories
  • UPPERCASE: Environment variables, constants
  • Avoid magic numbers; define constants instead
  • Functions should start with action verbs
  • Boolean variables use prefixes:
    isLoading
    ,
    hasError
    ,
    canDelete
  • PascalCase:类、接口、枚举
  • camelCase:变量、函数、方法
  • underscores_case:文件和目录
  • UPPERCASE:环境变量、常量
  • 避免魔法数字;改用定义常量
  • 函数应以动作动词开头
  • 布尔变量使用前缀:
    isLoading
    ,
    hasError
    ,
    canDelete

Function Design

函数设计

  • Keep functions under 20 instructions with single responsibility
  • Use verb-based naming
  • Prefix boolean returns with
    is
    ,
    has
    , or
    can
  • Prefix void returns with
    execute
    ,
    save
    ,
    send
  • Combat nesting through early returns, utility extraction, and higher-order functions
  • Use default parameters instead of null checks
  • Consolidate parameters into objects (RO-RO pattern)
  • 函数代码不超过20行,遵循单一职责原则
  • 使用动词性命名
  • 返回布尔值的函数前缀为
    is
    has
    can
  • 返回void的函数前缀为
    execute
    save
    send
  • 通过提前返回、提取工具方法和高阶函数减少嵌套
  • 使用默认参数替代空值检查
  • 将参数整合到对象中(RO-RO模式)

Data and Classes

数据与类

  • Employ data classes for data structures
  • Encapsulate primitives in composite types; validate internally
  • Favor immutability; use
    val
    for unchanging values
  • Follow SOLID principles; prefer composition over inheritance
  • Keep classes under 200 instructions, 10 public methods, 10 properties
  • 使用数据类作为数据结构
  • 将基本类型封装到复合类型中;在内部进行验证
  • 优先使用不可变性;对不变值使用
    val
  • 遵循SOLID原则;优先组合而非继承
  • 类的代码不超过200行,公开方法不超过10个,属性不超过10个

Exception Handling

异常处理

  • Reserve exceptions for unexpected errors
  • Catch exceptions only to fix anticipated issues or add context
  • Create custom exception types for domain errors
  • 异常仅用于处理意外错误
  • 仅在修复预期问题或添加上下文时捕获异常
  • 为领域错误创建自定义异常类型

Android Architecture

Android架构

Clean Architecture

整洁架构

  • Implement clean architecture with clear layer separation
  • Use repository pattern for data persistence and caching
  • Keep business logic in Use Cases or Interactors
  • Separate concerns between UI, domain, and data layers
  • 实现具有清晰分层的整洁架构
  • 使用仓库模式进行数据持久化和缓存
  • 将业务逻辑放在用例(Use Cases)或交互器(Interactors)中
  • 分离UI、领域和数据层的关注点

Project Structure

项目结构

app/
├── data/           # Data sources, repositories, models
├── domain/         # Use cases, domain models, interfaces
├── presentation/   # UI components, ViewModels, state
└── di/             # Dependency injection modules
app/
├── data/           # 数据源、仓库、模型
├── domain/         # 用例、领域模型、接口
├── presentation/   # UI组件、ViewModels、状态
└── di/             # 依赖注入模块

MVI Pattern

MVI模式

  • Deploy MVI pattern for state and event management
  • ViewModels manage UI state as a single immutable state object
  • UI components observe state and render accordingly
  • Handle user intents/events through a single entry point
  • Keep side effects predictable and traceable
  • 采用MVI模式进行状态和事件管理
  • ViewModels将UI状态管理为单一不可变状态对象
  • UI组件观察状态并据此渲染
  • 通过单一入口处理用户意图/事件
  • 保持副作用可预测且可追踪

UI Development

UI开发

Navigation

导航

  • Use Navigation Component for fragment and activity routing
  • Define navigation graph for app flow
  • Handle deep links through Navigation Component
  • Implement safe args for type-safe navigation arguments
  • 使用Navigation Component进行Fragment和Activity路由
  • 定义导航图以规划应用流程
  • 通过Navigation Component处理深度链接
  • 实现Safe Args以进行类型安全的导航参数传递

Main Activity Structure

主Activity结构

  • MainActivity manages primary navigation
  • Use BottomNavigationView for main destinations (Home, Profile, Settings, etc.)
  • Handle navigation state properly across configuration changes
  • MainActivity管理主导航
  • 使用BottomNavigationView处理主要目标页面(首页、个人资料、设置等)
  • 在配置变更时正确处理导航状态

View Binding and State

View Binding与状态

  • Use ViewBinding for type-safe view access
  • Use Flow or LiveData for UI state management
  • Observe state changes in lifecycle-aware manner
  • Handle loading, error, and success states consistently
  • 使用ViewBinding进行类型安全的视图访问
  • 使用Flow或LiveData进行UI状态管理
  • 以感知生命周期的方式观察状态变化
  • 一致处理加载、错误和成功状态

UI Framework Preferences

UI框架偏好

  • Prefer XML layouts and Fragments over Jetpack Compose (unless Compose is specifically required)
  • Use ConstraintLayout for complex layouts
  • Apply Material 3 design guidelines
  • Follow responsive design practices for different screen sizes
  • 优先使用XML布局和Fragments而非Jetpack Compose(除非明确要求使用Compose)
  • 对复杂布局使用ConstraintLayout
  • 遵循Material 3设计指南
  • 针对不同屏幕尺寸遵循响应式设计实践

Authentication Flow

认证流程

Structure authentication screens properly:
  1. Splash Screen - Initial app launch
  2. Login Screen - User authentication
  3. Register Screen - New user registration
  4. Forgot Password Screen - Password recovery
  5. Verify Email Screen - Email verification
合理构建认证屏幕:
  1. 启动页 - 应用初始启动
  2. 登录页 - 用户认证
  3. 注册页 - 新用户注册
  4. 忘记密码页 - 密码找回
  5. 邮箱验证页 - 邮箱验证

Testing

测试

Unit Testing

单元测试

  • Follow Arrange-Act-Assert conventions
  • Test ViewModels, Use Cases, and Repositories
  • Use test doubles for dependencies
  • Achieve good coverage of business logic
  • 遵循Arrange-Act-Assert规范
  • 测试ViewModels、用例和仓库
  • 对依赖使用测试替身(test doubles)
  • 实现良好的业务逻辑覆盖率

UI Testing

UI测试

  • Implement widget testing for UI components
  • Write integration tests for API modules
  • Test navigation flows
  • Use Espresso for instrumented tests
  • 为UI组件实现微件测试
  • 为API模块编写集成测试
  • 测试导航流程
  • 使用Espresso进行仪器化测试

Best Practices

最佳实践

Lifecycle Management

生命周期管理

  • Handle lifecycle events properly
  • Avoid memory leaks from improper lifecycle handling
  • Use lifecycle-aware components
  • 正确处理生命周期事件
  • 避免因不当生命周期处理导致的内存泄漏
  • 使用感知生命周期的组件

Background Processing

后台处理

  • Use Coroutines for async operations
  • Handle cancellation properly
  • Use WorkManager for deferrable background work
  • 使用Coroutines进行异步操作
  • 正确处理取消操作
  • 使用WorkManager处理可延迟的后台任务

Dependency Injection

依赖注入

  • Use Hilt or Dagger for dependency injection
  • Scope dependencies appropriately
  • Keep DI configuration organized
  • 使用Hilt或Dagger进行依赖注入
  • 合理设置依赖的作用域
  • 保持DI配置的组织性

Performance

性能

  • Avoid work on the main thread
  • Optimize RecyclerView with DiffUtil
  • Use lazy loading for heavy resources
  • Profile and optimize memory usage
  • 避免在主线程执行任务
  • 使用DiffUtil优化RecyclerView
  • 对重型资源使用懒加载
  • 分析并优化内存使用