else if(cmd.startsWith("article delete")) {
int id = Util.getId(cmd);
if(id == -1) continue;
Optional<Article> article = articles.stream().filter((a) -> a.getId() == id).findFirst();
if(article.isEmpty()) {
System.out.printf("%d번 게시글은 없습니다\n", id);
} else {
articles.remove(article.get());
System.out.printf("%d번 게시글이 삭제되엇습니다.\n", id);
}
}
public static int getId(String cmd) {
int id = -1;
try {
id = Integer.parseInt(cmd.split(" ")[2]);
} catch (Exception e) {
System.out.println("번호는 정수로 입력해");
}
return id;
}
코드 설명
①커멘드로 부터 id 분리하는 로직은, 조회 로직에도 있는 공통 로직이므로 분리하여 메소드화
②스트림 기능 활용하여 id 조회 및 null방지를 위해 optional로 로직 처리
아쉬웠던 점
굳이 optional을 사용 할거면, 기존 null체크랑 다름 없는 코드가 아니라, ifPresentOrElse등의 옵셔널 특화기능을 최대한 활용하는 편이 더 좋았다.
else if (cmd.startsWith("article list")) {
String searchKeyword = "";
if(cmd.startsWith("article list '") && cmd.endsWith("'") && cmd.indexOf('\'') != cmd.lastIndexOf('\'')) {
searchKeyword = cmd.substring("article list '".length(), cmd.length()-1);
}else if(!cmd.trim().equals("article list")) {
System.out.println("검색어는 article list '검색어'의 형식으로 입력해 주세요.");
continue;
}
final String searchWord = searchKeyword;
List<Article> articles = Main.articles.stream().filter((a) -> a.getTitle().contains(searchWord)).toList();
클라이언트에서 curd기능을 호출할 때 메소드는 다음과같은 두가지로 분류할 수 있다.
1. 클라이언트에서 리소스 식별자를 몰라도 호출할 수 있는 메소드
create (서버에서 생성 후 알려주게 된다.)
list
this를 반환하여 객체 생성 및 초기화를 연결하여 수행하는 방식