♻️ refactor(playbook): streamline agents and refresh tsl docs
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
# TSL 常见编码模式
|
||||
|
||||
> 本文档是 `$tsl-guide` 的子文档,汇总常见的组织方式与实践范式。
|
||||
> 语法示例以 `docs/tsl/syntax_book/` 为准。
|
||||
|
||||
## 目录
|
||||
|
||||
- [参数校验](#参数校验)
|
||||
- [早返回(减少嵌套)](#早返回减少嵌套)
|
||||
- [错误处理与上下文信息](#错误处理与上下文信息)
|
||||
- [I/O 分层](#io-分层)
|
||||
- [常量与配置管理](#常量与配置管理)
|
||||
- [集合与结果集处理](#集合与结果集处理)
|
||||
- [性能小贴士](#性能小贴士)
|
||||
|
||||
---
|
||||
|
||||
## 参数校验
|
||||
|
||||
尽早验证输入并给出明确错误信息。
|
||||
|
||||
```tsl
|
||||
Function ValidateUserId(UserId);
|
||||
Begin
|
||||
If UserId <= 0 then
|
||||
Raise "invalid user_id: " + IntToStr(UserId);
|
||||
End;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 早返回(减少嵌套)
|
||||
|
||||
```tsl
|
||||
Function NormalizeName(Name);
|
||||
Begin
|
||||
If Trim(Name) = "" then
|
||||
Return "";
|
||||
|
||||
Return UpperCase(Trim(Name));
|
||||
End;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 错误处理与上下文信息
|
||||
|
||||
```tsl
|
||||
Function LoadConfig(Path);
|
||||
Begin
|
||||
Try
|
||||
Return ReadFile(Path);
|
||||
Except
|
||||
Raise "load config failed: " + Path + ", " + ExceptObject.ErrInfo;
|
||||
End;
|
||||
End;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## I/O 分层
|
||||
|
||||
```tsl
|
||||
Function ReadUserIds(Path);
|
||||
Begin
|
||||
Content := ReadFile(Path);
|
||||
Return ParseUserIds(Content);
|
||||
End;
|
||||
|
||||
Function ParseUserIds(Content);
|
||||
Begin
|
||||
// 纯函数:只负责解析
|
||||
Return array();
|
||||
End;
|
||||
|
||||
Function WriteReport(Path, Report);
|
||||
Begin
|
||||
WriteFile(Path, Report);
|
||||
End;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 常量与配置管理
|
||||
|
||||
```tsl
|
||||
Const MaxRetries = 3;
|
||||
Const TimeoutMs = 5000;
|
||||
|
||||
Function RetryFetch(Url);
|
||||
Begin
|
||||
For i := 1 to MaxRetries do
|
||||
Begin
|
||||
// ...
|
||||
End;
|
||||
End;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 集合与结果集处理
|
||||
|
||||
```tsl
|
||||
Function SumPositive(Values);
|
||||
Begin
|
||||
Total := 0;
|
||||
For i := 0 to Length(Values) - 1 do
|
||||
Begin
|
||||
If Values[i] > 0 then
|
||||
Total := Total + Values[i];
|
||||
End;
|
||||
Return Total;
|
||||
End;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 性能小贴士
|
||||
|
||||
仅当明确存在性能瓶颈时采用:
|
||||
|
||||
- 把循环内的常量/表达式提到循环外
|
||||
- 避免在循环内执行 I/O 或 SQL
|
||||
- 对结果集访问做局部缓存(如字段名映射)
|
||||
|
||||
详细流程见:`$performance-optimization`。
|
||||
Reference in New Issue
Block a user