java/코드 리뷰

11. ex2 - (1) UserApp Demo (예외를 활용한 User 서비스)

Astaroth아스 2020. 4. 23. 19:16
1
2
3
4
5
6
7
8
9
10
11
package ex2;
 
// 모든 서비스 클래스가 공통으로 사용하는 속성이나 기능을 정의
public abstract class CommonService {
    
    public void processError(String errorCode, String msg) {
        throw new HTAException(errorCode, msg);
    }
 
}
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package ex2;
 
public class HTAException extends RuntimeException {
    
    private String errorCode;
    
    public HTAException() {
        
    }
    
    public HTAException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    
    public String getErrorCode() {
        return errorCode;
    }
 
//    public HTAException(Throwable cause) {
//        super(cause);
//    }
//    
//    public HTAException(String message, Throwable cause) {
//        super(message, cause);
//    }
    
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ex2;
 
public class DuplicatedUserIdException extends HTAException {
    
    public DuplicatedUserIdException() {
        
    }
    
//    public DuplicatedUserIdException(String msg) {
//        super(msg);
//    }
    
}
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ex2;
 
public class PasswordNotEqualException extends HTAException {
    
    public PasswordNotEqualException() {
        
    }
    
//    public PasswordNotEqualException(String id) {
//        super(id);
//    }
    
}
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ex2;
 
public class UserNotFoundException extends HTAException {
    
    public UserNotFoundException() {
        
    }
//    
//    public UserNotFoundException(String msg) {
//        super(msg);
//    }
    
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ex2;
 
import java.util.HashMap;
import java.util.Map;
 
public class ErrorCode {
    
    private Map<StringString> errorCodes = new HashMap<StringString>();
    
    public ErrorCode() {
        errorCodes.put("ERROR_USER_001","아이디가 중복되었습니다");
       errorCodes.put("ERROR_USER_002","가입되지 않은 아이디입니다");
       errorCodes.put("ERROR_USER_003","비밀번호가 존재하지 않습니다");
       errorCodes.put("ERROR_USER_004","부적절한 아이디입니다");
       errorCodes.put("ERROR_USER_005","안전하지 못한 비밀번호 조합입니다");
    }
    
    public String getDescription(String errorCode) {
        return errorCodes.get(errorCode);
    }
    
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package ex2;
 
public class User {
    
    private String id;
    private String name;
    private String pwd;
    
    public User() {
        
    }
    
    public User(String id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package ex2;
 
public class UserRepository {
    
    private User[] db = new User[100];
    private int position = 0;
    
    public void insert(User user) {
        db[position] = user;
        position++;
    }
    
    public User getUserById(String userId) {
        for (int i=0; i<position; i++) {
            User user = db[i];
            if(user.getId().equals(userId)) {
                return user;
            }
            
        }
        return null;
    }
    
    
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package ex2;
 
public class UserService extends CommonService {
    
    private UserRepository repo = new UserRepository();
    
    public void addNewUser(String id, String name, String pwd) throws HTAException { // 런타임 예외면  throws HTAException 삭제 가능 
        User savedUser = repo.getUserById(id);
        
        if(savedUser != null) {
//            System.out.println("동일한 아이디가 존재합니다.");
//            return;
//            throw new HTAException("[" + id + "]는 이미 사용중인 아이디입니다.");
//            throw new DuplicatedUserIdException(id);
//            throw new HTAException("ERROR_USER_001", id);
            processError("ERROR_USER_001", id);
        }
        
        User user = new User(id, name, pwd);
        repo.insert(user);
        
    }
    
    public void login(String id, String pwd) throws HTAException {
        User user = repo.getUserById(id);
        if (user == null) {
//            throw new HTAException(아이디 혹은 비밀번호가 일치하지 않습니다.");
//            throw new UserNotFoundException(id);
//            throw new HTAException("ERROR_USER_002", id);
            processError("ERROR_USER_002", id);
        }
        
        if (!user.getPwd().equals(pwd)) {
//            throw new HTAException(아이디 혹은 비밀번호가 일치하지 않습니다.");
//            throw new PasswordNotEqualException(id);
//            throw new HTAException("ERROR_USER_003", pwd);
            processError("ERROR_USER_003", pwd);
        }
        
        // 로그인 관련 처리 수행
        
    }
    
    public void changePassword(String id, String oldPwd, String newPwd) throws HTAException {
        User user = repo.getUserById(id);
        if(user == null) {
//            throw new HTAException(아이디 혹은 비밀번호가 일치하지 않습니다.");
//            throw new UserNotFoundException(id);
//            throw new HTAException("ERROR_USER_002", id);
            processError("ERROR_USER_002", id);
        }
 
        if(!user.getPwd().equals(oldPwd)) {
//            throw new HTAException(아이디 혹은 비밀번호가 일치하지 않습니다.");
//            throw new PasswordNotEqualException(id);
//            throw new HTAException("ERROR_USER_003", oldPwd);
            processError("ERROR_USER_003", oldPwd);
        }
        
        user.setPwd(newPwd);
    }
    
}
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package ex2;
 
import java.util.Scanner;
 
public class UserApp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        UserService service = new UserService();
        ErrorCode code = new ErrorCode();
 
        while (true) {
 
            try {
                System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
                System.out.println("1.회원가입    2.로그인    3.비밀번호변경    0.종료");
                System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
 
                System.out.print("메뉴를 선택하세요 : ");
                int menuNo = sc.nextInt();
 
                if (menuNo == 1) {
                    System.out.println("[회원가입]");
 
                    System.out.print("아이디를 입력하세요 : ");
                    String id = sc.next();
                    System.out.print("이름을 입력하세요 : ");
                    String name = sc.next();
                    System.out.print("비밀번호를 입력하세요 : ");
                    String pwd = sc.next();
                    
                    service.addNewUser(id, name, pwd); // HTA 예외발생이 예고된 메서드 실행
                    
                    System.out.println("### 가입이 완료되었습니다 ###"); // 예고된 예외가 발생하지 않은 경우에만 실행됨
 
                } else if (menuNo == 2) {
                    System.out.println("[로그인]");
                    
                    System.out.print("아이디를 입력하세요 : ");
                    String id = sc.next();
                    System.out.print("비밀번호를 입력하세요 : ");
                    String pwd = sc.next();
                    
                    service.login(id, pwd);
                    System.out.println("### 로그인이 완료되었습니다 ###");
                    
                } else if (menuNo == 3) {
                    System.out.println("[비밀번호 변경]");
                    
                    System.out.print("아이디를 입력하세요 : ");
                    String id = sc.next();
                    System.out.print("이전 비밀번호를 입력하세요 : ");
                    String oldPwd = sc.next();
                    System.out.print("비밀번호를 입력하세요 : ");
                    String newPwd = sc.next();
                    
                    service.changePassword(id, oldPwd, newPwd);
                    System.out.println("### 비밀번호 변경이 완료되었습니다 ###");
                    
                } else if (menuNo == 0) {
                    break;
                }
                
            } catch (HTAException e) {
//                String errorMessage = e.getMessage();
//                System.err.println("[에러메시지] -> " + errorMessage);
                System.err.println(e);
                
                String errorCode = e.getErrorCode();
                String errorDescription = code.getDescription(errorCode);
                System.err.println("[" + errorCode + "] -> " + errorDescription);
            }
        }
 
    }
}