避免写出难以理解的大类
- 原因:一个人理解的东西是有限的,没人能面对所有的细节
- 大类的产生:
- 操作要点:把类写小,越小越好
案例1:
1 2 3 4 5 6 7 8 9 10 11 12
| public class User { private long userId; private String name; private String nickname; private String email; private String phoneNumber; private AuthorType authorType; private ReviewStatus authorReviewStatus; private EditorType editorType; ... }
|
问题:userId,name这些是和用户关联的,后面的AuthorType,ReviewStatus,EditorType和用户信息无关
修正:AuthorType,ReviewStatus,EditorType和用户信息无关 拆成单独的类,通过userId去关联
1 2 3 4 5 6 7
| public class Author { private long userId; private AuthorType authorType; private ReviewStatus authorReviewStatus; ... }
|
1 2 3 4 5 6
| public class Editor { private long userId; private EditorType editorType; ... }
|
案例2
1 2 3 4 5 6 7 8 9
| public class User { private long userId; private String name; private String nickname; private String email; private String phoneNumber; ... }
|
问题:这个类中userId,name,nickname是属于用户的基本信息,而email,phoneNumber其实是属于用户的联系方式
修正:对字段进行分组,把email,phoneNumber放在单独的contact类
1 2 3 4 5 6 7 8
| public class User { private long userId; private String name; private String nickname; private Contact contact; ... }
|
1 2 3 4 5
| public class Contact { private String email; private String phoneNumber; ... }
|