이번에는 지금 까지 했던거를 리팩토링 해보려고 해.
리팩토링이 뭐냐면 각자 해당하는 역할별로 기능을 분리시키는 작업? 이라고 생각하면 돼.
그래서 새로운 패키지와 클래스들을 만들어서 구현 해 볼거야.
이런식으로 구성을 다시 새로 짤거야.
먼저 MotivationController 클래스의 역할은 여기서 기능을 수행한다고 생각하면 돼.
Motivation클래스는 getter와 setter 놓는 곳, SystemController는 motivation종료 하는 곳 이라고 생각하자.
그럼 이제 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;
}
아니요.. 어려워 죽을것같은디요,,