移动应用遗留系统重构(7)- 解耦重构演示篇 (一),android 开发环境的搭建视频
//发送 http get 请求,需要用到 userId 做标识 String params = userId;}}
代码移动
代码移动至独立的 library,加上对应的 Gradle 依赖:

移动后模块结构如下:

功能验证
执行冒烟测试,验证功能
./gradlew app:testDebug --tests SmokeTesting

**代码演示:[mp.weixin.qq.com/s/C0nQRbgmp…](
)**
具体的代码:[github 链接](
)
file 包重构
依赖分析

通过分析我们发现 file 包存在横向 bundle 模块的依赖,该依赖为异常依赖,须要解除。
安全重构
重构前代码:
public class FileController {public List<FileInfo> getFileList() {return new ArrayList<>();}
public FileInfo upload(String path) {//上传文件 LogUtils.log("upload file");HttpUtils.post("http://file", UserController.userId);return new FileInfo();}
public FileInfo download(String url) {//下载文件 if (!UserController.isLogin) {return null;}return new FileInfo();}}
重构手法:
2.1 抽取 getUserId、isLogin 方法


重构后代码如下:
public class FileController {public List<FileInfo> getFileList() {return new ArrayList<>();}
public FileInfo upload(String path) {//上传文件 LogUtils.log("upload file");HttpUtils.post("http://file", getUserId());return new FileInfo();}
public FileInfo download(String url) {//下载文件 if (!isLogin()) {return null;}return new FileInfo();}
private String getUserId() {return UserController.userId;}
private boolean isLogin() {return UserController.isLogin;}}
2.2 抽取代理类,UserState


重构后代码如下:
public class FileController {private final UserState userState = new UserState();
public List<FileInfo> getFileList() {return new ArrayList<>();}
public FileInfo upload(String path) {//上传文件 LogUtils.log("upload file");HttpUtils.post("http://file", userState.getUserId());return new FileInfo();}
public FileInfo download(String url) {//下载文件 if (!userState.isLogin()) {return nu
ll;}return new FileInfo();}}
2.3 抽取接口


重构后代码如下:
public class FileController {private final UserState userState = new UserStateImpl();
public List<FileInfo> getFileList() {return new ArrayList<>();}
public FileInfo upload(String path) {//上传文件 LogUtils.log("upload file");HttpUtils.post("http://file", userState.getUserId());return new FileInfo();}
public FileInfo download(String url) {//下载文件 if (!userState.isLogin()) {return null;}return new FileInfo();}}
2.4 提取构造函数,依赖接口注入


重构后代码如下:
public class FileController {private final UserState userState;
public FileController(UserState userState) {this.userState = userState;}
public List<FileInfo> getFileList() {return new ArrayList<>();}
public FileInfo upload(String path) {//上传文件 LogUtils.log("upload file");HttpUtils.post("http://file", userState.getUserId());return new FileInfo();}
评论