1、精准命名,类名词,函数动词,见名知意
2、长函数,对方法进行拆分,拆成小函数
3、大类,职责单一,对不同的业务的变量或方法用不同的类来实现,避免一个类处理过多的业务
4、长参数,将同一类型的参数封装、避免使用标识参数
5、类中对外提供方法访问类中的属性,避免直接链式访问
6、控制语句:循环语句尽量减少嵌套,嵌套逻辑抽取出来,减少缩减行数(多层if-else 判断嵌套)
public void distributeEpubs (final long bookId) {
List<Epub> epubs = this.getEpubsByBookId(bookId);
for(Epub epub : epubs) {
if (epub.isValid()) {
boolean registered = this.registerIsbn(epub);
if(registered) {
this.sendEpub(epub);
}
}
}
}
改进后
public void distributeEpubs(final long bookId) {
List<Epub> epubs = this.getEpubsByBookId(bookId);
for (Epub epub : epubs) {
this.distributeEpub(epub);
}
}
private void distributeEpub(final Epub epub) {
if (!epub.isValid()) {
return;
}
boolean registered = this.registerIsbn(epub);
if (!registered) {
return;
}
this.sendEpub(epub);
}
7、基本数据类型作为方法返回值,使用对象替换基本数据类型,数据的校验放在对象里
class Price {
private long price;
public Price(final double price) {
if (price <= 0) {
throw new IllegalArgumentException("Price should be positive");
}
this.price = price;
}
}
8、setter不可控,可以专门为赋值的业务提供一个方法,尽量移除设值函数
9、一次性声明变量,把变量的赋值放到方法里返回,不要先声明null再赋值,try-catch时变量直接在try里面声明、用声明式的方式对集合进行初始化,不是先创建集合再添加元素
EpubStatus status = null;
CreateEpubResponse response = createEpub(request);
if (response.getCode() == 201) {
status = EpubStatus.CREATED;
} else {
status = EpubStatus.TO_CREATE;
}
改进
final CreateEpubResponse response = createEpub(request);
final EpubStatus status = toEpubStatus(response);
private EpubStatus toEpubStatus(final CreateEpubResponse response) {
if (response.getCode() == 201) {
return EpubStatus.CREATED;
}
return EpubStatus.TO_CREATE;
}
try (InputStream is = new FileInputStream(...)) {
...
}
10、保持代码各层面的一致性,比如命名、方案等
11、使用Optional减少if-else 、函数式编程简化代码、lambda表达式处理集合,lambda表达式中的逻辑进行声明式的方式处理,而不是写在lambda表达式里面,完美的lambda表达式应该只有一行代码
Optional<Author> author = book.getAuthor();
String name = author.map(Author::getName).orElse(null);
public ChapterParameters toParameters(final List<Chapter> chapters) {
List<ChapterParameter> parameters = new ArrayList<>();
for (Chapter chapter : chapters) {
if (chapter.isApproved()) {
parameters.add(toChapterParameter(chapter));
}
}
return new ChapterParameters(parameters);
}
public ChapterParameters toParameters(final List<Chapter> chapters) {
List<ChapterParameter> parameters = chapters.stream()
.filter(Chapter::isApproved)
.map(this::toChapterParameter)
.collect(Collectors.toList());
return new ChapterParameters(parameters);
}
12、不同层,参数类型不一样,做好不同层之间的防腐
class NewBookRequest {
public NewBookParameters toNewBookRequest(long userId) {
...
}
}
@PostMapping("/books")
public NewBookResponse createBook(final NewBookRequest request, final Authentication authentication) {
long userId = getUserIdentity(authentication);
boolean result = this.service.createBook(request.toNewBookParameter(userId));
...
}
13、抽象不应依赖于细节,细节应依赖于抽象。