1、面向对象类封装性,避免属性直接赋值,而应该使用方法暴露
#1 改造前
public void approve(final long bookId) {
...
book.setReviewStatus(ReviewStatus.APPROVED);
...
}
#2 改造后
public void approve(final long bookId) {
...
book.approve();
...
}
2、复数命名:不使用List,Set,Map这种,直接使用s结尾
3、函数参数:
a、长度不超过2个,超过2个包装类
b、如果调用时需要计算,先使用变量算出来,再放入参数列表中
c、不要企图使用函数参数控制if-else逻辑,试图封装不同的函数
这里会破坏单一职责原则和接口隔离原则
public void buyCourse(long userId, long courseId, boolean isVip);
// 将其拆分成两个函数
public void buyCourse(long userId, long courseId);
public void buyCourseForVip(long userId, long courseId);
4、模型封装:一个模型的封装应该以行为为基础
改造前
--------------------------
public void createBook(final NewBookParamters parameters) {
...
Book book = Book.builder
.title(parameters.getTitle())
.introduction(parameters.getIntroduction())
.coverUrl(parameters.getCoverUrl())
.type(parameters.getType())
.channel(parameters.getChannel())
.protagonists(parameters.getProtagonists())
.tags(parameters.getTags())
.completed(parameters.isCompleted())
.build();
this.repository.save(book);
}
改造后
--------------------------
public class NewBookParamters {
private String title;
private String introduction;
private URL coverUrl;
private BookType type;
private BookChannel channel;
private String protagonists;
private String tags;
private boolean completed;
public Book newBook() {
return Book.builder
.title(title)
.introduction(introduction)
.coverUrl(coverUrl)
.type(type)
.channel(channel)
.protagonists(protagonists)
.tags(tags)
.completed(completed)
.build();
}
}
public void createBook(final NewBookParamters parameters) {
...
Book book = parameters.newBook();
this.repository.save(book);
}
5、动静分离:分离关注点,静态不变的数据可以成为类的一个字段,而不应该通过参数传递
--------------------------
public void getChapters(final long bookId,
final HttpClient httpClient,
final ChapterProcessor processor) {
HttpUriRequest request = createChapterRequest(bookId);
HttpResponse response = httpClient.execute(request);
List<Chapter> chapters = toChapters(response);
processor.process(chapters);
}
改造后
--------------------------
public void getChapters(final long bookId) {
HttpUriRequest request = createChapterRequest(bookId);
HttpResponse response = this.httpClient.execute(request);
List<Chapter> chapters = toChapters(response);
this.processor.process(chapters);
}
6、for优化:内部提炼单个函数
7、else消除:尽早返回
8、swith优化:封装策略模式
9、基本类型偏执: 不应该暴露业务方更多业务代码逻辑
改造前:String name = book.getAuthor().getName();
改造后 String name= book.getAuthorName(); //依赖委托实现
标签:重构,技巧,parameters,代码,long,final,void,private,public From: https://www.cnblogs.com/binfirechen/p/17985899