Motivation 프로그램 #3

Yullc·2025년 3월 24일
post-thumbnail

1. 리팩토링

이번에는 지금 까지 했던거를 리팩토링 해보려고 해.
리팩토링이 뭐냐면 각자 해당하는 역할별로 기능을 분리시키는 작업? 이라고 생각하면 돼.
그래서 새로운 패키지와 클래스들을 만들어서 구현 해 볼거야.

  • 먼저 새로운 패키지는 motivation, entity, controller, system/controller 이렇게 만들고
  • motivation -> controller -> (MotivationController) 클래스
  • motivation -> entity -> Motivation 클래스
  • system/controller -> SystemController 클래스

이런식으로 구성을 다시 새로 짤거야.

먼저 MotivationController 클래스의 역할은 여기서 기능을 수행한다고 생각하면 돼.
Motivation클래스는 getter와 setter 놓는 곳, SystemController는 motivation종료 하는 곳 이라고 생각하자.

2. delete

그럼 이제 MotivationController클래스에서 delete 부분을 구현 해보자.

  • 나는 먼저 생각한게 for문을 돌면서 motivations의 id를 비교해서 id와 일치하는 값으로 제거를 해야겠다고 생각했어.

  • 내가 입력한 값이랑 id랑 비교해서 일치하면 해당 motivations에 저장되어있는 객체를 ArrayList의 함수인 remove를 이용해서 지우는거지.

  • 그럼 여기서 문제는 id를 어떻게 뭘로 가져오냐 이거야. 그래서 생각한게 계속 써먹고 있는 split함수를 이용했어 예를 들어 delete 1하면 빈 공간으로 split해서 인덱스의 1번 값을 가져오면 숫자만 짤리니까 이걸로 비교해야겠다고 생각했어. 이제 내가 생각한 것들을 코드로 나타내보자,

    public void delete(String cmd) {
           int id = Integer.parseInt(cmd.split(" ")[1]);
    
           Motivation foundMotivation = null;
           int foundIndex = -1;
    
           for (int i = 0; i < motivations.size(); i++) {
               Motivation motivation = motivations.get(i);
               if (motivation.getId() == id) {
                   foundMotivation = motivation;
                   foundIndex = i;
                   break;
               }
           }
    
           if (foundMotivation == null) {
               System.out.println("해당 moti는 없던데????");
               return;
           }
    
           motivations.remove(foundIndex);
           System.out.println(id + "번 moti 삭제됨");
       }
### 3. edit
> 이번에는 수정 기능인데 일단 이건 우리가 add에서 사용한 내용을 거의 그대로 가져와서 시작거야. 

- edit기능에는 뭐가 필요할까를 먼저 생각해보면 add에서 했던거 처럼 새로운 수정사항을 추가하는 기능이 있어야 될거야.

```java
 public void edit(String cmd) {
        int id;
        try {
            id = Integer.parseInt(cmd.split(" ")[1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("명령어 확인해라");
            return;
        }

        Motivation foundMotivation = findById(id);

        if (foundMotivation == null) {
            System.out.println("해당 moti는 없던데????");
            return;
        }

        // 찾은 motivation의 인스턴스 변수에 접근
        System.out.println("body(기존) : " + foundMotivation.getBody());
        System.out.println("source(기존) : " + foundMotivation.getSource());

        String newBody;
        String newSource;
        // 수정사항 입력받기
        while (true) {
            System.out.print("new body : ");
            newBody = Container.getScanner().nextLine().trim();

            if (newBody.length() != 0) {
                break;
            }
            System.out.println("수정사항(body) 입력해");
        }

        while (true) {
            System.out.print("new source : ");
            newSource = Container.getScanner().nextLine();

            if (newSource.length() != 0) {
                break;
            }
            System.out.println("수정사항(source) 입력해");
        }

        // 찾은 motivation의 인스턴스 변수 값 수정
        foundMotivation.setBody(newBody);
        foundMotivation.setSource(newSource);

        System.out.println(id + "번 moti 수정됨");

    }

    // 명령어의 id 와 일치하는 motivation 찾기
    private Motivation findById(int id) {
        for (Motivation motivation : motivations) {
            if (motivation.getId() == id) {
                return motivation;
            }
        }
        return null;
    }
  • 이 코드를 보면 먼저 try-catch문을 이용해 id를 split해서 가져오고 명령어가 잘못되면 다시 입력하라는 문구를 보여주게 할거야.
  • 그리고 foundMotivation변수를 이용해 id를 찾을건데, 만약 id값이 null이면 그런 moti는 없다고 출력하게 하고 return할거야.
  • 이제 foundMotivation을 이용해 Body랑 Source에 접근 하고 새로운 newBody랑 newSource라는 변수를 만들어 수정한 내용을 여기에 저장시킬거야.
  • 그리고 이제 while문을 돌면서 수정사항을 기입할건데 생가보다 간단하지?

아니요.. 어려워 죽을것같은디요,,

profile
아자아자자

0개의 댓글