프롬프트 AI&OpenAPI&공공데이터를 활용한 웹앱개발자 양성 과정 17일차

서명원·2024년 1월 2일

1. 과제 및 구현

  1. 과제. crud중 delete 기능의 구현
  2. 구현 코드
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;
	}
  1. 코드 설명
    ①커멘드로 부터 id 분리하는 로직은, 조회 로직에도 있는 공통 로직이므로 분리하여 메소드화
    ②스트림 기능 활용하여 id 조회 및 null방지를 위해 optional로 로직 처리

  2. 아쉬웠던 점
    굳이 optional을 사용 할거면, 기존 null체크랑 다름 없는 코드가 아니라, ifPresentOrElse등의 옵셔널 특화기능을 최대한 활용하는 편이 더 좋았다.

     

2. 과제 및 구현 2

  1. 과제
    article list '~'를 입력하면 '~'가 포함된 글만 리스트로 보여주기
  1. 구현 코드
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();
  1. 코드 설명
    ①DB역활을 하는 List articles(전역변수)에서, 입력한 검색어가 타이틀과 일치하는 객체만 가져와 다시 리스트화 시켰다.
    ②상기 리스트를 전역변수와 동일한 변수명 articles에 담아, 목록을 보여주는 처리 안에서 기존 로직을 수정하지 않고, 단지 내용물만 바꿔친 articles를 참조하도록 하였다.

3. CRUD와 리소스

클라이언트에서 curd기능을 호출할 때 메소드는 다음과같은 두가지로 분류할 수 있다.
1. 클라이언트에서 리소스 식별자를 몰라도 호출할 수 있는 메소드
create (서버에서 생성 후 알려주게 된다.)
list

  1. 반면에 아래 작업들은 클라이언트 쪽에서 사용할 리소스의 식별자를 알아야 한다.
    read
    delete
    update

4. 생성자 체이닝(Constructor Chaining)

this를 반환하여 객체 생성 및 초기화를 연결하여 수행하는 방식

profile
백엔드 취업을 꿈꾸는 일본어 전공자

0개의 댓글