跨平台开发 / 系统课时
把 DTO 和业务模型分开
把 DTO 和业务模型分开
接口返回的字段结构属于服务端契约,而页面和业务规则需要的是稳定、好用的领域对象。把两者混成一个类,会让字段改名、可空性变化甚至接口版本升级直接渗透到业务层。本课通过一个可运行示例演示 DTO、业务模型和映射器如何协作。
学习目标
- 区分 DTO 与业务模型各自表达的职责
- 实现从接口 JSON 到 DTO,再到业务模型的转换
- 判断小型项目中何时可以暂不拆分,何时值得分层
两种模型关注点不同
DTO 负责忠实承接外部数据,例如服务端字段叫 display_name、价格以“分”为单位、某些字段允许缺失。业务模型则应按照应用内部最自然的方式表达,例如使用 displayName、把价格转换成可直接参与业务判断的值,并尽量减少无意义的可空字段。
分离的关键不是“类更多”,而是把变化隔开。接口字段变化时,通常只调整 DTO 和映射代码;页面、用例和状态管理继续依赖稳定的业务模型。
从 JSON 映射到业务模型
下面示例模拟接口返回商品 JSON。DTO 保留服务端字段语义,Product 只暴露应用真正需要的字段。
class ProductDto {
ProductDto({
required this.id,
required this.title,
required this.priceCents,
required this.stock,
});
final int id;
final String title;
final int priceCents;
final int? stock;
factory ProductDto.fromJson(Map<String, dynamic> json) {
return ProductDto(
id: json['id'] as int,
title: json['display_name'] as String,
priceCents: json['price_cents'] as int,
stock: json['stock'] as int?,
);
}
}
class Product {
const Product({
required this.id,
required this.name,
required this.price,
required this.inStock,
});
final int id;
final String name;
final double price;
final bool inStock;
}
Product mapProduct(ProductDto dto) {
return Product(
id: dto.id,
name: dto.title,
price: dto.priceCents / 100,
// 接口缺少库存时,业务层采用“不可售”的保守策略。
inStock: (dto.stock ?? 0) > 0,
);
}
void main() {
final json = <String, dynamic>{
'id': 7,
'display_name': 'Mechanical Keyboard',
'price_cents': 12990,
'stock': 3,
};
final dto = ProductDto.fromJson(json);
final product = mapProduct(dto);
print(product.name);
print(product.price.toStringAsFixed(2));
print(product.inStock);
}预期输出:
Mechanical Keyboard
129.90
true这里的业务层完全不知道 display_name 和 price_cents 这两个接口字段。若服务端以后把显示名称改成别的字段,只要 DTO 解析与映射仍能产出相同的 Product,业务代码就不需要跟着改。
把兼容逻辑放在边界上
接口演进经常伴随字段缺失、旧字段保留或单位变化。兼容代码应尽量集中在 DTO 解析或映射层,而不是散落到多个页面。例如服务端暂时可能同时返回 display_name 与旧字段 name,可以在 fromJson 中决定优先级,再继续产出稳定的 title。
什么时候值得分离
当项目出现以下任一情况时,分离 DTO 通常开始有价值:同一业务模型来自多个接口;服务端命名与应用语义明显不同;接口字段经常调整;需要把字符串、时间戳、金额单位或枚举值转换成更安全的类型;业务层希望禁止某些可空状态继续向上扩散。
对于原型或很小的应用,如果接口稳定、模型简单,而且只有一两个页面使用,同一个类同时承担解析与展示也可以接受。关键不是追求层数,而是让外部契约的变化不要无条件传播到整个应用。
DTO 与业务模型分开后,Repository 通常最适合承担映射边界:数据源返回 DTO,Repository 转成业务模型,再把稳定对象交给状态管理和页面。