23. 引入参数对象

资料参考:https://blog.csdn.net/knightswarrior/article/details/9447815

概念:本文中的“引入参数对象”是指当一个方法的参数过多或者过为复杂时,可以考虑把这些参数封装成一个单独的类。

正文:如果一个方法所需要的参数大于5个,理解该方法的签名就变得比较困难,因为这样感觉参数很长、样式不好并且没有分类,所以我们有必要把参数进行封装。

 1 /**
 2  * 注册类
 3  */
 4 class Registration {
 5     /**
 6      * 注册
 7      *
 8      * @param amount 数量
 9      * @param student 学生
10      * @param courses 课程列表
11      * @param credits 学分
12      */
13     public void Create(double amount, Student student, List<Course> courses, double credits) {
14         // doSomething
15     }
16 }
1 /**
2  * 学生类
3  */
4 class Student {
5 }
1 /**
2  * 课程类
3  */
4 class Course {
5 }

通常这种情形下创建一个用户传递参数的类是很有帮助的,这会使得代码更容易明白也更灵活,因为当你需要增加参数时,只需要给参数类添加一个属性即可。请注意只有当你发现方法的参数比较多时才应该应用该重构,如果方法的参数比较少,就没有必要应用此重构,因为该重构会增加系统中类的数量,同时也会加大维护负担。所以要看参数情况而定。
重构后的代码如下(Android studio 中可用introduce parameter object来进行重构):

 1 /**
 2  * 注册类
 3  */
 4 class Registration {
 5     /**
 6      * 注册
 7      *
 8      * @param registrationContext 注册上下文
 9      */
10     public void Create(RegistrationContext registrationContext) {
11         // doSomething
12     }
13 }
 1 /**
 2  * 注册上下文类
 3  */
 4 public class RegistrationContext {
 5     private final double amount;
 6     private final Student student;
 7     private final List<Course> courses;
 8     private final double credits;
 9 
10     /**
11      * @param amount  数量
12      * @param student 学生
13      * @param courses 课程列表
14      * @param credits 学分
15      */
16     public RegistrationContext(double amount, Student student, List<Course> courses, double credits) {
17         this.amount = amount;
18         this.student = student;
19         this.courses = courses;
20         this.credits = credits;
21     }
22 
23     public double getAmount() {
24         return amount;
25     }
26 
27     public Student getStudent() {
28         return student;
29     }
30 
31     public List<Course> getCourses() {
32         return courses;
33     }
34 
35     public double getCredits() {
36         return credits;
37     }
38 }

总结:这种重构很重要,尤其是当一个方法的参数比较多的时候,不管是大中型项目还是小型项目,都会遇到这种场景,所以建议大家多使用这个重构。

posted @ 2020-12-29 19:32  ysyouaremyall  阅读(394)  评论(0编辑  收藏  举报