ste*_*337 5 java if-statement coding-style conditional-statements
我有这样的代码:
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"));
}
Run Code Online (Sandbox Code Playgroud)
LibraryService:
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);
}
Run Code Online (Sandbox Code Playgroud)
BookRepository:
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));
}
Run Code Online (Sandbox Code Playgroud)
是否有一种干净的方法来避免ifs?我希望我的代码决定是否必须使用参数-I或-T.我处理的情况是什么args时候没有,我只是简化了StackOverflow的代码.我在代码中多次使用findByTitle和findByIsbn方法,所以我不确定另一种方法是否适合这里.
你的代码看起来相当不错,至少对我来说是这样。
您的 if 语句不需要删除。它们不会重复,因此请将它们保留在那里。
另一方面,我确实在findBy方法中发现了一些重复的代码:
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));
}
Run Code Online (Sandbox Code Playgroud)
您可以编写一个名为的新方法findBy:
private Book findBy<T>(Function<Book, T> selector, T value) {
return books.stream()
.filter(s -> selector.apply(s).equals(value))
.findFirst()
.orElseThrow(() -> new RuntimeException(NO_BOOKS_FOUND));
}
Run Code Online (Sandbox Code Playgroud)
然后findByIsbn打电话:findByTitlefindBy
public Book findByIsbn(String isbn) {
return findBy(Book::getIsbn, isbn);
}
public Book findByTitle(String title) {
return findBy(Book::getTitle, title);
}
Run Code Online (Sandbox Code Playgroud)