Files
harmony-client/docs/conventions.md
2026-09-11 14:47:53 +08:00

63 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Conventions(编码规范)
ArkTS(TypeScript 的超集,HarmonyOS 严格类型方言)+ ArkUI 声明式 UI。
## 命名 Naming
| 元素 Element | 规则 Rule | 示例 Example |
|-------------|----------|-------------|
| 组件 / Ability | `PascalCase` | `LoginPage`, `EntryAbility` |
| 文件 | 与组件同名 `.ets` | `LoginPage.ets` |
| 变量 / 函数 / 属性 | `camelCase` | `userName`, `fetchData()` |
| 常量 | `UPPER_SNAKE_CASE` | `MAX_RETRY_COUNT` |
| 布尔变量 | `is`/`has`/`can` 前缀 | `isLoading`, `hasError` |
## 严格类型 Strict Typing
- **禁止** `any`、`@ts-ignore`、`@ts-expect-error`。
- 类型搞不定 = 设计有问题,重构类型而不是绕过它。
- 优先 `interface` / `enum`,复杂类型放 `model/`。
## 声明式 UI 与状态 Declarative UI & State
- UI 由状态驱动:改状态 → 自动重渲染,禁止命令式直接改 UI。
- 状态装饰器选择:
- 局部状态 `@State`
- 父子传递 `@Prop`(单向)/ `@Link`(双向)
- 跨层 `@Provide` / `@Consume`
- 避免不必要的重渲染:状态粒度要细,不要一个 `@State` 装一整个大对象。
## 资源 Resources
- 字符串、颜色、媒体一律 `$r('app.xxx')`(定义在 `resources/base/element/`)。
- 禁止在 `.ets` 里硬编码字符串、颜色值、路径。
## 组件化 Components
- 页面:`@Entry` 组件,放 `pages/`。
- 复用组件:`@Component` 或 `@Reusable`(长列表复用),放 `components/`,通过 `@Prop`/事件回调与外界通信,不直接依赖业务层。
## 分层与依赖方向 Layering
`pages → viewmodel → service → model`。禁止反向依赖(如 `model` import `service`)。
架构越界由约定 + 人工审查把关(ArkTS 侧暂无现成的依赖方向 linter)。
## 安全 Security
`code-linter.json5` 已启用 `@security/*` 规则,**改动不得引入不安全算法**:
- 禁用不安全哈希(MD5/SHA1)、不安全 AES 模式、3DES、弱 RSA/DH 密钥等。
- 需要加密时优先系统安全 API(如 `@ohos.security.cryptoFramework` 的安全模式)。
## 性能 Performance
`code-linter.json5` 已启用 `@performance/recommended`:
- 长列表用 `LazyForEach` + `@Reusable`,不要 `ForEach` 渲染大量节点。
- 避免在 `build()` 里做重计算/创建新对象。
- 大图/列表项懒加载,图片用合适的缓存策略。
## 改动后验证 Verify After Change
- 跑 lint:DevEco 里 Code Linter,或 hvigor 对应任务。
- 跑相关测试:见 `docs/testing.md`。
- 提交前确认 `code-linter.json5` 无新增 error。