----------- 2022-11-12 补充 -----------
最近在开发中尝试用了clean架构,感觉就是 麻烦。。。太多模板代码,很容易过度开发。
我认为了解这些理念是很重要的,但应该跟随你的项目、流程 进行调整、裁剪。
如果你们的流程是 服务端出接口,然后召开接口会议,实际上就是在将 Data层的Module 变成 Domain层的entity (争执难免),当然你这样就相当于 依赖了服务端,而服务端是IO,显然违背了 Clean架构的依赖规范。
如果你的项目不是测试驱动开发,根本就没 自动化测试case,那你去划分 Local、Remote、Test 的DataSource也很蛋疼,因为我就是从云端拿数据。 当然了这就看你的项目了。
小吐槽下。
----------- end 2022-11-12 补充 -----------
对于Flutter在逐渐的熟悉,基本经历的几个阶段
《架构整洁之道》绝对要推荐一波,他完美的满足需求,同时思想上大大超越的。
(怎样去评价组件的好坏、组件的发展周期、SOLID重新回顾、引出 clean架构、编程几十年也不会变的编程范式)
但看完后如何去实践,毕竟读过和真正懂得还是有很远的距离,在搜Media的时候看到了 如下的大神文章,从头开始教你实战 测试驱动开发、clean框架。
上图,clean架构的组件示意图。其组件依赖由外向内单向依赖。越靠近IO设备,越接近于外部。
抛砖引玉吧,下面是我感触比较深的地方
简单说你的APP,有隔离出 业务层(domain layer)吗?业务层不应该和Flutter层等代码关联。
最后找到了, Flutter上的 TDD (Test-Drive Development)、Clean架构 相对好的,有完整代码记录的。
大神级文章 以下为翻译,同时我也加入自己的理解,尽量 信达雅吧。
是一个获取天气信息的案例
作者的GitHub case地址
lib
├── data
│ ├── constants.dart
│ ├── datasources
│ │ └── remote_data_source.dart
│ ├── exception.dart
│ ├── failure.dart
│ ├── models
│ │ └── weather_model.dart
│ └── repositories
│ └── weather_repository_impl.dart
├── domain
│ ├── entities
│ │ └── weather.dart
│ ├── repositories
│ │ └── weather_repository.dart
│ └── usecases
│ └── get_current_weather.dart
├── injection.dart
├── main.dart
└── presentation
├── bloc
│ ├── weather_bloc.dart
│ ├── weather_event.dart
│ └── weather_state.dart
└── pages
└── weather_page.dart
test
├── data
│ ├── datasources
│ │ └── remote_data_source_test.dart
│ ├── models
│ │ └── weather_model_test.dart
│ └── repositories
│ └── weather_repository_impl_test.dart
├── domain
│ └── usecases
│ └── get_current_weather_test.dart
├── helpers
│ ├── dummy_data
│ │ └── dummy_weather_response.json
│ ├── json_reader.dart
│ ├── test_helper.dart
│ └── test_helper.mocks.dart
└── presentation
├── bloc
│ └── weather_bloc_test.dart
└── pages
└── weather_page_test.dart
(注意,get_current_weather_test.dart 和 get_current_weather.dart 是在同一个 包名下,根目录不同而已 lib、test)
在 test/domain目录, 我们的用例是 get_current_weather_test.dart
import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_weather_app_sample/domain/entities/weather.dart';
import 'package:flutter_weather_app_sample/domain/usecases/get_current_weather.dart';
import 'package:mockito/mockito.dart';
import '../../helpers/test_helper.mocks.dart';
void main() {
late MockWeatherRepository mockWeatherRepository;
late GetCurrentWeather usecase;
setUp(() {
mockWeatherRepository = MockWeatherRepository();
usecase = GetCurrentWeather(mockWeatherRepository);
});
const testWeatherDetail = Weather(
cityName: 'Jakarta',
main: 'Clouds',
description: 'few clouds',
iconCode: '02d',
temperature: 302.28,
pressure: 1009,
humidity: 70,
);
const tCityName = 'Jakarta';
test(
'should get current weather detail from the repository',
() async {
// arrange
when(mockWeatherRepository.getCurrentWeather(tCityName))
.thenAnswer((_) async => const Right(testWeatherDetail));
// act
final result = await usecase.execute(tCityName);
// assert
expect(result, equals(Right(testWeatherDetail)));
},
);
}
Domain layer 有3个部分
Entity
Use Cases 用例
Repositories
import 'package:dartz/dartz.dart';
import 'package:flutter_weather_app_sample/data/failure.dart';
import 'package:flutter_weather_app_sample/domain/entities/weather.dart';
abstract class WeatherRepository {
Future> getCurrentWeather(String cityName);
}
我们mock一下Repository 用于测试
在test_helper.dart 中,创建 mock的 Repository
import 'package:mockito/annotations.dart';
import 'package:http/http.dart' as http;
@GenerateMocks(
[
WeatherRepository,
],
customMocks: [MockSpec(as: #MockHttpClient)],
)
void main() {}
执行命令,生成mock文件(这个我还没试,试后补充)
flutter pub run build_runner build
包含三部分
编写测试情景,确保 model 可以转换为 entities
Ok, we will start with models, the process begins by writing testing code for the model, weather_model_test.dart. Here, we will test 3 main things:
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_weather_app_sample/data/models/weather_model.dart';
import 'package:flutter_weather_app_sample/domain/entities/weather.dart';
import '../../helpers/json_reader.dart';
void main() {
const tWeatherModel = WeatherModel(
cityName: 'Jakarta',
main: 'Clouds',
description: 'few clouds',
iconCode: '02d',
temperature: 302.28,
pressure: 1009,
humidity: 70,
);
const tWeather = Weather(
cityName: 'Jakarta',
main: 'Clouds',
description: 'few clouds',
iconCode: '02d',
temperature: 302.28,
pressure: 1009,
humidity: 70,
);
group('to entity', () {
test(
'should be a subclass of weather entity',
() async {
// assert
final result = tWeatherModel.toEntity();
expect(result, equals(tWeather));
},
);
});
group('from json', () {
test(
'should return a valid model from json',
() async {
// arrange
final Map jsonMap = json.decode(
readJson('helpers/dummy_data/dummy_weather_response.json'),
);
// act
final result = WeatherModel.fromJson(jsonMap);
// assert
expect(result, equals(tWeatherModel));
},
);
});
group('to json', () {
test(
'should return a json map containing proper data',
() async {
// act
final result = tWeatherModel.toJson();
// assert
final expectedJsonMap = {
'weather': [
{
'main': 'Clouds',
'description': 'few clouds',
'icon': '02d',
}
],
'main': {
'temp': 302.28,
'pressure': 1009,
'humidity': 70,
},
'name': 'Jakarta',
};
expect(result, equals(expectedJsonMap));
},
);
});
}
然后开始编写 domain 中的module,和 Entity 差不多,但多了个 JSON的互相转换。
import 'package:equatable/equatable.dart';
import 'package:flutter_weather_app_sample/domain/entities/weather.dart';
class WeatherModel extends Equatable {
const WeatherModel({
required this.cityName,
required this.main,
required this.description,
required this.iconCode,
required this.temperature,
required this.pressure,
required this.humidity,
});
final String cityName;
final String main;
final String description;
final String iconCode;
final double temperature;
final int pressure;
final int humidity;
factory WeatherModel.fromJson(Map json) => WeatherModel(
cityName: json['name'],
main: json['weather'][0]['main'],
description: json['weather'][0]['description'],
iconCode: json['weather'][0]['icon'],
temperature: json['main']['temp'],
pressure: json['main']['pressure'],
humidity: json['main']['humidity'],
);
Map toJson() => {
'weather': [
{
'main': main,
'description': description,
'icon': iconCode,
},
],
'main': {
'temp': temperature,
'pressure': pressure,
'humidity': humidity,
},
'name': cityName,
};
Weather toEntity() => Weather(
cityName: cityName,
main: main,
description: description,
iconCode: iconCode,
temperature: temperature,
pressure: pressure,
humidity: humidity,
);
@override
List
然后编写 Repository,
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
dartz: ^0.10.1
equatable: ^2.0.3
flutter_bloc: ^8.0.1
get_it: ^7.2.0
http: ^0.13.3
rxdart: ^0.27.3
dev_dependencies:
bloc_test: ^9.0.2
build_runner: ^2.1.2
flutter_test:
sdk: flutter
mockito: ^5.0.15
mocktail: ^0.2.0
Flutter实现Clean的一些参考 demo