return으로 코드를 짜면
package ex15;
class Repository {
// 1이면 존재하는 회원, -1이면 존재하지 않음
int findIdAndPw(String id, String pw) {
System.out.println("레포지토리 findIdAndPw 호출됨");
if (id.equals("ssar") && pw.equals("5678")) {
return 1;
} else {
return -1;
}
}
}
// 책임 : 유효성 검사
class Controller01 {
String login(String id, String pw) {
System.out.println("컨트롤러 로그인 호출됨");
if (id.length() < 4) {
return "유효성검사 : id의 길이가 4자 이상이어야 합니다.";
}
if (pw.length() < 4) {
return "유효성검사 : id의 길이가 4자 이상이어야 합니다.";
}
Repository repo = new Repository();
int code = repo.findIdAndPw(id, pw);
if (code == -1) {
return "id 혹은 pw가 잘못됐습니다";
}
return "로그인이 완료되었습니다";
}
}
public class Try03 {
public static void main(String[] args) {
Controller01 con = new Controller01();
String message = con.login("ssar", "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789");
System.out.println(message);
}
} 
예외처리로 바꾼 코드
package ex15;
class Repository02 {
// 1이면 존재하는 회원, -1이면 존재하지 않음
void findIdAndPw(String id, String pw) {
System.out.println("레포지토리 findIdAndPw 호출됨");
if (!(id.equals("ssar") && pw.equals("5678"))) {
throw new RuntimeException("아이디 혹은 비번 틀림");
}
}
}
// 책임 : 유효성 검사
class Controller02 {
void login(String id, String pw) {
System.out.println("컨트롤러 로그인 호출됨");
if (id.length() < 4) {
throw new RuntimeException("id 길이가 최소 4자 이상이어야 해요");
}
if (pw.length() < 4) {
throw new RuntimeException("pw 길이가 최소 4자 이상이어야 해요");
}
Repository repo = new Repository();
repo.findIdAndPw(id, pw);
}
}
public class Try04 {
public static void main(String[] args) {
Controller01 con = new Controller01();
try {
con.login("ssar", "123");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Share article