【发布时间】:2018-10-30 03:39:15
【问题描述】:
我有这样的代码:
Map<String, String> args = new HashMap<>();
args.put("-T", "Tom Sawyer");
// args.put("-I", "1112223334");
if (args.containsKey("-T")) {
Book book = libraryService.findBookByTitle(args.get("-T"));
} else {
Book book = libraryService.findBookByIsbn(args.get("-I"));
}
图书馆服务:
public class LibraryService {
private final BookRepository bookRepository = new BookRepository();
public Book findBookByTitle(String title) {
return bookRepository.findByTitle(title);
}
public Book findBookByIsbn(String isbn) {
return bookRepository.findByIsbn(isbn);
}
书库:
public class BookRepository {
private List<Book> books = new ArrayList<>();
public Book findByIsbn(String isbn) {
return books.stream()
.filter(s -> s.getIsbn().equals(isbn))
.findFirst()
.orElseThrow(() -> new RuntimeException(NO_BOOKS_FOUND));
}
public Book findByTitle(String title) {
return books.stream()
.filter(s -> s.getTitle().equals(title))
.findFirst()
.orElseThrow(() -> new RuntimeException(NO_BOOKS_FOUND));
}
有没有避免ifs的干净方法?我希望我的代码决定是否必须使用参数-I 或-T。我处理了args 没有的情况,我只是简化了 StackOverflow 的代码。我在代码中多次使用 findByTitle 和 findByIsbn 方法,所以我不确定其他方法是否适合这里。
【问题讨论】:
-
能否多发些代码,尤其是代码重复的地方,让我们看看如何改进?
-
为了避免每次使用都重复 if,您可以将条件逻辑放在一个函数中。
-
@Sweeper 我发布了更多代码
-
我还是不明白你想如何改进你的代码。看起来不错。
-
args来自哪里?我想知道你为什么把它放到地图中
标签: java if-statement coding-style conditional-statements