입문 스프링 강의 수강중.
기존 코드
public class Customer {
private String customerName;
private String customerEmail;
private String customerRating;
private int orderAmount = 0;
public Customer(String customerName,String customerEmail, int orderAmount){
this.customerName = customerName;
this.customerEmail = customerEmail;
this.customerRating = gradeRating();
// amount 앞에 호출 되어서 에러발생
this.orderAmount = orderAmount;
}
private String gradeRating(){
if(orderAmount<500000){
this.customerRating = "Bronze";
}
else if(orderAmount >= 500000 && orderAmount < 1000000){
this.customerRating = "Silver";
}
else if (orderAmount >= 1000000 && orderAmount < 2000000){
this.customerRating = "Gold";
}
else if(orderAmount >= 2000000) {
this.customerRating = "Platinum";
}
}//return 없음, 불필요한 조건이 있음
public String getCustomerName(){
return customerName;
}
public String getCustomerEmail(){
return customerEmail;
}
public String getCustomerRating(){
return customerRating;
}
public int getOrderAmount(){
return orderAmount;
}
void printCustomerInfo(){
System.out.println("고객이름: " + customerName + "고객이메일: " + customerEmail + "고객등급: " + customerRating + "누적금액: " + orderAmount);
}
}
피드백 받아서 수정한 코드
public class Customer {
private String customerName;
private String customerEmail;
private String customerRating;
private int orderAmount = 0;
public Customer(String customerName,String customerEmail, int orderAmount){
this.customerName = customerName;
this.customerEmail = customerEmail;
this.orderAmount = orderAmount;
this.customerRating = gradeRating();
// 호출 순서 변경
}
private String gradeRating(){
Rank rank = Rank.fromAmount(orderAmount);
return customerRating = rank.getName();
// return 추가, enum활용
}
// 사용하지 않는 게터 삭제
void printCustomerInfo(){
System.out.println("고객이름: " + customerName + " 고객이메일: " + customerEmail + " 누적금액: " + orderAmount + " 고객등급: " + customerRating );
}
}
//enum 구현
public enum Rank {
BRONZE("Bronze", 0, 500000),
SILVER("Silver", 500000, 1000000),
GOLD("Gold", 1000000, 2000000),
PLATINUM("Platinum", 2000000, Integer.MAX_VALUE);
private final String name;
private final int minAmount;
private final int maxAmount;
Rank(String name, int minAmount, int maxAmount) {
this.name = name;
this.minAmount = minAmount;
this.maxAmount = maxAmount;
}
public String getName(){
return name;
}
public static Rank fromAmount(int amount){
for(Rank rank : values()){
if(rank.minAmount <= amount && rank.maxAmount > amount){
return rank;
}
}
}
}
//CommerceSystem 클래스에 추가
System.out.print("이름: ");
String name = sc.next();
System.out.print("이메일: ");
String email = sc.next();
System.out.print("금액: ");
int amount = sc.nextInt();
if(amount>=0) {
Customer customer = new Customer(name, email, amount);
customer.printCustomerInfo();
}else{
throw new IllegalArgumentException("금액이 잘못 입력 되었습니다.");
}