code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,50 @@ +package lotto.controller; + +import lotto.model.Lotto; +import lotto.model.LottoNumberMaker; +import lotto.model.LottoPercentageCalculation; +import lotto.model.constants.LottoPrize; +import lotto.view.LottoInput; +import lotto.view.LottoOutput; + +import java.util.ArrayList; +import java.util.List; + +import static java.util.Arrays.asList; +import static lotto.model.constants.LottoPrize.*; + +public class LottoController { + private static final LottoNumberMaker lottoNumberMaker = new LottoNumberMaker(); + private static final LottoInput lottoInput = new LottoInput(); + private static final LottoOutput lottoOutput = new LottoOutput(); + private static final LottoPercentageCalculation lottoPercentageCalculation = new LottoPercentageCalculation(); + public static void setPrice() { + lottoNumberMaker.checkInt(); + } + +// static List<LottoPrize> LottoPrizelist= asList(FIFTH_PRIZE,FOURTH_PRIZE,THIRD_PRIZE,SECOND_PRIZE,FIRST_PRIZE); + public static void setBuyLottoNumberPrint() { + lottoOutput.buyLottoNumberPrint(lottoNumberMaker.getLottoNumber()); + } + + public static void setPrizeNumberInput() { + Lotto lotto = new Lotto(lottoInput.prizeNumberInput()); + lotto.checkSame(lottoInput.bonusNumberInput(),lottoNumberMaker.getLottoNumber()); + } + + public static void winningStatistic() { + List<String> lottoPrizes = new ArrayList<>(); + for(LottoPrize lottoPrize: LottoPrize.values()){ + lottoPrizes.add(lottoPrize.getText()+lottoPrize.getWinCount()+lottoPrize.getUnit()); + } + LottoOutput.seeWinningStatstic(lottoPrizes); + } + + public static void PerformanceCalculation() { + lottoOutput.seePercentage(lottoPercentageCalculation.percentageCalculation(LottoPrize.values(),lottoNumberMaker.getBuyPrice())); + } + + public String askPrice() { + return lottoInput.askPrice(); + } +} \ No newline at end of file
Java
컨트롤러 안에 대부분의 메서드와 변수를 static 처리한 별도의 이유가 있나요?
@@ -0,0 +1,79 @@ +package lotto.model; + +import lotto.model.constants.LottoPrize; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +import static lotto.constants.ErrorMessage.DUPLICATION; +import static lotto.constants.ErrorMessage.SIXNUMBER; +import static lotto.model.constants.LottoPrize.*; +public class Lotto { + private final List<Integer> numbers; + + public Lotto(List<Integer> numbers) { + validate(numbers); + duplicate(numbers); + this.numbers = numbers; + } + + private void duplicate(List<Integer> numbers) { + List<Integer> duplication = numbers.stream() + .distinct() + .toList(); + if (duplication.size() != numbers.size()) { + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(SIXNUMBER.getMessage()); + } + } + public void checkSame(Integer bonusNumber, List<List<Integer>> lottoNumber) { + bonusDuplication(bonusNumber); + for (List<Integer> integers : lottoNumber) { + List<Integer> Result = integers.stream() + .filter(i -> this.numbers.stream().anyMatch(Predicate.isEqual(i))) + .toList(); + long bonusResult = integers.stream() + .filter(bonusNumber::equals).count(); + CheckPrize(Result.size(), bonusResult).addWinCount(); + + } + } + + private void bonusDuplication(Integer bonusNumber) { + List<Integer> Result = this.numbers.stream() + .filter(i-> !Objects.equals(i, bonusNumber)) + .toList(); + if(Result.size()!=6){ + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + + } + + public LottoPrize CheckPrize(int result, long bonusResult){ + if(result==6){ + return FIRST_PRIZE; + } + if(result==5&&bonusResult==1){ + return SECOND_PRIZE; + } + if(result==5&&bonusResult==0){ + return THIRD_PRIZE; + } + if(result==4){ + return FOURTH_PRIZE; + } + if(result==3){ + return FIFTH_PRIZE; + } + if(result<3){ + return LOOSE; + } + throw new IllegalArgumentException("존재 하지 않는 순위입니다."); + } +}
Java
bonus의 경우 long형을 사용한 이유가 있나요? 그리고 해당 메서드가 lotto 도메인에서 꼭 선언되야 하는 이유가 있는지 궁금합니다 !!(lotto객체가 가지는 변수를 사용하지 않은거 같아서요 !!)
@@ -0,0 +1,67 @@ +package lotto.model; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.controller.LottoController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static lotto.constants.ErrorMessage.ISNOTINTEGER; +import static lotto.constants.ErrorMessage.NOTTHOUSAND; + +public class LottoNumberMaker { + private static int buyPrice; + private static final List<List<Integer>> numbers = new ArrayList<>(); + private static final LottoController lottoController = new LottoController(); + + public static int getBuyPrice() { + return buyPrice; + } + + public void makeLottoNumber(Integer count) { + buyPrice = count; + checkThousand(count); + IntStream.range(0, count / 1000) + .forEach(i -> numbers.add(makeRandomNumber())); + } + + private void checkThousand(Integer count) { + if(count%1000!=0){ + throw new IllegalArgumentException(NOTTHOUSAND.getMessage()); + } + return; + } + + private List<Integer> makeRandomNumber() { + return Randoms.pickUniqueNumbersInRange(1, 45, 6).stream() + .sorted() + .collect(Collectors.toList()); + } + + public void checkInt() { + while (true) { + try { + int number = checkCount(); + makeLottoNumber(number); + break; + } catch (IllegalArgumentException e) { + System.out.println(ISNOTINTEGER.getMessage()); + System.out.println(NOTTHOUSAND.getMessage()); + } + } + } + + private int checkCount() { + try { + return Integer.parseInt(lottoController.askPrice()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ISNOTINTEGER.getMessage()); + } + } + + public List<List<Integer>> getLottoNumber() { + return numbers; + } +}
Java
Lotto가 List'<'Integer'>'형을 가지는데 List'<'Lotto'>'로 만들었다면 어떨까요 ?!
@@ -0,0 +1,67 @@ +package lotto.model; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.controller.LottoController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static lotto.constants.ErrorMessage.ISNOTINTEGER; +import static lotto.constants.ErrorMessage.NOTTHOUSAND; + +public class LottoNumberMaker { + private static int buyPrice; + private static final List<List<Integer>> numbers = new ArrayList<>(); + private static final LottoController lottoController = new LottoController(); + + public static int getBuyPrice() { + return buyPrice; + } + + public void makeLottoNumber(Integer count) { + buyPrice = count; + checkThousand(count); + IntStream.range(0, count / 1000) + .forEach(i -> numbers.add(makeRandomNumber())); + } + + private void checkThousand(Integer count) { + if(count%1000!=0){ + throw new IllegalArgumentException(NOTTHOUSAND.getMessage()); + } + return; + } + + private List<Integer> makeRandomNumber() { + return Randoms.pickUniqueNumbersInRange(1, 45, 6).stream() + .sorted() + .collect(Collectors.toList()); + } + + public void checkInt() { + while (true) { + try { + int number = checkCount(); + makeLottoNumber(number); + break; + } catch (IllegalArgumentException e) { + System.out.println(ISNOTINTEGER.getMessage()); + System.out.println(NOTTHOUSAND.getMessage()); + } + } + } + + private int checkCount() { + try { + return Integer.parseInt(lottoController.askPrice()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ISNOTINTEGER.getMessage()); + } + } + + public List<List<Integer>> getLottoNumber() { + return numbers; + } +}
Java
도메인에서 컨트롤러를 사용한 이유가 궁금합니다
@@ -0,0 +1,67 @@ +package lotto.model; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.controller.LottoController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static lotto.constants.ErrorMessage.ISNOTINTEGER; +import static lotto.constants.ErrorMessage.NOTTHOUSAND; + +public class LottoNumberMaker { + private static int buyPrice; + private static final List<List<Integer>> numbers = new ArrayList<>(); + private static final LottoController lottoController = new LottoController(); + + public static int getBuyPrice() { + return buyPrice; + } + + public void makeLottoNumber(Integer count) { + buyPrice = count; + checkThousand(count); + IntStream.range(0, count / 1000) + .forEach(i -> numbers.add(makeRandomNumber())); + } + + private void checkThousand(Integer count) { + if(count%1000!=0){ + throw new IllegalArgumentException(NOTTHOUSAND.getMessage()); + } + return; + } + + private List<Integer> makeRandomNumber() { + return Randoms.pickUniqueNumbersInRange(1, 45, 6).stream() + .sorted() + .collect(Collectors.toList()); + } + + public void checkInt() { + while (true) { + try { + int number = checkCount(); + makeLottoNumber(number); + break; + } catch (IllegalArgumentException e) { + System.out.println(ISNOTINTEGER.getMessage()); + System.out.println(NOTTHOUSAND.getMessage()); + } + } + } + + private int checkCount() { + try { + return Integer.parseInt(lottoController.askPrice()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ISNOTINTEGER.getMessage()); + } + } + + public List<List<Integer>> getLottoNumber() { + return numbers; + } +}
Java
로또 구입 금액또한 1000으로 고정시키는 것 보다 확장성 측면에서 고려하여 상수 처리해서 사용해도 좋을거같아요
@@ -1,5 +1,7 @@ package lotto; +import lotto.model.Lotto; +import lotto.model.LottoNumberMaker; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -22,6 +24,11 @@ void createLottoByDuplicatedNumber() { assertThatThrownBy(() -> new Lotto(List.of(1, 2, 3, 4, 5, 5))) .isInstanceOf(IllegalArgumentException.class); } + @DisplayName("로또 번호가 6개 미만이면 예외가 발생한다.") + @Test + void createLottoByMinSize() { + assertThatThrownBy(() -> new Lotto(List.of(1))) + .isInstanceOf(IllegalArgumentException.class); + } - // 아래에 추가 테스트 작성 가능 } \ No newline at end of file
Java
단위 테스트도 도메인 별로 다양하게 진행해보면 더 좋을거 같아요 :)
@@ -1,7 +1,13 @@ package lotto; +import lotto.controller.LottoController; + public class Application { public static void main(String[] args) { - // TODO: 프로그램 구현 + LottoController.setPrice(); + LottoController.setBuyLottoNumberPrint(); + LottoController.setPrizeNumberInput(); + LottoController.winningStatistic(); + LottoController.PerformanceCalculation(); } }
Java
순서대로 모두 실행해야한다면 controller안에서 하나의 메소드로 실행하면 조금 더 코드가 깔끔해질 것 같아요.
@@ -0,0 +1,79 @@ +package lotto.model; + +import lotto.model.constants.LottoPrize; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +import static lotto.constants.ErrorMessage.DUPLICATION; +import static lotto.constants.ErrorMessage.SIXNUMBER; +import static lotto.model.constants.LottoPrize.*; +public class Lotto { + private final List<Integer> numbers; + + public Lotto(List<Integer> numbers) { + validate(numbers); + duplicate(numbers); + this.numbers = numbers; + } + + private void duplicate(List<Integer> numbers) { + List<Integer> duplication = numbers.stream() + .distinct() + .toList(); + if (duplication.size() != numbers.size()) { + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(SIXNUMBER.getMessage()); + } + } + public void checkSame(Integer bonusNumber, List<List<Integer>> lottoNumber) { + bonusDuplication(bonusNumber); + for (List<Integer> integers : lottoNumber) { + List<Integer> Result = integers.stream() + .filter(i -> this.numbers.stream().anyMatch(Predicate.isEqual(i))) + .toList(); + long bonusResult = integers.stream() + .filter(bonusNumber::equals).count(); + CheckPrize(Result.size(), bonusResult).addWinCount(); + + } + } + + private void bonusDuplication(Integer bonusNumber) { + List<Integer> Result = this.numbers.stream() + .filter(i-> !Objects.equals(i, bonusNumber)) + .toList(); + if(Result.size()!=6){ + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + + } + + public LottoPrize CheckPrize(int result, long bonusResult){ + if(result==6){ + return FIRST_PRIZE; + } + if(result==5&&bonusResult==1){ + return SECOND_PRIZE; + } + if(result==5&&bonusResult==0){ + return THIRD_PRIZE; + } + if(result==4){ + return FOURTH_PRIZE; + } + if(result==3){ + return FIFTH_PRIZE; + } + if(result<3){ + return LOOSE; + } + throw new IllegalArgumentException("존재 하지 않는 순위입니다."); + } +}
Java
set을 이용하지 않는 방법도 있었네요.
@@ -0,0 +1,79 @@ +package lotto.model; + +import lotto.model.constants.LottoPrize; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +import static lotto.constants.ErrorMessage.DUPLICATION; +import static lotto.constants.ErrorMessage.SIXNUMBER; +import static lotto.model.constants.LottoPrize.*; +public class Lotto { + private final List<Integer> numbers; + + public Lotto(List<Integer> numbers) { + validate(numbers); + duplicate(numbers); + this.numbers = numbers; + } + + private void duplicate(List<Integer> numbers) { + List<Integer> duplication = numbers.stream() + .distinct() + .toList(); + if (duplication.size() != numbers.size()) { + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(SIXNUMBER.getMessage()); + } + } + public void checkSame(Integer bonusNumber, List<List<Integer>> lottoNumber) { + bonusDuplication(bonusNumber); + for (List<Integer> integers : lottoNumber) { + List<Integer> Result = integers.stream() + .filter(i -> this.numbers.stream().anyMatch(Predicate.isEqual(i))) + .toList(); + long bonusResult = integers.stream() + .filter(bonusNumber::equals).count(); + CheckPrize(Result.size(), bonusResult).addWinCount(); + + } + } + + private void bonusDuplication(Integer bonusNumber) { + List<Integer> Result = this.numbers.stream() + .filter(i-> !Objects.equals(i, bonusNumber)) + .toList(); + if(Result.size()!=6){ + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + + } + + public LottoPrize CheckPrize(int result, long bonusResult){ + if(result==6){ + return FIRST_PRIZE; + } + if(result==5&&bonusResult==1){ + return SECOND_PRIZE; + } + if(result==5&&bonusResult==0){ + return THIRD_PRIZE; + } + if(result==4){ + return FOURTH_PRIZE; + } + if(result==3){ + return FIFTH_PRIZE; + } + if(result<3){ + return LOOSE; + } + throw new IllegalArgumentException("존재 하지 않는 순위입니다."); + } +}
Java
해당 부분을 LottoPrize에서 해주면 lotto의 역할을 줄일 수 있을 것이라고 생각하는데 어떠신가요? stream을 이용해서 filter를 하면 조금 더 깔끔해 질 것 같아요.
@@ -0,0 +1,67 @@ +package lotto.model; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.controller.LottoController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static lotto.constants.ErrorMessage.ISNOTINTEGER; +import static lotto.constants.ErrorMessage.NOTTHOUSAND; + +public class LottoNumberMaker { + private static int buyPrice; + private static final List<List<Integer>> numbers = new ArrayList<>(); + private static final LottoController lottoController = new LottoController(); + + public static int getBuyPrice() { + return buyPrice; + } + + public void makeLottoNumber(Integer count) { + buyPrice = count; + checkThousand(count); + IntStream.range(0, count / 1000) + .forEach(i -> numbers.add(makeRandomNumber())); + } + + private void checkThousand(Integer count) { + if(count%1000!=0){ + throw new IllegalArgumentException(NOTTHOUSAND.getMessage()); + } + return; + } + + private List<Integer> makeRandomNumber() { + return Randoms.pickUniqueNumbersInRange(1, 45, 6).stream() + .sorted() + .collect(Collectors.toList()); + } + + public void checkInt() { + while (true) { + try { + int number = checkCount(); + makeLottoNumber(number); + break; + } catch (IllegalArgumentException e) { + System.out.println(ISNOTINTEGER.getMessage()); + System.out.println(NOTTHOUSAND.getMessage()); + } + } + } + + private int checkCount() { + try { + return Integer.parseInt(lottoController.askPrice()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ISNOTINTEGER.getMessage()); + } + } + + public List<List<Integer>> getLottoNumber() { + return numbers; + } +}
Java
매직 넘버 해주시면 더 좋을 것 같습니다.
@@ -0,0 +1,62 @@ +package lotto.view; + +import camp.nextstep.edu.missionutils.Console; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static lotto.constants.ErrorMessage.*; +import static lotto.view.ConstantsMessage.*; + +public class LottoInput { + public String askPrice() { + System.out.println(ASK_BUY_PRICE.getMessage()); + String input = Console.readLine(); + return input; + + } + + public List<Integer> prizeNumberInput() { + while (true) { + try { + printNewLine(); + System.out.println(ASK_PRIZE_NUMBER.getMessage()); + return changeInt(Arrays.asList(Console.readLine().split(","))); + }catch (IllegalArgumentException e){ + System.out.println(OUTFRANGE.getMessage()); + } + } + } + public Integer bonusNumberInput() { + try{ + printNewLine(); + System.out.println(ASK_BONUS_NUMBER.getMessage()); + String input = Console.readLine(); + + return Integer.parseInt(input); + }catch (NumberFormatException e){ + throw new IllegalArgumentException(ONENUMBER.getMessage()); + } + + } + private List<Integer> changeInt(List<String> prizeNumbers) { + try{ + List<Integer> numbers = prizeNumbers.stream() + .map(Integer::parseInt) + .filter(i->i>0&&i<45) + .toList(); + if(numbers.size() != prizeNumbers.size()){ + throw new NumberFormatException(); + } + return numbers; + }catch (NumberFormatException e){ + throw new IllegalArgumentException(OUTFRANGE.getMessage()); + } + + } + + private void printNewLine() { + System.out.println(); + } +}
Java
메시지 앞에 %n를 이용해서 printf를 이용한다면 printNewLine 코드를 안써도 될 것 같은데 이 부분에 대해서 어떻게 생각하시는지 궁금합니다.
@@ -0,0 +1,21 @@ +package lotto.constants; + +public enum ErrorMessage { + DUPLICATION("[ERROR] 값이 중복되었습니다"), + ISNOTINTEGER("[ERROR] 숫자를 입력해주세요"), + SIXNUMBER("[ERROR] 번호 6개를 입력해주세요"), + OUTFRANGE("[ERROR] 로또 번호는 1부터 45 사이의 숫자여야 합니다."), + ONENUMBER("[ERROR] 숫자 번호 1개를 입력해주세요"), + NOTTHOUSAND("[ERROR] 1000원 단위로 입력해 주세요"); + + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
constants 패키지가 두개가 존재하는데 이름을 달리해서 구분하는게 조금 더 가독성에는 좋을 것 같습니다.
@@ -0,0 +1,34 @@ +# 로또 + +## 기능 목록 +- [V] 랜덤 하게 생성한 로또 번호와 사용자가 임의로 선정한 당첨 번호를 비교하여 + 당첨된 등수와 수익률을 계산한다. + - [V] 사용자로부터 로또 구입 금액을 입력 받는다. + - [V] 입력 받은 금액에 따라 랜덤하게 6개의 숫자를 생성하여 로또 번호를 생성한다.(1~45범위, 중복X, 오름차순 정렬) + - [V] 사용자로부터 당첨 번호와 보너스 번호를 입력 받은 후, 생성한 로또 번호와 비교하여 등수를 출력한다. + - [V] 수익률을 계산하여 출력한다.(소수점 둘떄 자리 반올림) + -[]입력값 예외처리 + -[V]로또 번호 중복 예외처리 + -[V]로또 번호 범위 벗어남 예외처리 + -[] 보너스 번호 예외처리 +## 기능 요구 사항 +- 로또 번호의 숫자 범위는 1~45까지이다. +- 1개의 로또를 발행할 때 중복되지 않는 6개의 숫자를 뽑는다. +- 당첨 번호 추첨 시 중복되지 않는 숫자 6개와 보너스 번호 1개를 뽑는다. +- 당첨은 1등부터 5등까지 있다. 당첨 기준과 금액은 아래와 같다. + - 1등: 6개 번호 일치 / 2,000,000,000원 + - 2등: 5개 번호 + 보너스 번호 일치 / 30,000,000원 + - 3등: 5개 번호 일치 / 1,500,000원 + - 4등: 4개 번호 일치 / 50,000원 + - 5등: 3개 번호 일치 / 5,000원 + +### 추가된 요구 사항 +-[V] 함수(또는 메서드)의 길이가 15라인을 넘어가지 않도록 구현한다. +- 함수(또는 메서드)가 한 가지 일만 잘 하도록 구현한다. +-[V] else 예약어를 쓰지 않는다. +- 힌트: if 조건절에서 값을 return하는 방식으로 구현하면 else를 사용하지 않아도 된다. +- else를 쓰지 말라고 하니 switch/case로 구현하는 경우가 있는데 switch/case도 허용하지 않는다. +-[V] Java Enum을 적용한다. +-[] 도메인 로직에 단위 테스트를 구현해야 한다. 단, UI(System.out, System.in, Scanner) 로직은 제외한다. + - 핵심 로직을 구현하는 코드와 UI를 담당하는 로직을 분리해 구현한다. + - 단위 테스트 작성이 익숙하지 않다면 `test/java/lotto/LottoTest`를 참고하여 학습한 후 테스트를 구현한다. \ No newline at end of file
Unknown
완료된 부분 체크하여 리드미도 꼼꼼하게 관리해주시는 것이 좋을 것 같습니다~
@@ -0,0 +1,50 @@ +package lotto.controller; + +import lotto.model.Lotto; +import lotto.model.LottoNumberMaker; +import lotto.model.LottoPercentageCalculation; +import lotto.model.constants.LottoPrize; +import lotto.view.LottoInput; +import lotto.view.LottoOutput; + +import java.util.ArrayList; +import java.util.List; + +import static java.util.Arrays.asList; +import static lotto.model.constants.LottoPrize.*; + +public class LottoController { + private static final LottoNumberMaker lottoNumberMaker = new LottoNumberMaker(); + private static final LottoInput lottoInput = new LottoInput(); + private static final LottoOutput lottoOutput = new LottoOutput(); + private static final LottoPercentageCalculation lottoPercentageCalculation = new LottoPercentageCalculation(); + public static void setPrice() { + lottoNumberMaker.checkInt(); + } + +// static List<LottoPrize> LottoPrizelist= asList(FIFTH_PRIZE,FOURTH_PRIZE,THIRD_PRIZE,SECOND_PRIZE,FIRST_PRIZE); + public static void setBuyLottoNumberPrint() { + lottoOutput.buyLottoNumberPrint(lottoNumberMaker.getLottoNumber()); + } + + public static void setPrizeNumberInput() { + Lotto lotto = new Lotto(lottoInput.prizeNumberInput()); + lotto.checkSame(lottoInput.bonusNumberInput(),lottoNumberMaker.getLottoNumber()); + } + + public static void winningStatistic() { + List<String> lottoPrizes = new ArrayList<>(); + for(LottoPrize lottoPrize: LottoPrize.values()){ + lottoPrizes.add(lottoPrize.getText()+lottoPrize.getWinCount()+lottoPrize.getUnit()); + } + LottoOutput.seeWinningStatstic(lottoPrizes); + } + + public static void PerformanceCalculation() { + lottoOutput.seePercentage(lottoPercentageCalculation.percentageCalculation(LottoPrize.values(),lottoNumberMaker.getBuyPrice())); + } + + public String askPrice() { + return lottoInput.askPrice(); + } +} \ No newline at end of file
Java
set이라는 메서드명은 Setter의 느낌이 강한데 혹시 다른 변수명을 고려해보시는건 어떠실까요?
@@ -0,0 +1,79 @@ +package lotto.model; + +import lotto.model.constants.LottoPrize; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +import static lotto.constants.ErrorMessage.DUPLICATION; +import static lotto.constants.ErrorMessage.SIXNUMBER; +import static lotto.model.constants.LottoPrize.*; +public class Lotto { + private final List<Integer> numbers; + + public Lotto(List<Integer> numbers) { + validate(numbers); + duplicate(numbers); + this.numbers = numbers; + } + + private void duplicate(List<Integer> numbers) { + List<Integer> duplication = numbers.stream() + .distinct() + .toList(); + if (duplication.size() != numbers.size()) { + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(SIXNUMBER.getMessage()); + } + } + public void checkSame(Integer bonusNumber, List<List<Integer>> lottoNumber) { + bonusDuplication(bonusNumber); + for (List<Integer> integers : lottoNumber) { + List<Integer> Result = integers.stream() + .filter(i -> this.numbers.stream().anyMatch(Predicate.isEqual(i))) + .toList(); + long bonusResult = integers.stream() + .filter(bonusNumber::equals).count(); + CheckPrize(Result.size(), bonusResult).addWinCount(); + + } + } + + private void bonusDuplication(Integer bonusNumber) { + List<Integer> Result = this.numbers.stream() + .filter(i-> !Objects.equals(i, bonusNumber)) + .toList(); + if(Result.size()!=6){ + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + + } + + public LottoPrize CheckPrize(int result, long bonusResult){ + if(result==6){ + return FIRST_PRIZE; + } + if(result==5&&bonusResult==1){ + return SECOND_PRIZE; + } + if(result==5&&bonusResult==0){ + return THIRD_PRIZE; + } + if(result==4){ + return FOURTH_PRIZE; + } + if(result==3){ + return FIFTH_PRIZE; + } + if(result<3){ + return LOOSE; + } + throw new IllegalArgumentException("존재 하지 않는 순위입니다."); + } +}
Java
저도 놓친 부분이긴한데 매직넘버 처리해주시는게 좋을듯 합니다!
@@ -0,0 +1,79 @@ +package lotto.model; + +import lotto.model.constants.LottoPrize; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +import static lotto.constants.ErrorMessage.DUPLICATION; +import static lotto.constants.ErrorMessage.SIXNUMBER; +import static lotto.model.constants.LottoPrize.*; +public class Lotto { + private final List<Integer> numbers; + + public Lotto(List<Integer> numbers) { + validate(numbers); + duplicate(numbers); + this.numbers = numbers; + } + + private void duplicate(List<Integer> numbers) { + List<Integer> duplication = numbers.stream() + .distinct() + .toList(); + if (duplication.size() != numbers.size()) { + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(SIXNUMBER.getMessage()); + } + } + public void checkSame(Integer bonusNumber, List<List<Integer>> lottoNumber) { + bonusDuplication(bonusNumber); + for (List<Integer> integers : lottoNumber) { + List<Integer> Result = integers.stream() + .filter(i -> this.numbers.stream().anyMatch(Predicate.isEqual(i))) + .toList(); + long bonusResult = integers.stream() + .filter(bonusNumber::equals).count(); + CheckPrize(Result.size(), bonusResult).addWinCount(); + + } + } + + private void bonusDuplication(Integer bonusNumber) { + List<Integer> Result = this.numbers.stream() + .filter(i-> !Objects.equals(i, bonusNumber)) + .toList(); + if(Result.size()!=6){ + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + + } + + public LottoPrize CheckPrize(int result, long bonusResult){ + if(result==6){ + return FIRST_PRIZE; + } + if(result==5&&bonusResult==1){ + return SECOND_PRIZE; + } + if(result==5&&bonusResult==0){ + return THIRD_PRIZE; + } + if(result==4){ + return FOURTH_PRIZE; + } + if(result==3){ + return FIFTH_PRIZE; + } + if(result<3){ + return LOOSE; + } + throw new IllegalArgumentException("존재 하지 않는 순위입니다."); + } +}
Java
```suggestion .filter(i -> this.numbers .stream() .anyMatch(Predicate.isEqual(i))) ``` 다음과 같이 개행처리 해주시는게 가독성에 좋아보입니다!
@@ -0,0 +1,79 @@ +package lotto.model; + +import lotto.model.constants.LottoPrize; + +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; + +import static lotto.constants.ErrorMessage.DUPLICATION; +import static lotto.constants.ErrorMessage.SIXNUMBER; +import static lotto.model.constants.LottoPrize.*; +public class Lotto { + private final List<Integer> numbers; + + public Lotto(List<Integer> numbers) { + validate(numbers); + duplicate(numbers); + this.numbers = numbers; + } + + private void duplicate(List<Integer> numbers) { + List<Integer> duplication = numbers.stream() + .distinct() + .toList(); + if (duplication.size() != numbers.size()) { + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 6) { + throw new IllegalArgumentException(SIXNUMBER.getMessage()); + } + } + public void checkSame(Integer bonusNumber, List<List<Integer>> lottoNumber) { + bonusDuplication(bonusNumber); + for (List<Integer> integers : lottoNumber) { + List<Integer> Result = integers.stream() + .filter(i -> this.numbers.stream().anyMatch(Predicate.isEqual(i))) + .toList(); + long bonusResult = integers.stream() + .filter(bonusNumber::equals).count(); + CheckPrize(Result.size(), bonusResult).addWinCount(); + + } + } + + private void bonusDuplication(Integer bonusNumber) { + List<Integer> Result = this.numbers.stream() + .filter(i-> !Objects.equals(i, bonusNumber)) + .toList(); + if(Result.size()!=6){ + throw new IllegalArgumentException(DUPLICATION.getMessage()); + } + + } + + public LottoPrize CheckPrize(int result, long bonusResult){ + if(result==6){ + return FIRST_PRIZE; + } + if(result==5&&bonusResult==1){ + return SECOND_PRIZE; + } + if(result==5&&bonusResult==0){ + return THIRD_PRIZE; + } + if(result==4){ + return FOURTH_PRIZE; + } + if(result==3){ + return FIFTH_PRIZE; + } + if(result<3){ + return LOOSE; + } + throw new IllegalArgumentException("존재 하지 않는 순위입니다."); + } +}
Java
매직넘버 처리를 해주셔야 할것 같아요!
@@ -0,0 +1,67 @@ +package lotto.model; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.controller.LottoController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static lotto.constants.ErrorMessage.ISNOTINTEGER; +import static lotto.constants.ErrorMessage.NOTTHOUSAND; + +public class LottoNumberMaker { + private static int buyPrice; + private static final List<List<Integer>> numbers = new ArrayList<>(); + private static final LottoController lottoController = new LottoController(); + + public static int getBuyPrice() { + return buyPrice; + } + + public void makeLottoNumber(Integer count) { + buyPrice = count; + checkThousand(count); + IntStream.range(0, count / 1000) + .forEach(i -> numbers.add(makeRandomNumber())); + } + + private void checkThousand(Integer count) { + if(count%1000!=0){ + throw new IllegalArgumentException(NOTTHOUSAND.getMessage()); + } + return; + } + + private List<Integer> makeRandomNumber() { + return Randoms.pickUniqueNumbersInRange(1, 45, 6).stream() + .sorted() + .collect(Collectors.toList()); + } + + public void checkInt() { + while (true) { + try { + int number = checkCount(); + makeLottoNumber(number); + break; + } catch (IllegalArgumentException e) { + System.out.println(ISNOTINTEGER.getMessage()); + System.out.println(NOTTHOUSAND.getMessage()); + } + } + } + + private int checkCount() { + try { + return Integer.parseInt(lottoController.askPrice()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ISNOTINTEGER.getMessage()); + } + } + + public List<List<Integer>> getLottoNumber() { + return numbers; + } +}
Java
이부분만 따로 전역 메서드로 선언하신 이유가 있으실까요???
@@ -0,0 +1,67 @@ +package lotto.model; + +import camp.nextstep.edu.missionutils.Randoms; +import lotto.controller.LottoController; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static lotto.constants.ErrorMessage.ISNOTINTEGER; +import static lotto.constants.ErrorMessage.NOTTHOUSAND; + +public class LottoNumberMaker { + private static int buyPrice; + private static final List<List<Integer>> numbers = new ArrayList<>(); + private static final LottoController lottoController = new LottoController(); + + public static int getBuyPrice() { + return buyPrice; + } + + public void makeLottoNumber(Integer count) { + buyPrice = count; + checkThousand(count); + IntStream.range(0, count / 1000) + .forEach(i -> numbers.add(makeRandomNumber())); + } + + private void checkThousand(Integer count) { + if(count%1000!=0){ + throw new IllegalArgumentException(NOTTHOUSAND.getMessage()); + } + return; + } + + private List<Integer> makeRandomNumber() { + return Randoms.pickUniqueNumbersInRange(1, 45, 6).stream() + .sorted() + .collect(Collectors.toList()); + } + + public void checkInt() { + while (true) { + try { + int number = checkCount(); + makeLottoNumber(number); + break; + } catch (IllegalArgumentException e) { + System.out.println(ISNOTINTEGER.getMessage()); + System.out.println(NOTTHOUSAND.getMessage()); + } + } + } + + private int checkCount() { + try { + return Integer.parseInt(lottoController.askPrice()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ISNOTINTEGER.getMessage()); + } + } + + public List<List<Integer>> getLottoNumber() { + return numbers; + } +}
Java
해당 클래스가 너무 많은 책임을 가지고 있는것 같습니다. 구매금액을 검증하는 부분과 로또 번호를 검증하는 부분을 분리하는 것도 좋은 방법일거 같습니다.
@@ -0,0 +1,39 @@ +package lotto.model.constants; + +public enum LottoPrize { + FIRST_PRIZE(0,"6개 일치 (2,000,000,000원) - ","개",2000000000), + SECOND_PRIZE(0,"5개 일치, 보너스 볼 일치 (30,000,000원) - ","개", 30000000), + THIRD_PRIZE(0,"5개 일치 (1,500,000원) - ","개", 1500000), + FOURTH_PRIZE(0,"4개 일치 (50,000원) - ","개", 50000), + FIFTH_PRIZE(0,"3개 일치 (5,000원) - ","개", 5000), + LOOSE(0,"","개", 0); + + + private int winCount; + private final String text; + private final String unit; + private int prizeMoney; + + LottoPrize(int winCount, String text, String unit, int prizemoney) { + this.winCount = winCount; + this.text = text; + this.unit = unit; + this.prizeMoney = prizemoney; + } + public int getWinCount() { + return winCount; + } + public String getText() { + return text; + } + public String getUnit() { + return unit; + } + public int getPrizeMoney() { + return prizeMoney; + } + + public void addWinCount() { + this.winCount ++; + } +}
Java
출력 형식과 관련된 부분은 view에서 처리해야할거 같은데 이에 대해서 어떻게 생각하시나요?
@@ -0,0 +1,100 @@ +# Domain 구현 + +## 진행 프로세스 (시스템 책임) + +1. 게이머는 상대할 보스 몬스터의 HP를 설정한다. +2. 게이머는 플레이할 플레이어의 이름과 HP, MP를 설정한다. +3. 게임이 시작된다. +4. 게임은 턴제이며, 매 턴마다 다음과 같은 행동이 반복된다. + 1) 보스 몬스터와 플레이어의 현재 상태를 보여준다. + 2) 플레이어가 공격할 방식을 선택한다. + 3) 플레이어가 선택된 방식으로 공격한다. (보스 몬스터에게 데미지를 입힘) + 4) 데미지를 입은 보스 몬스터의 상태를 확인한다. + 5) 보스 몬스터가 죽었다면 게임이 종료된다. + 6) 보스 몬스터가 살아있다면 플레이어를 공격한다. + 7) 데미지를 입은 플레이어의 상태를 확인한다. + 8) 플레이어가 죽었다면 게임이 종료된다. +5. 게임 종료 후 승자를 안내한다. + - 플레이어가 이겼을 경우 : 진행한 턴 수를 알려준다. + - 보스 몬스터가 이겼을 경우 : 플레이어와 보스 몬스터의 현재 상태를 보여준다. + +## Domain 객체 선정 및 책임과 협력 할당 + +1. **Raid Game** + - 게임 시작 전 주요 인물에 대해 셋팅할 책임을 가짐 + - 게임 인물인 **Boss Monster**를 생성할 책임을 가짐 + - 게임 인물인 **Player**를 생성할 책임을 가짐 + - 매 턴을 실행할 책임을 가짐 + - 게임 상태를 확인할 책임을 가짐 (게임 상태가 '종료'일 경우 턴을 실행하지 않음) + - 턴 수를 증가시킬 책임을 가짐 + - **Player**가 **Boss Monster**를 선택된 공격 방식으로 공격하도록 할 책임을 가짐 + - **Player**의 공격 행동에 대한 결과를 제공받고, **Boss Monster**에게 전달할 책임을 가짐 (**Player**의 공격과 **Boss Monster**의 피해 행동에 대한 협력 필요) + - **Boss Monster**의 생존여부에 따라 게임 상태를 변경할 책임을 가짐 (**Boss Monster**의 상태를 제공받는 협력 필요) + - **Boss Monster**가 **Player**를 공격하도록 할 책임을 가짐 (**Boss Monster**의 공격과 **Player**의 피해 행동에 대한 협력 필요) + - **Boss Monster**의 공격 행동에 대한 결과를 제공받고, **Player**에게 전달할 책임을 가짐 (**Boss Monster**의 공격과 **Player**의 피해 행동에 대한 협력 필요) + - **Player**의 생존여부에 따라 게임 상태를 변경할 책임을 가짐 (**Player**의 상태를 제공받는 협력 필요) + - 해당 턴에 대한 게임 기록을 생성할 책임을 가짐 (**GameHistory**에게 턴에 대한 기록을 생성하는 협력 필요) + +2. **Boss Monster** + - 현재 상태를 제공해줄 책임을 가짐 (총 HP, 현재 HP) + - 공격 명령을 수행할 책임을 가짐 (0~20의 랜덤 데미지) + - 공격 피해 입음을 수행할 책임을 가짐 (현재 HP 감소) + +3. **Player** + - 현재 상태를 제공해줄 책임을 가짐 (이름, 총 HP, 현재 HP, 총 MP, 현재 MP) + - 공격 명령을 수행할 책임을 가짐 (**Attack Type**에 대한 정보를 제공받는 협력 필요, MP 감소) + - 공격 피해 입음을 수행할 책임을 가짐 (현재 HP 감소) + +4. **Attack Type** + - 공격 방식 종류를 제공해줄 책임을 가짐 (공격 변호, 공격 방식 이름) + - 공격 방식 수행에 대한 정보를 제공해줄 책임을 가짐 (데미지, MP 소모량, MP 회복량) + +5. **Game History** + - 매 턴에 대한 기록을 저장할 책임을 가짐 + - 추후 Controller의 Veiw를 위한 요청에 응답 가능 + +## 주요 메시지 구성 (공용 인터페이스) + +1. 보스 몬스터 설정을 요청 + - 수신자 : Raid Game + - 이름 : Create Boss Monster + - 인자 : int hp + - 응답 : void, Boss Monster 객체 생성 + +2. 플레이어 설정을 요청 + - 수신자 : Raid Game + - 이름 : Create Player + - 인자 : String name, int hp, int mp + - 응답 : void, Player 객체 생성 + +3. 턴 진행을 요청 + - 수신자 : Raid Game + - 이름 : Start Game + - 인자 : - + - 응답 : 구성된 턴 로직 실행 + +4. 게임 상태 확인을 요청 + - 수신자 : Raid Game + - 이름 : Check Game Status + - 인자 : - + - 응답 : return Game Status (true or False) + +5. 턴 횟수 증가를 요청 + - 수신자 : Raid Game + - 이름 : Increase Turns + - 인자 : - + - 응답 : void, Turn 1 증가 + +6. 공격 행동 수행을 요청 + - 수신자 : Player, Boss Monster + - 이름 : Attack + - 인자 : - + - 응답 : return 데미지, 공격 방식에 따라 MP 감소(Player) + +7. 공격 피해 전달을 요청 + - 수신자 : Player, Boss Monster + - 이름 : take Damage + - 인자 : int damage + - 응답 : return 현재 HP + +
Unknown
요청 사항을 굉장히 깔끔하게 적어주신 것 같아요! 하지만 우려되는 점도 있는데요. 정성스레 작성해주신 문서지만 동료 입장에서는 함수 이름이나 인자 등을 글로 표현하는 것보다 함수 형태를 보여주는 것이 가독성이 더 좋을 수도 있겠다는 생각을 했어요! 책들도 보면 글보다는 코드로 먼저 보여주잖아요:) ```java public void start() { // 게임 시작 로직 } ``` 이런 느낌으로요! 어떻게 생각하시나요?
@@ -0,0 +1,17 @@ +package bossmonster.exception; + +import bossmonster.view.OutputView; +import java.util.function.Supplier; + +public class ExceptionHandler { + + public static <T> T retryInput(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (Exception exception) { + OutputView.printError(exception); + } + } + } +}
Java
이렇게 만들 생각을 하진 못했는데, 제네릭을 정말 잘 활용하신 것 같아요! 하지만 함수명에서 오해의 소지가 있다고 생각해요. 첫 시도를 할 때도 해당 함수를 사용하기 때문인데요. 오류가 나지 않을때까지 계속 재입력 받는 것이기 때문에 다른 네이밍이 어울릴 것 같아요! 음... 마땅히 떠오르는 네이밍은 없네요ㅠㅠ
@@ -0,0 +1,17 @@ +package bossmonster.exception; + +import bossmonster.view.OutputView; +import java.util.function.Supplier; + +public class ExceptionHandler { + + public static <T> T retryInput(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (Exception exception) { + OutputView.printError(exception); + } + } + } +}
Java
추가적으로 클래스명이 어울리지 않는듯한 느낌을 받았어요. 스프링을 생각해서 네이밍을 정하신 것 같아서 스프링의 ExceptionHandler와 비교해서 말씀드리겠습니다! `ExceptionHandler`의 경우 말 그대로 예외를 핸들링해주는 역할입니다. A라는 예외가 발생하면 ExceptionHandler가 그에 맞게 처리해주고, B라는 예외가 발생하면 그것도 그것의 ExceptionHandler에 맞게 처리해주는 역할이죠. 스프링의 ExceptionHandler처럼 예외를 핸들링하는 그 자체에만 목적이 있어야한다고 생각해요. 하지만 작성하신 코드에서는 예외가 발생했을 때 이벤트가 예외를 감지해 예외를 핸들링하는 것이 아니라, 마치 예외가 발생할법한 함수들을 대신 실행해주는 역할같아요. 넵, 그저 함수형 인터페이스죠. 그렇다면 이것에 맞는 네이밍으로 하는 것이 좋지 않을까요? 만약 `ExceptionHandler`를 사용하고 싶으면 아래와 같이 되어야할 것 같습니다. ```java public static T handle(Exception e) { // 핸들링 } ```
@@ -0,0 +1,78 @@ +package bossmonster.exception; + +import bossmonster.view.constants.Message; + +public class Validator { + + public static String validateInputOfNumber(String inputValue) { + validateEmpty(inputValue); + validateInteger(inputValue); + return inputValue; + } + + public static String validatePlayerName(String inputValue) { + validateEmpty(inputValue); + validateRangeOfPlayerName(inputValue); + return inputValue; + } + + public static String[] validateInputOfNumbers(String inputValue) { + validateSeparated(inputValue); + String[] separatedValue = inputValue.split(","); + validateArray(separatedValue); + for (String value : separatedValue) { + validateEmpty(value); + validateInteger(value); + } + return separatedValue; + } + + public static int validateBossMonster(int hp) { + return validateRangeOfMonster(hp); + } + + public static void validatePlayerStatus(int hp, int mp) { + if (hp + mp != 200) { + throw new IllegalArgumentException(Message.ERROR_PLAYER_STATUS.getErrorMessage()); + } + } + + private static void validateEmpty(String inputValue) { + if (inputValue.isEmpty()) { + throw new IllegalArgumentException(Message.ERROR_EMPTY.getErrorMessage()); + } + } + + private static void validateInteger(String inputValue) { + try { + Integer.parseInt(inputValue); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(Message.ERROR_NOT_INTEGER.getErrorMessage()); + } + } + + private static void validateSeparated(String inputValue) { + if (!inputValue.contains(",")) { + throw new IllegalArgumentException(Message.ERROR_NOT_COMMA.getErrorMessage()); + } + } + + private static void validateArray(String[] inputValue) { + if (inputValue.length != 2) { + throw new IllegalArgumentException(Message.ERROR_ARRAY_SIZE.getErrorMessage()); + } + } + + private static int validateRangeOfMonster(int hp) { + if (hp < 100 || hp > 300) { + throw new IllegalArgumentException(Message.ERROR_BOSS_MONSTER_HP.getErrorMessage()); + } + return hp; + } + + private static void validateRangeOfPlayerName(String name) { + if (name.length() > 5) { + throw new IllegalArgumentException(Message.ERROR_PLAYER_NAME.getErrorMessage()); + } + } +}
Java
해당 클래스를 exception 패키지에 넣으신 이유가 궁금합니다! hp + mp는 200이어야한다 등... 비즈니스 로직이 담긴 부분이 있는데 domain 패키지와 분리되어 있어서요!
@@ -0,0 +1,61 @@ +package bossmonster.domain; + +import bossmonster.exception.Validator; + +public class Player { + + private String name; + private PlayerStatus status; + + public Player(String name, int maxHP, int maxMP) { + this.name = Validator.validatePlayerName(name); + Validator.validatePlayerStatus(maxHP, maxMP); + this.status = new PlayerStatus(maxHP, maxMP); + } + + public String getName() { + return name; + } + + public boolean isAlive() { + return status.isAlive(); + } + + public int getMaxHP() { + return status.getMaxHP(); + } + + public int getCurrentHP() { + return status.getCurrentHP(); + } + + public int getMaxMP() { + return status.getMaxMP(); + } + + public int getCurrentMP() { + return status.getCurrentMP(); + } + + public int attack(AttackType attackType) { + if (attackType.getName().equals(AttackType.ATTACK_TYPE_NORMAL.getName())) { + recoverMP(attackType.getMpRecover()); + } + if (attackType.getName().equals(AttackType.ATTACK_TYPE_MAGIC.getName())) { + consumeMP(attackType.getMpUsage()); + } + return attackType.getDamage(); + } + + public void takeDamage(int damage) { + status.setCurrentHP(status.getCurrentHP() - damage); + } + + private void recoverMP(int mp) { + status.setCurrentMP(status.getCurrentMP() + mp); + } + + private void consumeMP(int mp) { + status.setCurrentMP(status.getCurrentMP() - mp); + } +}
Java
controller에서 Validator를 사용할 때도 있고, domain에서 사용할 때도 있군요. 어떤 기준으로 분리하셨는지 궁금합니다!
@@ -0,0 +1,70 @@ +package bossmonster.domain; + +import bossmonster.domain.dto.GameHistoryDto; +import java.util.ArrayList; +import java.util.List; + +public class GameHistory { + + private class Turns { + + private int turnCount; + private String playerName; + private String playerAttackType; + private int playerAttackDamage; + private int monsterAttackDamage; + private int playerMaxHP; + private int playerCurrentHP; + private int playerMaxMP; + private int playerCurrentMP; + private int monsterMaxHP; + private int monsterCurrentHP; + private boolean gameStatus; + + public Turns(int turnCount, String playerAttackType, int playerAttackDamage, + int monsterAttackDamage, boolean gameStatus, Player player, BossMonster bossMonster) { + this.turnCount = turnCount; + this.playerName = player.getName(); + this.playerAttackType = playerAttackType; + this.playerAttackDamage = playerAttackDamage; + this.monsterAttackDamage = monsterAttackDamage; + this.playerMaxHP = player.getMaxHP(); + this.playerCurrentHP = player.getCurrentHP(); + this.playerMaxMP = player.getMaxMP(); + this.playerCurrentMP = player.getCurrentMP(); + this.monsterMaxHP = bossMonster.getMaxHP(); + this.monsterCurrentHP = bossMonster.getCurrentHP(); + this.gameStatus = gameStatus; + } + } + + private static final String DEFAULT_ATTACK_TYPE = ""; + private static final int DEFAULT_DAMAGE = 0; + private int recentRecord; + private List<Turns> raidHistory = new ArrayList<>(); + + public void addHistory(int turnCount, boolean gameStatus, Player player, BossMonster bossMonster) { + raidHistory.add( + new Turns(turnCount, DEFAULT_ATTACK_TYPE, DEFAULT_DAMAGE, DEFAULT_DAMAGE, gameStatus, player, + bossMonster)); + } + + public void addHistory(int turnCount, String playerAttackType, int playerAttackDamage, + int monsterAttackDamage, boolean gameStatus, Player player, BossMonster bossMonster) { + raidHistory.add( + new Turns(turnCount, playerAttackType, playerAttackDamage, monsterAttackDamage, gameStatus, player, + bossMonster)); + } + + public GameHistoryDto requestRaidHistory() { + setRecentRecord(); + Turns turns = raidHistory.get(recentRecord); + return new GameHistoryDto(turns.turnCount, turns.playerName, turns.playerAttackType, turns.playerAttackDamage, + turns.monsterAttackDamage, turns.playerMaxHP, turns.playerCurrentHP, turns.playerMaxMP, + turns.playerCurrentMP, turns.monsterMaxHP, turns.monsterCurrentHP, turns.gameStatus); + } + + private void setRecentRecord() { + recentRecord = raidHistory.size() - 1; + } +}
Java
해당 객체를 만드신 목적이 궁금합니다!
@@ -0,0 +1,82 @@ +package bossmonster.domain.dto; + +public class GameHistoryDto { + + private int turnCount; + private String playerName; + private String playerAttackType; + private int playerAttackDamage; + private int monsterAttackDamage; + private int playerMaxHP; + private int playerCurrentHP; + private int playerMaxMP; + private int playerCurrentMP; + private int monsterMaxHP; + private int monsterCurrentHP; + private boolean gameStatus; + + public GameHistoryDto(int turnCount, String playerName, String playerAttackType, int playerAttackDamage, + int monsterAttackDamage, int playerMaxHP, int playerCurrentHP, int playerMaxMP, + int playerCurrentMP, int monsterMaxHP, int monsterCurrentHP, boolean gameStatus) { + this.turnCount = turnCount; + this.playerName = playerName; + this.playerAttackType = playerAttackType; + this.playerAttackDamage = playerAttackDamage; + this.monsterAttackDamage = monsterAttackDamage; + this.playerMaxHP = playerMaxHP; + this.playerCurrentHP = playerCurrentHP; + this.playerMaxMP = playerMaxMP; + this.playerCurrentMP = playerCurrentMP; + this.monsterMaxHP = monsterMaxHP; + this.monsterCurrentHP = monsterCurrentHP; + this.gameStatus = gameStatus; + } + + public int getTurnCount() { + return turnCount; + } + + public String getPlayerName() { + return playerName; + } + + public String getPlayerAttackType() { + return playerAttackType; + } + + public int getPlayerAttackDamage() { + return playerAttackDamage; + } + + public int getMonsterAttackDamage() { + return monsterAttackDamage; + } + + public int getPlayerMaxHP() { + return playerMaxHP; + } + + public int getPlayerCurrentHP() { + return playerCurrentHP; + } + + public int getPlayerMaxMP() { + return playerMaxMP; + } + + public int getPlayerCurrentMP() { + return playerCurrentMP; + } + + public int getMonsterMaxHP() { + return monsterMaxHP; + } + + public int getMonsterCurrentHP() { + return monsterCurrentHP; + } + + public boolean isGameStatus() { + return gameStatus; + } +}
Java
`isFinish()`나 `isPlaying()`와 같은 것은 어떨까요?
@@ -0,0 +1,119 @@ +package bossmonster.controller; + +import bossmonster.domain.AttackType; +import bossmonster.domain.BossMonster; +import bossmonster.domain.Player; +import bossmonster.domain.RaidGame; +import bossmonster.domain.dto.GameHistoryDto; +import bossmonster.exception.ExceptionHandler; +import bossmonster.exception.ManaShortageException; +import bossmonster.exception.Validator; +import bossmonster.view.InputView; +import bossmonster.view.OutputView; +import bossmonster.view.constants.Message; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.NoSuchElementException; + +public class Controller { + + public void startGame() { + RaidGame raidGame = createRaid(); + OutputView.printMessage(Message.OUTPUT_START_RAID); + + while (isGamePossible(raidGame)) { + showGameStatus(raidGame); + raidGame.executeTurn(selectAttackType(raidGame)); + showTurnResult(raidGame); + } + showGameOver(raidGame); + } + + private RaidGame createRaid() { + OutputView.printMessage(Message.INPUT_MONSTER_HP); + BossMonster bossMonster = ExceptionHandler.retryInput(this::createBossMonster); + + OutputView.printMessage(Message.INPUT_PLAYER_NAME); + String playerName = ExceptionHandler.retryInput(this::requestPlayerName); + + OutputView.printMessage(Message.INPUT_PLAYER_HP_MP); + Player player = ExceptionHandler.retryInput(() -> createPlayer(playerName)); + + return new RaidGame(bossMonster, player); + } + + private BossMonster createBossMonster() { + int bossMonsterHP = Integer.parseInt(Validator.validateInputOfNumber(InputView.readLine())); + return new BossMonster(bossMonsterHP); + } + + private String requestPlayerName() { + return Validator.validatePlayerName(InputView.readLine()); + } + + private Player createPlayer(String playerName) { + String[] playerStatus = Validator.validateInputOfNumbers(InputView.readLine()); + int playerHP = Integer.parseInt(playerStatus[0]); + int playerMP = Integer.parseInt(playerStatus[1]); + return new Player(playerName, playerHP, playerMP); + } + + private boolean isGamePossible(RaidGame raidGame) { + return raidGame.getGameHistory().isGameStatus(); + } + + private void showGameStatus(RaidGame raidGame) { + OutputView.printGameStatus(raidGame.getGameHistory()); + } + + private AttackType selectAttackType(RaidGame raidGame) { + OutputView.printAttackType(provideAttackType()); + return ExceptionHandler.retryInput(() -> requestAttackType(raidGame)); + } + + private LinkedHashMap<Integer, String> provideAttackType() { + LinkedHashMap<Integer, String> attackType = new LinkedHashMap<>(); + for (AttackType type : AttackType.values()) { + if (type.getNumber() != 0) { + attackType.put(type.getNumber(), type.getName()); + } + } + return attackType; + } + + private AttackType requestAttackType(RaidGame raidGame) { + int valueInput = Integer.parseInt(Validator.validateInputOfNumber(InputView.readLine())); + AttackType attackType = Arrays.stream(AttackType.values()) + .filter(type -> type.getNumber() == valueInput && type.getNumber() != 0) + .findFirst() + .orElseThrow(() -> new NoSuchElementException(Message.ERROR_PLAYER_ATTACK_TYPE.getErrorMessage())); + checkPlayerMP(raidGame, attackType); + return attackType; + } + + private void checkPlayerMP(RaidGame raidGame, AttackType attackType) { + GameHistoryDto gameHistoryDto = raidGame.getGameHistory(); + if (gameHistoryDto.getPlayerCurrentMP() < attackType.getMpUsage()) { + throw new ManaShortageException(Message.ERROR_PLAYER_MANA_SHORTAGE.getErrorMessage()); + } + } + + private void showTurnResult(RaidGame raidGame) { + GameHistoryDto gameHistoryDto = raidGame.getGameHistory(); + OutputView.printPlayerTurnResult(gameHistoryDto); + if (gameHistoryDto.getMonsterCurrentHP() != 0) { + OutputView.printBossMonsterTurnResult(gameHistoryDto); + } + } + + private void showGameOver(RaidGame raidGame) { + GameHistoryDto gameHistoryDto = raidGame.getGameHistory(); + if (gameHistoryDto.getMonsterCurrentHP() == 0) { + OutputView.printPlayerWin(gameHistoryDto); + } + if (gameHistoryDto.getPlayerCurrentHP() == 0) { + OutputView.printGameStatus(gameHistoryDto); + OutputView.printPlayerLose(gameHistoryDto); + } + } +}
Java
DTO로 받았다면 인덱스를 사용하지 않고 플레이어 정보를 받았을 수 있을 것 같아요!
@@ -0,0 +1,73 @@ +package bossmonster.domain; + +import bossmonster.domain.dto.GameHistoryDto; + +public class RaidGame { + + private static final int DEFAULT_VALUE = 0; + + private BossMonster bossMonster; + private Player player; + private GameHistory gameHistory; + private boolean status; + private int turns; + + public RaidGame(BossMonster bossMonster, Player player) { + this.bossMonster = bossMonster; + this.player = player; + this.gameHistory = new GameHistory(); + this.status = true; + this.turns = DEFAULT_VALUE; + + gameHistory.addHistory(turns, status, player, bossMonster); + } + + public void executeTurn(AttackType attackType) { + if (isGameProgress()) { + increaseTurn(); + int playerAttackDamage = DEFAULT_VALUE; + int monsterAttackDamage = DEFAULT_VALUE; + playerAttackDamage = executePlayerTurn(attackType); + if (bossMonster.isAlive()) { + monsterAttackDamage = executeBossMonsterTurn(); + } + setStatus(); + createTurnHistory(attackType, playerAttackDamage, monsterAttackDamage); + } + } + + public GameHistoryDto getGameHistory() { + return gameHistory.requestRaidHistory(); + } + + private boolean isGameProgress() { + setStatus(); + return status; + } + + private void setStatus() { + status = player.isAlive() && bossMonster.isAlive(); + } + + private void increaseTurn() { + turns ++; + } + + private int executePlayerTurn(AttackType attackType) { + int playerAttackDamage = player.attack(attackType); + bossMonster.takeDamage(playerAttackDamage); + return playerAttackDamage; + } + + private int executeBossMonsterTurn() { + int monsterAttackDamage = bossMonster.attack(); + player.takeDamage(monsterAttackDamage); + return monsterAttackDamage; + } + + private void createTurnHistory(AttackType playerAttackType, int playerAttackDamage, int monsterAttackDamage) { + gameHistory.addHistory(turns, playerAttackType.getName(), playerAttackDamage, monsterAttackDamage, status, + player, + bossMonster); + } +}
Java
컨트롤러와 도메인을 정말 잘 분리하신 것 같습니다!
@@ -0,0 +1,61 @@ +package bossmonster.domain; + +import bossmonster.exception.Validator; + +public class Player { + + private String name; + private PlayerStatus status; + + public Player(String name, int maxHP, int maxMP) { + this.name = Validator.validatePlayerName(name); + Validator.validatePlayerStatus(maxHP, maxMP); + this.status = new PlayerStatus(maxHP, maxMP); + } + + public String getName() { + return name; + } + + public boolean isAlive() { + return status.isAlive(); + } + + public int getMaxHP() { + return status.getMaxHP(); + } + + public int getCurrentHP() { + return status.getCurrentHP(); + } + + public int getMaxMP() { + return status.getMaxMP(); + } + + public int getCurrentMP() { + return status.getCurrentMP(); + } + + public int attack(AttackType attackType) { + if (attackType.getName().equals(AttackType.ATTACK_TYPE_NORMAL.getName())) { + recoverMP(attackType.getMpRecover()); + } + if (attackType.getName().equals(AttackType.ATTACK_TYPE_MAGIC.getName())) { + consumeMP(attackType.getMpUsage()); + } + return attackType.getDamage(); + } + + public void takeDamage(int damage) { + status.setCurrentHP(status.getCurrentHP() - damage); + } + + private void recoverMP(int mp) { + status.setCurrentMP(status.getCurrentMP() + mp); + } + + private void consumeMP(int mp) { + status.setCurrentMP(status.getCurrentMP() - mp); + } +}
Java
이 부분 어려우셨을텐데 역할분배 잘하신 것 같아요!
@@ -0,0 +1,63 @@ +package bossmonster.view.constants; + +public enum Message { + + /* Input Request */ + INPUT_MONSTER_HP("보스 몬스터의 HP를 입력해주세요."), + INPUT_PLAYER_NAME("\n" + "플레이어의 이름을 입력해주세요"), + INPUT_PLAYER_HP_MP("\n" + "플레이어의 HP와 MP를 입력해주세요.(,로 구분)"), + INPUT_ATTACK_TYPE_SELECT("\n" + "어떤 공격을 하시겠습니까?"), + INPUT_ATTACK_TYPE("%d. %s"), + + /* Output Message */ + OUTPUT_START_RAID("\n" + "보스 레이드를 시작합니다!"), + OUTPUT_LINE_ONE("============================"), + OUTPUT_BOSS_STATUS("BOSS HP [%d/%d]"), + OUTPUT_LINE_TWO("____________________________"), + OUTPUT_BOSS_DEFAULT(" ^-^" + "\n" + + " / 0 0 \\" + "\n" + + "( \" )" + "\n" + + " \\ - /" + "\n" + + " - ^ -"), + OUTPUT_BOSS_DAMAGED(" ^-^" + "\n" + + " / x x \\" + "\n" + + "( \"\\ )" + "\n" + + " \\ ^ /" + "\n" + + " - ^ -"), + OUTPUT_BOSS_WIN(" ^-^" + "\n" + + " / ^ ^ \\" + "\n" + + "( \" )" + "\n" + + " \\ 3 /" + "\n" + + " - ^ -"), + OUTPUT_PLAYER_STATUS("\n" + "%s HP [%d/%d] MP [%d/%d]"), + OUTPUT_TURN_RESULT_PLAYER("\n" + "%s을 했습니다. (입힌 데미지: %d)"), + OUTPUT_TURN_RESULT_BOSS("보스가 공격 했습니다. (입힌 데미지: %d)"), + OUTPUT_GAME_OVER_PLAYER_WIN("\n" + "%s 님이 %d번의 전투 끝에 보스 몬스터를 잡았습니다."), + OUTPUT_GAME_OVER_PLAYER_LOSE("\n" + "%s의 HP가 %d이 되었습니다." + "\n" + "보스 레이드에 실패했습니다."), + + /* Error Message */ + ERROR_EMPTY("입력값이 없습니다. 다시 입력해 주세요."), + ERROR_NOT_INTEGER("숫자만 입력 가능합니다. 다시 입력해 주세요."), + ERROR_NOT_COMMA("콤마(',')를 통해 구분해서 다시 입력해 주세요."), + ERROR_ARRAY_SIZE("입력된 항목이 많습니다. 다시 입력해 주세요."), + ERROR_BOSS_MONSTER_HP("보스몬스터의 HP는 100 이상 300 이하만 설정 가능합니다. 다시 입력해 주세요."), + ERROR_PLAYER_NAME("플레이어의 이름은 5자 이하만 가능합니다. 다시 입력해 주세요."), + ERROR_PLAYER_STATUS("플레이어의 HP와 MP의 합은 200으로만 설정 가능합니다. 다시 입력해 주세요."), + ERROR_PLAYER_ATTACK_TYPE("존재하지 않는 공격 방식입니다. 다시 입력해 주세요."), + ERROR_PLAYER_MANA_SHORTAGE("마나가 부족합니다. 다시 입력해 주세요."); + + public static final String ERROR_PREFIX = "[ERROR] "; + private final String message; + + Message(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public String getErrorMessage() { + return ERROR_PREFIX + message; + } +}
Java
저도 상수를 한 파일로 관리했었는데요. 상수를 한 파일로 관리하게 되면 팀 프로젝트를 진행할 때 상수 파일에서 충돌이 많이 일어나더라구요. 이런 문제를 어떻게 해결하면 좋을까요?
@@ -0,0 +1,63 @@ +package bossmonster.view.constants; + +public enum Message { + + /* Input Request */ + INPUT_MONSTER_HP("보스 몬스터의 HP를 입력해주세요."), + INPUT_PLAYER_NAME("\n" + "플레이어의 이름을 입력해주세요"), + INPUT_PLAYER_HP_MP("\n" + "플레이어의 HP와 MP를 입력해주세요.(,로 구분)"), + INPUT_ATTACK_TYPE_SELECT("\n" + "어떤 공격을 하시겠습니까?"), + INPUT_ATTACK_TYPE("%d. %s"), + + /* Output Message */ + OUTPUT_START_RAID("\n" + "보스 레이드를 시작합니다!"), + OUTPUT_LINE_ONE("============================"), + OUTPUT_BOSS_STATUS("BOSS HP [%d/%d]"), + OUTPUT_LINE_TWO("____________________________"), + OUTPUT_BOSS_DEFAULT(" ^-^" + "\n" + + " / 0 0 \\" + "\n" + + "( \" )" + "\n" + + " \\ - /" + "\n" + + " - ^ -"), + OUTPUT_BOSS_DAMAGED(" ^-^" + "\n" + + " / x x \\" + "\n" + + "( \"\\ )" + "\n" + + " \\ ^ /" + "\n" + + " - ^ -"), + OUTPUT_BOSS_WIN(" ^-^" + "\n" + + " / ^ ^ \\" + "\n" + + "( \" )" + "\n" + + " \\ 3 /" + "\n" + + " - ^ -"), + OUTPUT_PLAYER_STATUS("\n" + "%s HP [%d/%d] MP [%d/%d]"), + OUTPUT_TURN_RESULT_PLAYER("\n" + "%s을 했습니다. (입힌 데미지: %d)"), + OUTPUT_TURN_RESULT_BOSS("보스가 공격 했습니다. (입힌 데미지: %d)"), + OUTPUT_GAME_OVER_PLAYER_WIN("\n" + "%s 님이 %d번의 전투 끝에 보스 몬스터를 잡았습니다."), + OUTPUT_GAME_OVER_PLAYER_LOSE("\n" + "%s의 HP가 %d이 되었습니다." + "\n" + "보스 레이드에 실패했습니다."), + + /* Error Message */ + ERROR_EMPTY("입력값이 없습니다. 다시 입력해 주세요."), + ERROR_NOT_INTEGER("숫자만 입력 가능합니다. 다시 입력해 주세요."), + ERROR_NOT_COMMA("콤마(',')를 통해 구분해서 다시 입력해 주세요."), + ERROR_ARRAY_SIZE("입력된 항목이 많습니다. 다시 입력해 주세요."), + ERROR_BOSS_MONSTER_HP("보스몬스터의 HP는 100 이상 300 이하만 설정 가능합니다. 다시 입력해 주세요."), + ERROR_PLAYER_NAME("플레이어의 이름은 5자 이하만 가능합니다. 다시 입력해 주세요."), + ERROR_PLAYER_STATUS("플레이어의 HP와 MP의 합은 200으로만 설정 가능합니다. 다시 입력해 주세요."), + ERROR_PLAYER_ATTACK_TYPE("존재하지 않는 공격 방식입니다. 다시 입력해 주세요."), + ERROR_PLAYER_MANA_SHORTAGE("마나가 부족합니다. 다시 입력해 주세요."); + + public static final String ERROR_PREFIX = "[ERROR] "; + private final String message; + + Message(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public String getErrorMessage() { + return ERROR_PREFIX + message; + } +}
Java
입출력에 사용되는 메시지들을 InputView와 OutputView에서 각각 사용하다 보니 메시지가 많은 경우에는 자리를 많이 차지하는 것 같아서 한 파일로 관리하고 가져다 쓰는 형태로 해야겠다고 생각했습니다. 제가 공부한지 얼마 되지 않아 팀 프로젝트를 경험해본 적이 아직 없어 어떤 부분에서 충돌이 일어나는지는 잘 모르겠습니다. 분명 상수를 한 파일로 관리하다보면 문제가 생길 수도 있을 것 같은데요. 이 부분은 여러 프로젝트를 진행하면서 조금 더 고민해 봐야 할 부분인 것 같습니다. 의견 감사합니다!
@@ -0,0 +1,78 @@ +package bossmonster.exception; + +import bossmonster.view.constants.Message; + +public class Validator { + + public static String validateInputOfNumber(String inputValue) { + validateEmpty(inputValue); + validateInteger(inputValue); + return inputValue; + } + + public static String validatePlayerName(String inputValue) { + validateEmpty(inputValue); + validateRangeOfPlayerName(inputValue); + return inputValue; + } + + public static String[] validateInputOfNumbers(String inputValue) { + validateSeparated(inputValue); + String[] separatedValue = inputValue.split(","); + validateArray(separatedValue); + for (String value : separatedValue) { + validateEmpty(value); + validateInteger(value); + } + return separatedValue; + } + + public static int validateBossMonster(int hp) { + return validateRangeOfMonster(hp); + } + + public static void validatePlayerStatus(int hp, int mp) { + if (hp + mp != 200) { + throw new IllegalArgumentException(Message.ERROR_PLAYER_STATUS.getErrorMessage()); + } + } + + private static void validateEmpty(String inputValue) { + if (inputValue.isEmpty()) { + throw new IllegalArgumentException(Message.ERROR_EMPTY.getErrorMessage()); + } + } + + private static void validateInteger(String inputValue) { + try { + Integer.parseInt(inputValue); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(Message.ERROR_NOT_INTEGER.getErrorMessage()); + } + } + + private static void validateSeparated(String inputValue) { + if (!inputValue.contains(",")) { + throw new IllegalArgumentException(Message.ERROR_NOT_COMMA.getErrorMessage()); + } + } + + private static void validateArray(String[] inputValue) { + if (inputValue.length != 2) { + throw new IllegalArgumentException(Message.ERROR_ARRAY_SIZE.getErrorMessage()); + } + } + + private static int validateRangeOfMonster(int hp) { + if (hp < 100 || hp > 300) { + throw new IllegalArgumentException(Message.ERROR_BOSS_MONSTER_HP.getErrorMessage()); + } + return hp; + } + + private static void validateRangeOfPlayerName(String name) { + if (name.length() > 5) { + throw new IllegalArgumentException(Message.ERROR_PLAYER_NAME.getErrorMessage()); + } + } +}
Java
처음에는 입력 단계에서 검증하는 부분만 따로 넣고, 도메인 부분에서 검증할 로직은 각 도메인 클래스에서 진행하는 것으로 했었는데요. 하다보니 겹치는 부분이 있는 것 같아서 잘 활용하지 못했습니다. 위에서 의견을 주신 것 처럼 DTO를 활용하면 더 깔끔하게 검증 로직을 분배할 수 있을 것 같습니다.
@@ -0,0 +1,17 @@ +package bossmonster.exception; + +import bossmonster.view.OutputView; +import java.util.function.Supplier; + +public class ExceptionHandler { + + public static <T> T retryInput(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (Exception exception) { + OutputView.printError(exception); + } + } + } +}
Java
저도 에러 발생 시, 재입력을 받아야 하는 부분에 대해서 고민을 많이 하다가.. 다른 분들의 코드 리뷰를 보고 여러가지 찾아보다 이런 방법도 있다는 것을 알게 되었습니다. 하나 만들어 두면 활용성이 좋은 것 같아요. 네이밍에 대해서는 말씀 주신 부분처럼 가독성이 안 좋아 질 수 있기 때문에 더 고민이 필요할 것 같습니다. 막상 네이밍에 대해서는 많이 신경을 쓰지 못했던 것 같네요. 클래스명에 관해 의견 주신 부분에 대해서도 감사합니다. 스프링에 대한 개념이 아직 없어서 스프링의 ExceptionHandler가 어떻게 사용되는지 처음 알았네요.. 저는 단순히 예외를 관리한다는 부분에서 저렇게 사용했는데 다른 분들이 읽기에는 헷갈릴 수 있을 것 같습니다. 이 부분도 참고하겠습니다. 감사합니다!
@@ -0,0 +1,82 @@ +package bossmonster.domain.dto; + +public class GameHistoryDto { + + private int turnCount; + private String playerName; + private String playerAttackType; + private int playerAttackDamage; + private int monsterAttackDamage; + private int playerMaxHP; + private int playerCurrentHP; + private int playerMaxMP; + private int playerCurrentMP; + private int monsterMaxHP; + private int monsterCurrentHP; + private boolean gameStatus; + + public GameHistoryDto(int turnCount, String playerName, String playerAttackType, int playerAttackDamage, + int monsterAttackDamage, int playerMaxHP, int playerCurrentHP, int playerMaxMP, + int playerCurrentMP, int monsterMaxHP, int monsterCurrentHP, boolean gameStatus) { + this.turnCount = turnCount; + this.playerName = playerName; + this.playerAttackType = playerAttackType; + this.playerAttackDamage = playerAttackDamage; + this.monsterAttackDamage = monsterAttackDamage; + this.playerMaxHP = playerMaxHP; + this.playerCurrentHP = playerCurrentHP; + this.playerMaxMP = playerMaxMP; + this.playerCurrentMP = playerCurrentMP; + this.monsterMaxHP = monsterMaxHP; + this.monsterCurrentHP = monsterCurrentHP; + this.gameStatus = gameStatus; + } + + public int getTurnCount() { + return turnCount; + } + + public String getPlayerName() { + return playerName; + } + + public String getPlayerAttackType() { + return playerAttackType; + } + + public int getPlayerAttackDamage() { + return playerAttackDamage; + } + + public int getMonsterAttackDamage() { + return monsterAttackDamage; + } + + public int getPlayerMaxHP() { + return playerMaxHP; + } + + public int getPlayerCurrentHP() { + return playerCurrentHP; + } + + public int getPlayerMaxMP() { + return playerMaxMP; + } + + public int getPlayerCurrentMP() { + return playerCurrentMP; + } + + public int getMonsterMaxHP() { + return monsterMaxHP; + } + + public int getMonsterCurrentHP() { + return monsterCurrentHP; + } + + public boolean isGameStatus() { + return gameStatus; + } +}
Java
단순히 현재 게임 상태를 묻기 위해 썼던 것 같은데 의견 주신 메서드명이 반환되는 값을 이해하기에 더 직관적이네요!
@@ -0,0 +1,73 @@ +package bossmonster.domain; + +import bossmonster.domain.dto.GameHistoryDto; + +public class RaidGame { + + private static final int DEFAULT_VALUE = 0; + + private BossMonster bossMonster; + private Player player; + private GameHistory gameHistory; + private boolean status; + private int turns; + + public RaidGame(BossMonster bossMonster, Player player) { + this.bossMonster = bossMonster; + this.player = player; + this.gameHistory = new GameHistory(); + this.status = true; + this.turns = DEFAULT_VALUE; + + gameHistory.addHistory(turns, status, player, bossMonster); + } + + public void executeTurn(AttackType attackType) { + if (isGameProgress()) { + increaseTurn(); + int playerAttackDamage = DEFAULT_VALUE; + int monsterAttackDamage = DEFAULT_VALUE; + playerAttackDamage = executePlayerTurn(attackType); + if (bossMonster.isAlive()) { + monsterAttackDamage = executeBossMonsterTurn(); + } + setStatus(); + createTurnHistory(attackType, playerAttackDamage, monsterAttackDamage); + } + } + + public GameHistoryDto getGameHistory() { + return gameHistory.requestRaidHistory(); + } + + private boolean isGameProgress() { + setStatus(); + return status; + } + + private void setStatus() { + status = player.isAlive() && bossMonster.isAlive(); + } + + private void increaseTurn() { + turns ++; + } + + private int executePlayerTurn(AttackType attackType) { + int playerAttackDamage = player.attack(attackType); + bossMonster.takeDamage(playerAttackDamage); + return playerAttackDamage; + } + + private int executeBossMonsterTurn() { + int monsterAttackDamage = bossMonster.attack(); + player.takeDamage(monsterAttackDamage); + return monsterAttackDamage; + } + + private void createTurnHistory(AttackType playerAttackType, int playerAttackDamage, int monsterAttackDamage) { + gameHistory.addHistory(turns, playerAttackType.getName(), playerAttackDamage, monsterAttackDamage, status, + player, + bossMonster); + } +}
Java
감사합니다. 객체지향을 공부하면서 MVC 패턴에 구애받지 않고 도메인 로직은 도메인 로직에서만으로도 돌아갈 수 있도록 구현하고자 연습하고 있습니다. 컨트롤러가 없어도 도메인 내에서는 도메인 로직이 잘 돌아가야 한다고 생각하면서 고민했던 것 같아요!
@@ -0,0 +1,61 @@ +package bossmonster.domain; + +import bossmonster.exception.Validator; + +public class Player { + + private String name; + private PlayerStatus status; + + public Player(String name, int maxHP, int maxMP) { + this.name = Validator.validatePlayerName(name); + Validator.validatePlayerStatus(maxHP, maxMP); + this.status = new PlayerStatus(maxHP, maxMP); + } + + public String getName() { + return name; + } + + public boolean isAlive() { + return status.isAlive(); + } + + public int getMaxHP() { + return status.getMaxHP(); + } + + public int getCurrentHP() { + return status.getCurrentHP(); + } + + public int getMaxMP() { + return status.getMaxMP(); + } + + public int getCurrentMP() { + return status.getCurrentMP(); + } + + public int attack(AttackType attackType) { + if (attackType.getName().equals(AttackType.ATTACK_TYPE_NORMAL.getName())) { + recoverMP(attackType.getMpRecover()); + } + if (attackType.getName().equals(AttackType.ATTACK_TYPE_MAGIC.getName())) { + consumeMP(attackType.getMpUsage()); + } + return attackType.getDamage(); + } + + public void takeDamage(int damage) { + status.setCurrentHP(status.getCurrentHP() - damage); + } + + private void recoverMP(int mp) { + status.setCurrentMP(status.getCurrentMP() + mp); + } + + private void consumeMP(int mp) { + status.setCurrentMP(status.getCurrentMP() - mp); + } +}
Java
잘 되었다니 다행이네요 좋게 봐주셔서 감사합니다!
@@ -0,0 +1,61 @@ +package bossmonster.domain; + +import bossmonster.exception.Validator; + +public class Player { + + private String name; + private PlayerStatus status; + + public Player(String name, int maxHP, int maxMP) { + this.name = Validator.validatePlayerName(name); + Validator.validatePlayerStatus(maxHP, maxMP); + this.status = new PlayerStatus(maxHP, maxMP); + } + + public String getName() { + return name; + } + + public boolean isAlive() { + return status.isAlive(); + } + + public int getMaxHP() { + return status.getMaxHP(); + } + + public int getCurrentHP() { + return status.getCurrentHP(); + } + + public int getMaxMP() { + return status.getMaxMP(); + } + + public int getCurrentMP() { + return status.getCurrentMP(); + } + + public int attack(AttackType attackType) { + if (attackType.getName().equals(AttackType.ATTACK_TYPE_NORMAL.getName())) { + recoverMP(attackType.getMpRecover()); + } + if (attackType.getName().equals(AttackType.ATTACK_TYPE_MAGIC.getName())) { + consumeMP(attackType.getMpUsage()); + } + return attackType.getDamage(); + } + + public void takeDamage(int damage) { + status.setCurrentHP(status.getCurrentHP() - damage); + } + + private void recoverMP(int mp) { + status.setCurrentMP(status.getCurrentMP() + mp); + } + + private void consumeMP(int mp) { + status.setCurrentMP(status.getCurrentMP() - mp); + } +}
Java
밑에 Validator의 사용에 대해 주신 의견과 동일한 문제네요.. 입출력에 관련된 검증과 도메인 부분의 검증은 분리해서 사용하는게 맞을 것 같습니다. 감사합니다!
@@ -0,0 +1,70 @@ +package bossmonster.domain; + +import bossmonster.domain.dto.GameHistoryDto; +import java.util.ArrayList; +import java.util.List; + +public class GameHistory { + + private class Turns { + + private int turnCount; + private String playerName; + private String playerAttackType; + private int playerAttackDamage; + private int monsterAttackDamage; + private int playerMaxHP; + private int playerCurrentHP; + private int playerMaxMP; + private int playerCurrentMP; + private int monsterMaxHP; + private int monsterCurrentHP; + private boolean gameStatus; + + public Turns(int turnCount, String playerAttackType, int playerAttackDamage, + int monsterAttackDamage, boolean gameStatus, Player player, BossMonster bossMonster) { + this.turnCount = turnCount; + this.playerName = player.getName(); + this.playerAttackType = playerAttackType; + this.playerAttackDamage = playerAttackDamage; + this.monsterAttackDamage = monsterAttackDamage; + this.playerMaxHP = player.getMaxHP(); + this.playerCurrentHP = player.getCurrentHP(); + this.playerMaxMP = player.getMaxMP(); + this.playerCurrentMP = player.getCurrentMP(); + this.monsterMaxHP = bossMonster.getMaxHP(); + this.monsterCurrentHP = bossMonster.getCurrentHP(); + this.gameStatus = gameStatus; + } + } + + private static final String DEFAULT_ATTACK_TYPE = ""; + private static final int DEFAULT_DAMAGE = 0; + private int recentRecord; + private List<Turns> raidHistory = new ArrayList<>(); + + public void addHistory(int turnCount, boolean gameStatus, Player player, BossMonster bossMonster) { + raidHistory.add( + new Turns(turnCount, DEFAULT_ATTACK_TYPE, DEFAULT_DAMAGE, DEFAULT_DAMAGE, gameStatus, player, + bossMonster)); + } + + public void addHistory(int turnCount, String playerAttackType, int playerAttackDamage, + int monsterAttackDamage, boolean gameStatus, Player player, BossMonster bossMonster) { + raidHistory.add( + new Turns(turnCount, playerAttackType, playerAttackDamage, monsterAttackDamage, gameStatus, player, + bossMonster)); + } + + public GameHistoryDto requestRaidHistory() { + setRecentRecord(); + Turns turns = raidHistory.get(recentRecord); + return new GameHistoryDto(turns.turnCount, turns.playerName, turns.playerAttackType, turns.playerAttackDamage, + turns.monsterAttackDamage, turns.playerMaxHP, turns.playerCurrentHP, turns.playerMaxMP, + turns.playerCurrentMP, turns.monsterMaxHP, turns.monsterCurrentHP, turns.gameStatus); + } + + private void setRecentRecord() { + recentRecord = raidHistory.size() - 1; + } +}
Java
컨트롤러에서 게임을 제어하는 것 보다 RaidGame 클래스에서 전체적인 게임 로직이 돌아가는 형태로 생각하고 구현하다 보니 게임이 실행되면서 히스토리를 남기고 컨트롤러에서 출력을 위해서는 기록에 남겨진 부분을 가져다가 보여줘야 의존성이 떨어질 것 같다고 생각했습니다. 실제로 턴 제 게임을 하면 매 턴마다 턴에 대한 기록이 게임에서도 남게 되는데 이걸 생각해서 만들었던 것 같습니다!
@@ -0,0 +1,119 @@ +package bossmonster.controller; + +import bossmonster.domain.AttackType; +import bossmonster.domain.BossMonster; +import bossmonster.domain.Player; +import bossmonster.domain.RaidGame; +import bossmonster.domain.dto.GameHistoryDto; +import bossmonster.exception.ExceptionHandler; +import bossmonster.exception.ManaShortageException; +import bossmonster.exception.Validator; +import bossmonster.view.InputView; +import bossmonster.view.OutputView; +import bossmonster.view.constants.Message; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.NoSuchElementException; + +public class Controller { + + public void startGame() { + RaidGame raidGame = createRaid(); + OutputView.printMessage(Message.OUTPUT_START_RAID); + + while (isGamePossible(raidGame)) { + showGameStatus(raidGame); + raidGame.executeTurn(selectAttackType(raidGame)); + showTurnResult(raidGame); + } + showGameOver(raidGame); + } + + private RaidGame createRaid() { + OutputView.printMessage(Message.INPUT_MONSTER_HP); + BossMonster bossMonster = ExceptionHandler.retryInput(this::createBossMonster); + + OutputView.printMessage(Message.INPUT_PLAYER_NAME); + String playerName = ExceptionHandler.retryInput(this::requestPlayerName); + + OutputView.printMessage(Message.INPUT_PLAYER_HP_MP); + Player player = ExceptionHandler.retryInput(() -> createPlayer(playerName)); + + return new RaidGame(bossMonster, player); + } + + private BossMonster createBossMonster() { + int bossMonsterHP = Integer.parseInt(Validator.validateInputOfNumber(InputView.readLine())); + return new BossMonster(bossMonsterHP); + } + + private String requestPlayerName() { + return Validator.validatePlayerName(InputView.readLine()); + } + + private Player createPlayer(String playerName) { + String[] playerStatus = Validator.validateInputOfNumbers(InputView.readLine()); + int playerHP = Integer.parseInt(playerStatus[0]); + int playerMP = Integer.parseInt(playerStatus[1]); + return new Player(playerName, playerHP, playerMP); + } + + private boolean isGamePossible(RaidGame raidGame) { + return raidGame.getGameHistory().isGameStatus(); + } + + private void showGameStatus(RaidGame raidGame) { + OutputView.printGameStatus(raidGame.getGameHistory()); + } + + private AttackType selectAttackType(RaidGame raidGame) { + OutputView.printAttackType(provideAttackType()); + return ExceptionHandler.retryInput(() -> requestAttackType(raidGame)); + } + + private LinkedHashMap<Integer, String> provideAttackType() { + LinkedHashMap<Integer, String> attackType = new LinkedHashMap<>(); + for (AttackType type : AttackType.values()) { + if (type.getNumber() != 0) { + attackType.put(type.getNumber(), type.getName()); + } + } + return attackType; + } + + private AttackType requestAttackType(RaidGame raidGame) { + int valueInput = Integer.parseInt(Validator.validateInputOfNumber(InputView.readLine())); + AttackType attackType = Arrays.stream(AttackType.values()) + .filter(type -> type.getNumber() == valueInput && type.getNumber() != 0) + .findFirst() + .orElseThrow(() -> new NoSuchElementException(Message.ERROR_PLAYER_ATTACK_TYPE.getErrorMessage())); + checkPlayerMP(raidGame, attackType); + return attackType; + } + + private void checkPlayerMP(RaidGame raidGame, AttackType attackType) { + GameHistoryDto gameHistoryDto = raidGame.getGameHistory(); + if (gameHistoryDto.getPlayerCurrentMP() < attackType.getMpUsage()) { + throw new ManaShortageException(Message.ERROR_PLAYER_MANA_SHORTAGE.getErrorMessage()); + } + } + + private void showTurnResult(RaidGame raidGame) { + GameHistoryDto gameHistoryDto = raidGame.getGameHistory(); + OutputView.printPlayerTurnResult(gameHistoryDto); + if (gameHistoryDto.getMonsterCurrentHP() != 0) { + OutputView.printBossMonsterTurnResult(gameHistoryDto); + } + } + + private void showGameOver(RaidGame raidGame) { + GameHistoryDto gameHistoryDto = raidGame.getGameHistory(); + if (gameHistoryDto.getMonsterCurrentHP() == 0) { + OutputView.printPlayerWin(gameHistoryDto); + } + if (gameHistoryDto.getPlayerCurrentHP() == 0) { + OutputView.printGameStatus(gameHistoryDto); + OutputView.printPlayerLose(gameHistoryDto); + } + } +}
Java
제가 작성한 코드의 InputView는 단순히 입력을 받는 메서드만 존재 하는데요. 이렇게 구성하다 보니 컨트롤러에서 입력받은 부분에 대해서 검증을 하고 변환해서 도메인을 생성하거나 데이터를 넘겨줘야 해서 할 일이 많아지는 단점이 있네요. 말씀주신 것처럼 InputView 쪽에서 입력을 받고 바로 입력에 대한 부분을 검증해서 DTO를 생성하여 건네주는 방식을 연습해봐야 할 것 같습니다. 좋은 의견 감사합니다!
@@ -0,0 +1,100 @@ +# Domain 구현 + +## 진행 프로세스 (시스템 책임) + +1. 게이머는 상대할 보스 몬스터의 HP를 설정한다. +2. 게이머는 플레이할 플레이어의 이름과 HP, MP를 설정한다. +3. 게임이 시작된다. +4. 게임은 턴제이며, 매 턴마다 다음과 같은 행동이 반복된다. + 1) 보스 몬스터와 플레이어의 현재 상태를 보여준다. + 2) 플레이어가 공격할 방식을 선택한다. + 3) 플레이어가 선택된 방식으로 공격한다. (보스 몬스터에게 데미지를 입힘) + 4) 데미지를 입은 보스 몬스터의 상태를 확인한다. + 5) 보스 몬스터가 죽었다면 게임이 종료된다. + 6) 보스 몬스터가 살아있다면 플레이어를 공격한다. + 7) 데미지를 입은 플레이어의 상태를 확인한다. + 8) 플레이어가 죽었다면 게임이 종료된다. +5. 게임 종료 후 승자를 안내한다. + - 플레이어가 이겼을 경우 : 진행한 턴 수를 알려준다. + - 보스 몬스터가 이겼을 경우 : 플레이어와 보스 몬스터의 현재 상태를 보여준다. + +## Domain 객체 선정 및 책임과 협력 할당 + +1. **Raid Game** + - 게임 시작 전 주요 인물에 대해 셋팅할 책임을 가짐 + - 게임 인물인 **Boss Monster**를 생성할 책임을 가짐 + - 게임 인물인 **Player**를 생성할 책임을 가짐 + - 매 턴을 실행할 책임을 가짐 + - 게임 상태를 확인할 책임을 가짐 (게임 상태가 '종료'일 경우 턴을 실행하지 않음) + - 턴 수를 증가시킬 책임을 가짐 + - **Player**가 **Boss Monster**를 선택된 공격 방식으로 공격하도록 할 책임을 가짐 + - **Player**의 공격 행동에 대한 결과를 제공받고, **Boss Monster**에게 전달할 책임을 가짐 (**Player**의 공격과 **Boss Monster**의 피해 행동에 대한 협력 필요) + - **Boss Monster**의 생존여부에 따라 게임 상태를 변경할 책임을 가짐 (**Boss Monster**의 상태를 제공받는 협력 필요) + - **Boss Monster**가 **Player**를 공격하도록 할 책임을 가짐 (**Boss Monster**의 공격과 **Player**의 피해 행동에 대한 협력 필요) + - **Boss Monster**의 공격 행동에 대한 결과를 제공받고, **Player**에게 전달할 책임을 가짐 (**Boss Monster**의 공격과 **Player**의 피해 행동에 대한 협력 필요) + - **Player**의 생존여부에 따라 게임 상태를 변경할 책임을 가짐 (**Player**의 상태를 제공받는 협력 필요) + - 해당 턴에 대한 게임 기록을 생성할 책임을 가짐 (**GameHistory**에게 턴에 대한 기록을 생성하는 협력 필요) + +2. **Boss Monster** + - 현재 상태를 제공해줄 책임을 가짐 (총 HP, 현재 HP) + - 공격 명령을 수행할 책임을 가짐 (0~20의 랜덤 데미지) + - 공격 피해 입음을 수행할 책임을 가짐 (현재 HP 감소) + +3. **Player** + - 현재 상태를 제공해줄 책임을 가짐 (이름, 총 HP, 현재 HP, 총 MP, 현재 MP) + - 공격 명령을 수행할 책임을 가짐 (**Attack Type**에 대한 정보를 제공받는 협력 필요, MP 감소) + - 공격 피해 입음을 수행할 책임을 가짐 (현재 HP 감소) + +4. **Attack Type** + - 공격 방식 종류를 제공해줄 책임을 가짐 (공격 변호, 공격 방식 이름) + - 공격 방식 수행에 대한 정보를 제공해줄 책임을 가짐 (데미지, MP 소모량, MP 회복량) + +5. **Game History** + - 매 턴에 대한 기록을 저장할 책임을 가짐 + - 추후 Controller의 Veiw를 위한 요청에 응답 가능 + +## 주요 메시지 구성 (공용 인터페이스) + +1. 보스 몬스터 설정을 요청 + - 수신자 : Raid Game + - 이름 : Create Boss Monster + - 인자 : int hp + - 응답 : void, Boss Monster 객체 생성 + +2. 플레이어 설정을 요청 + - 수신자 : Raid Game + - 이름 : Create Player + - 인자 : String name, int hp, int mp + - 응답 : void, Player 객체 생성 + +3. 턴 진행을 요청 + - 수신자 : Raid Game + - 이름 : Start Game + - 인자 : - + - 응답 : 구성된 턴 로직 실행 + +4. 게임 상태 확인을 요청 + - 수신자 : Raid Game + - 이름 : Check Game Status + - 인자 : - + - 응답 : return Game Status (true or False) + +5. 턴 횟수 증가를 요청 + - 수신자 : Raid Game + - 이름 : Increase Turns + - 인자 : - + - 응답 : void, Turn 1 증가 + +6. 공격 행동 수행을 요청 + - 수신자 : Player, Boss Monster + - 이름 : Attack + - 인자 : - + - 응답 : return 데미지, 공격 방식에 따라 MP 감소(Player) + +7. 공격 피해 전달을 요청 + - 수신자 : Player, Boss Monster + - 이름 : take Damage + - 인자 : int damage + - 응답 : return 현재 HP + +
Unknown
아직은 기능 목록 문서에 대해서 누군가 본다는 생각보다는 제가 구현에 앞서서 공부한 내용으로 이해하기 쉽게 정리하는 것을 목적으로 작성했었는데요. 개발은 혼자 하는 것이 아니기에 말씀 주신 부분에 대해서도 신경을 쓰면서 작성을 해야 할 것 같습니다. 감사합니다. 제가 밑에서부터 리뷰에 대한 답글을 남겼습니다. 리뷰를 요청하고 받아 보는게 처음이라 이렇게 도움이 많이 되는지 몰랐네요. 아직 공부를 시작한지 얼마 되지 않아 코드 읽기가 많이 힘드셨을텐데 늦은 시간에도 리뷰 해주셔서 감사합니다. 주신 의견들 모두 참고해서 제가 개선해 나가야 할 방향인 것 같습니다. 리뷰 감사드립니다. 좋은 하루 되세요!
@@ -0,0 +1,9 @@ +# 풀이 1 - Counter 이용 +from collections import Counter + +def solution(participant, completion): + # Counter를 이용하면 리스트 내의 성분의 숫자를 딕셔너리 형태로 반환해준다 + # ex) list1 =['a', 'b', 'c', 'a'] => Counter(list1) : {'a':2, 'b':1, 'c':1} + not_completion = Counter(participant) - Counter(completion) # Counter의 경우 사칙연산도 가능 + + return list(not_completion.keys())[0]
Python
`Counter`를 이용하는 방법이 굉장히 유용하군요 ! 💯
@@ -7,23 +7,31 @@ import useToast from '@/hooks/useToast'; import TextArea from '@/components/@shared/input/TextArea'; import RatingInput from '@/components/@shared/rating/RatingInput'; import Toast from '@/components/@shared/Toast'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { EditReviewParams, ReviewParams } from '@/types/mypage.types'; +import { editGatheringReview, postGatheringReview } from '@/axios/mypage/api'; interface MyReviewModalProps { isModal: boolean; setIsModal: React.Dispatch<React.SetStateAction<boolean>>; + id: number; // reviewId 또는 gatheringId score?: number; comment?: string; } export default function MyReviewModal({ isModal, + id, setIsModal, score, comment, }: MyReviewModalProps) { const [updatedScore, setUpdatedScore] = useState<number>(score || 0); const [updatedComment, setUpdatedComment] = useState<string>(comment || ''); - const { toastMessage, toastVisible, toastType, handleError } = useToast(); + const { toastMessage, toastVisible, toastType, handleError, handleSuccess } = + useToast(); + const queryClient = useQueryClient(); + const closeModalhandler = () => { setIsModal(false); }; @@ -39,6 +47,45 @@ export default function MyReviewModal({ const isModified = (updatedComment?.trim() !== '' && comment !== updatedComment) || (updatedScore > 0 && score !== updatedScore); + + // score||comment가 있을 때의 id는 reviewId => 리뷰 수정 + const { mutate: editReview } = useMutation({ + mutationFn: async ({ + reviewId, + ...submissData + }: { reviewId: number } & EditReviewParams) => + editGatheringReview(reviewId, submissData), + onSuccess: () => { + handleSuccess('리뷰가 수정되었습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.error('editReview Error:', error); + handleError('리뷰 수정에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + + // score&&comment가 없을 때의 id는 gatheringId => 리뷰 작성 + const { mutate: writeReview } = useMutation({ + mutationFn: async (submissData: ReviewParams) => + postGatheringReview(submissData), + onSuccess: () => { + handleSuccess('리뷰를 작성했습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', false] }); + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.log('postReview Error:', error); + handleError('리뷰 작성에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + return ( <Modal isOpen={isModal} @@ -83,7 +130,22 @@ export default function MyReviewModal({ disabled={!isModified} className="w-full" onClick={() => { - handleError('아직 구현되지 않은 기능입니다.'); + // 리뷰 작성 + if (!(score && comment)) { + const submissionData = { + gatheringId: id, + score: updatedScore, + comment: updatedComment, + }; + writeReview(submissionData); + // 리뷰 수정 + } else { + editReview({ + reviewId: id, + score: updatedScore, + comment: updatedComment, + }); + } }} > 리뷰등록
Unknown
[myReviews,true]인 쿼리키를 사용하는 쿼리가 있나요?
@@ -7,23 +7,31 @@ import useToast from '@/hooks/useToast'; import TextArea from '@/components/@shared/input/TextArea'; import RatingInput from '@/components/@shared/rating/RatingInput'; import Toast from '@/components/@shared/Toast'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { EditReviewParams, ReviewParams } from '@/types/mypage.types'; +import { editGatheringReview, postGatheringReview } from '@/axios/mypage/api'; interface MyReviewModalProps { isModal: boolean; setIsModal: React.Dispatch<React.SetStateAction<boolean>>; + id: number; // reviewId 또는 gatheringId score?: number; comment?: string; } export default function MyReviewModal({ isModal, + id, setIsModal, score, comment, }: MyReviewModalProps) { const [updatedScore, setUpdatedScore] = useState<number>(score || 0); const [updatedComment, setUpdatedComment] = useState<string>(comment || ''); - const { toastMessage, toastVisible, toastType, handleError } = useToast(); + const { toastMessage, toastVisible, toastType, handleError, handleSuccess } = + useToast(); + const queryClient = useQueryClient(); + const closeModalhandler = () => { setIsModal(false); }; @@ -39,6 +47,45 @@ export default function MyReviewModal({ const isModified = (updatedComment?.trim() !== '' && comment !== updatedComment) || (updatedScore > 0 && score !== updatedScore); + + // score||comment가 있을 때의 id는 reviewId => 리뷰 수정 + const { mutate: editReview } = useMutation({ + mutationFn: async ({ + reviewId, + ...submissData + }: { reviewId: number } & EditReviewParams) => + editGatheringReview(reviewId, submissData), + onSuccess: () => { + handleSuccess('리뷰가 수정되었습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.error('editReview Error:', error); + handleError('리뷰 수정에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + + // score&&comment가 없을 때의 id는 gatheringId => 리뷰 작성 + const { mutate: writeReview } = useMutation({ + mutationFn: async (submissData: ReviewParams) => + postGatheringReview(submissData), + onSuccess: () => { + handleSuccess('리뷰를 작성했습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', false] }); + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.log('postReview Error:', error); + handleError('리뷰 작성에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + return ( <Modal isOpen={isModal} @@ -83,7 +130,22 @@ export default function MyReviewModal({ disabled={!isModified} className="w-full" onClick={() => { - handleError('아직 구현되지 않은 기능입니다.'); + // 리뷰 작성 + if (!(score && comment)) { + const submissionData = { + gatheringId: id, + score: updatedScore, + comment: updatedComment, + }; + writeReview(submissionData); + // 리뷰 수정 + } else { + editReview({ + reviewId: id, + score: updatedScore, + comment: updatedComment, + }); + } }} > 리뷰등록
Unknown
onSettled에 invalidateQuery를 사용해주셨는데 의도가 무엇인직 궁금합니다.
@@ -0,0 +1,18 @@ +import { useQuery } from '@tanstack/react-query'; +import { getMyGatheringJoined } from '@/axios/mypage/api'; +import { UserGatheringJoined } from '@/types/mypage.types'; + +export const UseReviews = ({ + reviewed, + offset = 0, + limit = 10, +}: { + reviewed: boolean; + offset?: number; + limit?: number; +}) => { + return useQuery<UserGatheringJoined[]>({ + queryKey: ['myReviews', reviewed, offset, limit], + queryFn: () => getMyGatheringJoined({ reviewed, offset, limit }), + }); +};
TypeScript
U 대문자 오타가 있네요.
@@ -7,23 +7,31 @@ import useToast from '@/hooks/useToast'; import TextArea from '@/components/@shared/input/TextArea'; import RatingInput from '@/components/@shared/rating/RatingInput'; import Toast from '@/components/@shared/Toast'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { EditReviewParams, ReviewParams } from '@/types/mypage.types'; +import { editGatheringReview, postGatheringReview } from '@/axios/mypage/api'; interface MyReviewModalProps { isModal: boolean; setIsModal: React.Dispatch<React.SetStateAction<boolean>>; + id: number; // reviewId 또는 gatheringId score?: number; comment?: string; } export default function MyReviewModal({ isModal, + id, setIsModal, score, comment, }: MyReviewModalProps) { const [updatedScore, setUpdatedScore] = useState<number>(score || 0); const [updatedComment, setUpdatedComment] = useState<string>(comment || ''); - const { toastMessage, toastVisible, toastType, handleError } = useToast(); + const { toastMessage, toastVisible, toastType, handleError, handleSuccess } = + useToast(); + const queryClient = useQueryClient(); + const closeModalhandler = () => { setIsModal(false); }; @@ -39,6 +47,45 @@ export default function MyReviewModal({ const isModified = (updatedComment?.trim() !== '' && comment !== updatedComment) || (updatedScore > 0 && score !== updatedScore); + + // score||comment가 있을 때의 id는 reviewId => 리뷰 수정 + const { mutate: editReview } = useMutation({ + mutationFn: async ({ + reviewId, + ...submissData + }: { reviewId: number } & EditReviewParams) => + editGatheringReview(reviewId, submissData), + onSuccess: () => { + handleSuccess('리뷰가 수정되었습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.error('editReview Error:', error); + handleError('리뷰 수정에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + + // score&&comment가 없을 때의 id는 gatheringId => 리뷰 작성 + const { mutate: writeReview } = useMutation({ + mutationFn: async (submissData: ReviewParams) => + postGatheringReview(submissData), + onSuccess: () => { + handleSuccess('리뷰를 작성했습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', false] }); + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.log('postReview Error:', error); + handleError('리뷰 작성에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + return ( <Modal isOpen={isModal} @@ -83,7 +130,22 @@ export default function MyReviewModal({ disabled={!isModified} className="w-full" onClick={() => { - handleError('아직 구현되지 않은 기능입니다.'); + // 리뷰 작성 + if (!(score && comment)) { + const submissionData = { + gatheringId: id, + score: updatedScore, + comment: updatedComment, + }; + writeReview(submissionData); + // 리뷰 수정 + } else { + editReview({ + reviewId: id, + score: updatedScore, + comment: updatedComment, + }); + } }} > 리뷰등록
Unknown
[myReviews, true]라면 리뷰를 작성한 모임이라는 뜻이고 [myReviews, false]라면 리뷰를 작성하지 않은 모임이라는 뜻입니다! 쿼리 함수는 hook파일인 src/hooks/useReviews.ts 사용하고 있습니다! 나의 리뷰 페이지에서 사용하고 있습니다!
@@ -7,23 +7,31 @@ import useToast from '@/hooks/useToast'; import TextArea from '@/components/@shared/input/TextArea'; import RatingInput from '@/components/@shared/rating/RatingInput'; import Toast from '@/components/@shared/Toast'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { EditReviewParams, ReviewParams } from '@/types/mypage.types'; +import { editGatheringReview, postGatheringReview } from '@/axios/mypage/api'; interface MyReviewModalProps { isModal: boolean; setIsModal: React.Dispatch<React.SetStateAction<boolean>>; + id: number; // reviewId 또는 gatheringId score?: number; comment?: string; } export default function MyReviewModal({ isModal, + id, setIsModal, score, comment, }: MyReviewModalProps) { const [updatedScore, setUpdatedScore] = useState<number>(score || 0); const [updatedComment, setUpdatedComment] = useState<string>(comment || ''); - const { toastMessage, toastVisible, toastType, handleError } = useToast(); + const { toastMessage, toastVisible, toastType, handleError, handleSuccess } = + useToast(); + const queryClient = useQueryClient(); + const closeModalhandler = () => { setIsModal(false); }; @@ -39,6 +47,45 @@ export default function MyReviewModal({ const isModified = (updatedComment?.trim() !== '' && comment !== updatedComment) || (updatedScore > 0 && score !== updatedScore); + + // score||comment가 있을 때의 id는 reviewId => 리뷰 수정 + const { mutate: editReview } = useMutation({ + mutationFn: async ({ + reviewId, + ...submissData + }: { reviewId: number } & EditReviewParams) => + editGatheringReview(reviewId, submissData), + onSuccess: () => { + handleSuccess('리뷰가 수정되었습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.error('editReview Error:', error); + handleError('리뷰 수정에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + + // score&&comment가 없을 때의 id는 gatheringId => 리뷰 작성 + const { mutate: writeReview } = useMutation({ + mutationFn: async (submissData: ReviewParams) => + postGatheringReview(submissData), + onSuccess: () => { + handleSuccess('리뷰를 작성했습니다!'); + closeModalhandler(); + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['myReviews', false] }); + queryClient.invalidateQueries({ queryKey: ['myReviews', true] }); + }, + onError: (error: any) => { + console.log('postReview Error:', error); + handleError('리뷰 작성에 실패하였습니다. 다시 시도해주세요.'); + }, + }); + return ( <Modal isOpen={isModal} @@ -83,7 +130,22 @@ export default function MyReviewModal({ disabled={!isModified} className="w-full" onClick={() => { - handleError('아직 구현되지 않은 기능입니다.'); + // 리뷰 작성 + if (!(score && comment)) { + const submissionData = { + gatheringId: id, + score: updatedScore, + comment: updatedComment, + }; + writeReview(submissionData); + // 리뷰 수정 + } else { + editReview({ + reviewId: id, + score: updatedScore, + comment: updatedComment, + }); + } }} > 리뷰등록
Unknown
리뷰 삭제 후 최신 데이터를 반영하기 위해서 사용했는데.. reactQuery를 사실 잘 모르는데 써보고 싶어서 사용해봤습니다! 강사님이 질문하셔서 onSettled를 확인해보니깐 onSettled를 사용하는 것보다는 onSucess에 invalidateQuery를 사용하는게 더 적절할것 같아서 코드 리팩토링을 해야할것 같습니다! 다시한번 상기시켜 주셔서 감사합니다!
@@ -0,0 +1,18 @@ +import { useQuery } from '@tanstack/react-query'; +import { getMyGatheringJoined } from '@/axios/mypage/api'; +import { UserGatheringJoined } from '@/types/mypage.types'; + +export const UseReviews = ({ + reviewed, + offset = 0, + limit = 10, +}: { + reviewed: boolean; + offset?: number; + limit?: number; +}) => { + return useQuery<UserGatheringJoined[]>({ + queryKey: ['myReviews', reviewed, offset, limit], + queryFn: () => getMyGatheringJoined({ reviewed, offset, limit }), + }); +};
TypeScript
감사합니다..
@@ -0,0 +1,30 @@ +package nextstep.security.context; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class SecurityContextHolderFilter extends GenericFilterBean { + private final SecurityContextRepository securityContextRepository = HttpSessionSecurityContextRepository.getInstance(); + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + try { + SecurityContextHolder.setContext( + securityContextRepository.loadContext((HttpServletRequest) request) + ); + chain.doFilter(request, response); + } finally { + SecurityContextHolder.clearContext(); + } + } +}
Java
chain.doFilter(request, response) 중 예외가 발생하면 clearContext()가 호출되지 않을 수 있겠네요 finally 블록에서 호출하도록 변경해보면 어떨까요? 😄
@@ -0,0 +1,9 @@ +package nextstep.security.exception; + +public class AuthenticationException extends RuntimeException { + public AuthenticationException() {} + + public AuthenticationException(String message) { + super(message); + } +}
Java
현재 `AuthenticationException`을 싱글턴 인스턴스로 미리 생성해두고 있는데요. 이 방식은 불필요한 객체 생성을 방지하고 일관된 예외 메시지 제공이라는 장점이 있지만, 스택 트레이스가 남지 않는다는 문제가 있습니다. 혹시 이 부분을 인지하고 계실까요? 😄
@@ -0,0 +1,24 @@ +package nextstep.security.authentication.manager; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.provider.AuthenticationProvider; +import nextstep.security.exception.AuthenticationProviderException; + +import java.util.List; + +public class ProviderManager implements AuthenticationManager { + private final List<AuthenticationProvider> providers; + + public ProviderManager(List<AuthenticationProvider> providers) { + this.providers = providers; + } + + @Override + public Authentication authenticate(Authentication authenticationToken) { + return providers.stream() + .filter(provider -> provider.supports(authenticationToken.getClass())) + .findFirst() + .orElseThrow(AuthenticationProviderException::new) + .authenticate(authenticationToken); + } +}
Java
소소하지만 다음과 같이 개행을 하면 좀더 가독성이 좋을 것 같아요 😄 ```suggestion @Override public Authentication authenticate(Authentication authenticationToken) { return providers.stream() .filter(provider -> provider.supports(authenticationToken.getClass())) .findFirst() .orElseThrow(AuthenticationException::notSupported) .authenticate(authenticationToken); } ```
@@ -0,0 +1,9 @@ +package nextstep.security.exception; + +public class AuthenticationException extends RuntimeException { + public AuthenticationException() {} + + public AuthenticationException(String message) { + super(message); + } +}
Java
앗 스택 트레이스 부분을 생각을 못했네요. [394ed26](https://github.com/next-step/spring-security-authentication/pull/28/commits/394ed26a7c3b3dea8c17c1192cbed19393315d0f) 커밋에서 매번 새로운 객체를 생성하도록 수정했습니다. 하는 김에 커스텀 예외를 더 세분화할 수 있도록 하였습니다.
@@ -0,0 +1,24 @@ +package nextstep.security.authentication.manager; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.provider.AuthenticationProvider; +import nextstep.security.exception.AuthenticationProviderException; + +import java.util.List; + +public class ProviderManager implements AuthenticationManager { + private final List<AuthenticationProvider> providers; + + public ProviderManager(List<AuthenticationProvider> providers) { + this.providers = providers; + } + + @Override + public Authentication authenticate(Authentication authenticationToken) { + return providers.stream() + .filter(provider -> provider.supports(authenticationToken.getClass())) + .findFirst() + .orElseThrow(AuthenticationProviderException::new) + .authenticate(authenticationToken); + } +}
Java
[58614f1](https://github.com/next-step/spring-security-authentication/pull/28/commits/58614f1d4af41421b2f16d76eb1323fbf34c3bf9) 커밋에서 indentation 스타일 변경 반영했습니다.
@@ -0,0 +1,30 @@ +package nextstep.security.context; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class SecurityContextHolderFilter extends GenericFilterBean { + private final SecurityContextRepository securityContextRepository = HttpSessionSecurityContextRepository.getInstance(); + + @Override + public void doFilter( + ServletRequest request, + ServletResponse response, + FilterChain chain + ) throws IOException, ServletException { + try { + SecurityContextHolder.setContext( + securityContextRepository.loadContext((HttpServletRequest) request) + ); + chain.doFilter(request, response); + } finally { + SecurityContextHolder.clearContext(); + } + } +}
Java
앗 정말로 그렇겠네요. Filter 에서 예외처리 때문에 고생한적이 있는데, 지적해주셔서 감사합니다! ❤️ 항상 동작해야하는 로직은 finally 문법 활용하는 습관을 가져야겠네요. 실무에서 당장 활용해야겠다는 생각이 드는 유용한 피드백 감사합니다. [9e5ef93](https://github.com/next-step/spring-security-authentication/pull/28/commits/9e5ef934299204a6fd37b266e7dbb52f0e2b294a) 커밋에서 finally 블록에서 clearContext 가 호출되도록 변경했습니다!
@@ -0,0 +1,41 @@ +package nextstep.security.authentication.token; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.exception.AuthenticationTokenException; + +import java.util.Base64; + +import static org.springframework.http.HttpHeaders.AUTHORIZATION; + +public class BasicAuthenticationTokenConverter implements AuthenticationTokenConverter { + private BasicAuthenticationTokenConverter() {} + + public static AuthenticationTokenConverter getInstance() { + return SingletonHolder.INSTANCE; + } + + @Override + public Authentication convert(HttpServletRequest request) { + try { + final byte[] decoded = Base64.getDecoder().decode( + request.getHeader(AUTHORIZATION).trim().split(" ")[1] + ); + final String[] usernameAndPassword = new String(decoded).split(":"); + return new UsernamePasswordAuthenticationToken(usernameAndPassword[0], usernameAndPassword[1]); + } catch (Exception e) { + throw new AuthenticationTokenException(); + } + } + + @Override + public boolean supports(HttpServletRequest request) { + final String authorizationHeader = request.getHeader(AUTHORIZATION); + return authorizationHeader != null + && authorizationHeader.trim().startsWith("Basic "); + } + + private static final class SingletonHolder { + private static final BasicAuthenticationTokenConverter INSTANCE = new BasicAuthenticationTokenConverter(); + } +}
Java
`HttpHeaders.AUTHORIZATION`를 사용할 수 있을 것 같네요 😄
@@ -0,0 +1,41 @@ +package nextstep.security.authentication.token; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.exception.AuthenticationTokenException; + +import java.util.Base64; + +import static org.springframework.http.HttpHeaders.AUTHORIZATION; + +public class BasicAuthenticationTokenConverter implements AuthenticationTokenConverter { + private BasicAuthenticationTokenConverter() {} + + public static AuthenticationTokenConverter getInstance() { + return SingletonHolder.INSTANCE; + } + + @Override + public Authentication convert(HttpServletRequest request) { + try { + final byte[] decoded = Base64.getDecoder().decode( + request.getHeader(AUTHORIZATION).trim().split(" ")[1] + ); + final String[] usernameAndPassword = new String(decoded).split(":"); + return new UsernamePasswordAuthenticationToken(usernameAndPassword[0], usernameAndPassword[1]); + } catch (Exception e) { + throw new AuthenticationTokenException(); + } + } + + @Override + public boolean supports(HttpServletRequest request) { + final String authorizationHeader = request.getHeader(AUTHORIZATION); + return authorizationHeader != null + && authorizationHeader.trim().startsWith("Basic "); + } + + private static final class SingletonHolder { + private static final BasicAuthenticationTokenConverter INSTANCE = new BasicAuthenticationTokenConverter(); + } +}
Java
[65922ab](https://github.com/next-step/spring-security-authentication/pull/28/commits/65922ab2a9189e06adb07bd8950a96416d723db0) 커밋에서 반영 완료했습니다!
@@ -0,0 +1,6 @@ +package racingcar; + +public interface RacingNumberGenerator { + + int generate(); +}
Java
다리 미션에서 이 인터페이스를 함수형인터페이스로 구현을 하더라구요. `@FunctionalInterface` 어노테이션을 붙여서 한번쯤, 고려해볼만 한 것 같아, 관련 포스팅 링크 남겨놓습니다! https://codechacha.com/ko/java8-functional-interface/
@@ -0,0 +1,47 @@ +package racingcar.model; + +public class Car implements Comparable<Car> { + private static final int MOVABLE_LOWER_BOUND = 4; + + private final CarName name; + private final Position position = Position.init(); + + private Car(String name) { + this.name = CarName.from(name); + } + + public static Car from(String name) { + return new Car(name); + } + + public void move(int command) { + if (isMovable(command)) { + position.increase(); + } + } + + private static boolean isMovable(int command) { + return command >= MOVABLE_LOWER_BOUND; + } + + public boolean isAt(Position expectedPosition) { + return position.equals(expectedPosition); + } + + public int getPosition() { + return position.getPosition(); + } + + public CarName getName() { + return name; + } + + public boolean isSamePosition(Car other) { + return this.position.equals(other.position); + } + + @Override + public int compareTo(Car other) { + return this.position.compareTo(other.position); + } +}
Java
와 이거 충격적인데요... Comparable<Car>를 통해 Car 클래스를 정의하신 거 진짜 아이디어 좋네요. 배워 갑니다!
@@ -0,0 +1,48 @@ +package racingcar.model; + +import java.util.Objects; + +public class Position implements Comparable<Position> { + + private static final int STARTING_POSITION = 0; + + private int position; + + public Position(int position) { + this.position = position; + } + + public static Position from(int position) { + return new Position(position); + } + + public static Position init() { + return new Position(STARTING_POSITION); + } + + public void increase() { + position++; + } + + public int getPosition() { + return position; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Position position1 = (Position) o; + return position == position1.position; + } + + @Override + public int hashCode() { + return Objects.hash(position); + } + + @Override + public int compareTo(Position other) { + return this.position - other.position; + } +}
Java
Position을 일급객체화할 필요가 있나?에 대한 의문이 듭니다. Car 객체의 int 필드로 선언해도 충분해 보여서요. 생성시 validation이 필요한 것도 아니고, 초기값 설정도 Car 객체에서 충분히 가능하고, Car에서 compareTo를 오버라이딩할 때, Car에 대한 getter만 설정한다면 메소드 구현이 가능하다고 생각합니다. 혹 다른 의도가 있거나, 제 생각이 틀렸다면 피드백 부탁드립니다:)
@@ -0,0 +1,65 @@ +package racingcar.model; + +import racingcar.RacingNumberGenerator; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DUPLICATED_CAR_NAMES = "자동차들의 이름은 서로 중복될 수 없습니다."; + + private final List<Car> cars; + + private Cars(List<String> names) { + validate(names); + cars = toCars(names); + } + + private List<Car> toCars(List<String> names) { + return names.stream() + .map(Car::from) + .collect(Collectors.toList()); + } + + private void validate(List<String> names) { + if (isDuplicated(names)) { + throw new IllegalArgumentException(DUPLICATED_CAR_NAMES); + } + } + + private boolean isDuplicated(List<String> names) { + Set<String> uniqueNames = new HashSet<>(names); + + return uniqueNames.size() != names.size(); + } + + public static Cars from(List<String> names) { + return new Cars(names); + } + + public void race(RacingNumberGenerator numberGenerator) { + cars.forEach(car -> car.move(numberGenerator.generate())); + } + + public List<CarName> findWinners() { + Car maxPositionCar = getCarWithMaxPosition(); + return cars.stream() + .filter(maxPositionCar::isSamePosition) + .map(Car::getName) + .collect(Collectors.toList()); + } + + private Car getCarWithMaxPosition() { + return cars.stream() + .max(Car::compareTo) + .orElseThrow(() -> new IllegalArgumentException("차량 리스트가 비어있습니다.")); + } + + public List<Car> get() { + return Collections.unmodifiableList(cars); + } +}
Java
from이라는 메소드가 모든 클래스에서 반복되는데, Cars.from(names)이런 식으로 연결된 경우 의미가 드러나지만 메소드 이름이란 결국 객체에게 보내는 메세지라는 관점에서는 'from'이라는 메소드 이름만 볼 경우 어떤 용도인지 알기 힘든게 사실인것 같습니다. `setNewCars()`등등 적절하게 메소드명을 바꿔보시면 어떨까 생각해보았습니다.ㅎㅎ
@@ -0,0 +1,24 @@ +package racingcar.model; + +public class AttemptCount { + + private static final int IS_OVER = 0; + + private int count; + + public AttemptCount(int count) { + this.count = count; + } + + public static AttemptCount from(int count) { + return new AttemptCount(count); + } + + public boolean isPlayable() { + return count > IS_OVER; + } + + public void decrease() { + count--; + } +}
Java
AttemptCount 클래스는 시도 횟수에 대한 일급 객체로서의 성격보다, RacingGame의 전체 코드 흐름을 제어하는 역할을 하는 것 같습니다. isPlayable 메소드를 통해 게임 진행여부를 판단해 looping을 어디까지 돌 지 판단해주는 것이 핵심이니까요. `RacingGame`등으로 클래스명을 바꾸고, attemptCount를 인스턴스 필드화 해보면 어떨까요?ㅎㅎ
@@ -0,0 +1,24 @@ +package racingcar.model; + +public class AttemptCount { + + private static final int IS_OVER = 0; + + private int count; + + public AttemptCount(int count) { + this.count = count; + } + + public static AttemptCount from(int count) { + return new AttemptCount(count); + } + + public boolean isPlayable() { + return count > IS_OVER; + } + + public void decrease() { + count--; + } +}
Java
저도 사용하면서 찝찝했는데 `RacingGame` 객체로 게임을 진행하는 역할을 분리해봐야겠네요...! 좋은 지적 감사합니다!
@@ -0,0 +1,47 @@ +package racingcar.model; + +public class Car implements Comparable<Car> { + private static final int MOVABLE_LOWER_BOUND = 4; + + private final CarName name; + private final Position position = Position.init(); + + private Car(String name) { + this.name = CarName.from(name); + } + + public static Car from(String name) { + return new Car(name); + } + + public void move(int command) { + if (isMovable(command)) { + position.increase(); + } + } + + private static boolean isMovable(int command) { + return command >= MOVABLE_LOWER_BOUND; + } + + public boolean isAt(Position expectedPosition) { + return position.equals(expectedPosition); + } + + public int getPosition() { + return position.getPosition(); + } + + public CarName getName() { + return name; + } + + public boolean isSamePosition(Car other) { + return this.position.equals(other.position); + } + + @Override + public int compareTo(Car other) { + return this.position.compareTo(other.position); + } +}
Java
순수 제 아이디어는 아니구... **Tecoble** 에서 `getter()` 에 관련된 내용을 읽다가 알게 된 내용을 그대로 적용해본 거에요... 하하... 저도 처음 이 아이디어를 접하고 충격을 많이 받았습니다 ㅎ - [getter() 를 사용하는 대신 객체에 메시지를 보내지](https://tecoble.techcourse.co.kr/post/2020-04-28-ask-instead-of-getter/) - [Comparator 와 Comparable 의 이해](https://st-lab.tistory.com/243) 너무 좋은 자료들이라 한번 읽어보시는 거 강력히 추천드립니다!!
@@ -0,0 +1,65 @@ +package racingcar.model; + +import racingcar.RacingNumberGenerator; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DUPLICATED_CAR_NAMES = "자동차들의 이름은 서로 중복될 수 없습니다."; + + private final List<Car> cars; + + private Cars(List<String> names) { + validate(names); + cars = toCars(names); + } + + private List<Car> toCars(List<String> names) { + return names.stream() + .map(Car::from) + .collect(Collectors.toList()); + } + + private void validate(List<String> names) { + if (isDuplicated(names)) { + throw new IllegalArgumentException(DUPLICATED_CAR_NAMES); + } + } + + private boolean isDuplicated(List<String> names) { + Set<String> uniqueNames = new HashSet<>(names); + + return uniqueNames.size() != names.size(); + } + + public static Cars from(List<String> names) { + return new Cars(names); + } + + public void race(RacingNumberGenerator numberGenerator) { + cars.forEach(car -> car.move(numberGenerator.generate())); + } + + public List<CarName> findWinners() { + Car maxPositionCar = getCarWithMaxPosition(); + return cars.stream() + .filter(maxPositionCar::isSamePosition) + .map(Car::getName) + .collect(Collectors.toList()); + } + + private Car getCarWithMaxPosition() { + return cars.stream() + .max(Car::compareTo) + .orElseThrow(() -> new IllegalArgumentException("차량 리스트가 비어있습니다.")); + } + + public List<Car> get() { + return Collections.unmodifiableList(cars); + } +}
Java
정적 팩토리 메서드 네이밍에 컨벤션이 존재한다고 알고있습니다! 저도 개인적으로는 적절한 이름을 지어주는 것이 좋다고 생각합니다. 하지만 컨벤션이니까...! 컨벤션을 지키는 방향으로 진행하고 있어요... - [정적 팩토리 메서드의 네이밍 방식](https://velog.io/@saint6839/%EC%A0%95%EC%A0%81-%ED%8C%A9%ED%86%A0%EB%A6%AC-%EB%A9%94%EC%84%9C%EB%93%9C-%EB%84%A4%EC%9D%B4%EB%B0%8D-%EB%B0%A9%EC%8B%9D)
@@ -0,0 +1,48 @@ +package racingcar.model; + +import java.util.Objects; + +public class Position implements Comparable<Position> { + + private static final int STARTING_POSITION = 0; + + private int position; + + public Position(int position) { + this.position = position; + } + + public static Position from(int position) { + return new Position(position); + } + + public static Position init() { + return new Position(STARTING_POSITION); + } + + public void increase() { + position++; + } + + public int getPosition() { + return position; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Position position1 = (Position) o; + return position == position1.position; + } + + @Override + public int hashCode() { + return Objects.hash(position); + } + + @Override + public int compareTo(Position other) { + return this.position - other.position; + } +}
Java
말씀해주신 대로 현재 미션에서는 굳이 일급 객체화할 필요가 없다는 것에 동의합니다. 나열해주신 근거들도 모두 타당하다고 생각해요..! 다만 미션을 진행하면서 최대한 객체지향 생활 체조 원칙들을 지키면서 구현해보는 것을 목표로 하고 있어요. (객체지향 생활 체조 원칙에 **모든 원시 값과 문자열을 포장한다.** 라는 항목이 있더라구요!) 일종의 연습이라고 봐주시면 될 것 같습니다! 원시 값을 포장하는 것이 추후에 요구사항이 변했을 때 유지 보수에도 큰 이점이 있다는 것을 고려해서 억지로라도 Wrapping 하려고 노력하고 있습니다... - [원시 타입을 포장해야 하는 이유](https://tecoble.techcourse.co.kr/post/2020-05-29-wrap-primitive-type/)
@@ -0,0 +1,6 @@ +package racingcar; + +public interface RacingNumberGenerator { + + int generate(); +}
Java
와 좋은 자료 감사합니다! 최근에 람다를 학습하면서 함수형 인터페이스도 함께 공부했었는데 직접 활용해볼 생각은 못해봤네요. 지금 당장 리팩토링 해봐야겠습니다! 감사합니다!!
@@ -0,0 +1,57 @@ +package racingcar.view; + +import racingcar.model.Car; +import racingcar.model.CarName; +import racingcar.model.Cars; + +import java.util.List; +import java.util.stream.Collectors; + +public class OutputView { + + private static final String NEW_LINE = "\n"; + private static final String SCORE_UNIT = "-"; + private static final String SCORE_BOARD = "%s : %s"; + private static final String WINNER_SEPARATOR = ", "; + private static final String WINNERS_ARE = "최종 우승자 : "; + private static final String ERROR_PREFIX = "[ERROR] "; + private static final String RESULT_INTRO = "실행 결과"; + + public void printResult(Cars cars) { + System.out.println(getScore(cars)); + } + + private String getScore(Cars cars) { + return cars.get().stream() + .map(this::toScoreBoard) + .collect(Collectors.joining(NEW_LINE)); + } + + private String toScoreBoard(Car car) { + return String.format(SCORE_BOARD, car.getName(), convertToScore(car.getPosition())); + } + + private String convertToScore(int position) { + return SCORE_UNIT.repeat(position); + } + + public void printWinners(List<CarName> winners) { + System.out.print(WINNERS_ARE); + System.out.println(getWinnerNames(winners)); + } + + private String getWinnerNames(List<CarName> winners) { + return winners.stream() + .map(CarName::get) + .collect(Collectors.joining(WINNER_SEPARATOR)); + } + + public void printError(IllegalArgumentException error) { + System.out.print(ERROR_PREFIX); + System.out.println(error.getMessage()); + } + + public void printRaceIntro() { + System.out.println(RESULT_INTRO); + } +}
Java
이 부분은 메세지 부분이라 view에서 처리하신 것 같은데, 이 경우 `cars`가 직접 처리하는 것이 아닌 직접 꺼내와서 처리하는 것인 것 같아서 차라리 메시지를 `cars`에서 처리하는 게 더 객체를 독립적으로 만드는 게 아닐까 하는 생각이 드네요!
@@ -0,0 +1,37 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; +import racingcar.model.AttemptCount; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class InputView { + + private static final String SPLIT_REGEX = ","; + private static final String NON_NUMERIC_INPUT_MESSAGE = "숫자만 입력할 수 있습니다."; + private static final String REQUEST_ATTEMPT_COUNT_MESSAGE = "시도할 회수는 몇회인가요?"; + + public List<String> readNames() { + String names = Console.readLine(); + + return Arrays.stream(names.split(SPLIT_REGEX)) + .collect(Collectors.toList()); + } + + public AttemptCount readAttemptCount() { + System.out.println(REQUEST_ATTEMPT_COUNT_MESSAGE); + String attemptCount = Console.readLine(); + + return AttemptCount.from(parseInt(attemptCount)); + } + + private int parseInt(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException error) { + throw new IllegalArgumentException(NON_NUMERIC_INPUT_MESSAGE); + } + } +}
Java
이러한 메시지들을 일일이 상수처리하면 나중에 규모가 커졌을 때, 관리하기 힘들어진다고 합니다. 재사용되지 않는 메시지들은 직접 값에 담아보는 건 어떨까요?
@@ -0,0 +1,24 @@ +package racingcar.model; + +public class AttemptCount { + + private static final int IS_OVER = 0; + + private int count; + + public AttemptCount(int count) { + this.count = count; + } + + public static AttemptCount from(int count) { + return new AttemptCount(count); + } + + public boolean isPlayable() { + return count > IS_OVER; + } + + public void decrease() { + count--; + } +}
Java
저도 많이 배워가네요 감사합니다 :D
@@ -0,0 +1,47 @@ +package racingcar.model; + +public class Car implements Comparable<Car> { + private static final int MOVABLE_LOWER_BOUND = 4; + + private final CarName name; + private final Position position = Position.init(); + + private Car(String name) { + this.name = CarName.from(name); + } + + public static Car from(String name) { + return new Car(name); + } + + public void move(int command) { + if (isMovable(command)) { + position.increase(); + } + } + + private static boolean isMovable(int command) { + return command >= MOVABLE_LOWER_BOUND; + } + + public boolean isAt(Position expectedPosition) { + return position.equals(expectedPosition); + } + + public int getPosition() { + return position.getPosition(); + } + + public CarName getName() { + return name; + } + + public boolean isSamePosition(Car other) { + return this.position.equals(other.position); + } + + @Override + public int compareTo(Car other) { + return this.position.compareTo(other.position); + } +}
Java
저도 여기서 놀랐는데 덕분에 좋은 컨텐츠들을 배워가네요 감사합니다!
@@ -0,0 +1,44 @@ +package racingcar.model; + +import org.junit.jupiter.api.DisplayNameGeneration; +import org.junit.jupiter.api.DisplayNameGenerator; +import org.junit.jupiter.api.Test; +import racingcar.RacingNumberGenerator; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.util.Lists.newArrayList; + +@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) +public class CarsTest { + + @Test + void 자동차들의_이름은_서로_중복될_수_없다() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Cars.from(List.of("pobi,jun,pobi"))); + } + + @Test + void 가장_멀리_이동한_사림이_우승한다() { + Cars cars = Cars.from(List.of("pobi", "jun", "khj")); + TestRacingNumberGenerator numberGenerator = new TestRacingNumberGenerator(); + + cars.race(numberGenerator); + cars.race(numberGenerator); + + assertThat(cars.findWinners()) + .contains(CarName.from("pobi"), CarName.from("khj")); + } + + static class TestRacingNumberGenerator implements RacingNumberGenerator { + + private final List<Integer> numbers = newArrayList(4, 1, 4, 4, 1, 4); + + @Override + public int generate() { + return numbers.remove(0); + } + } +}
Java
이 부분은 `RacingNumberGenerator`라고 함수형 인터페이스로 이미 정의해 두셨으니 직접 구현할 필요 없이 간단하게 람다로 처리가 가능할 것 같습니다!
@@ -0,0 +1,44 @@ +package racingcar.model; + +import org.junit.jupiter.api.DisplayNameGeneration; +import org.junit.jupiter.api.DisplayNameGenerator; +import org.junit.jupiter.api.Test; +import racingcar.RacingNumberGenerator; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.util.Lists.newArrayList; + +@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) +public class CarsTest { + + @Test + void 자동차들의_이름은_서로_중복될_수_없다() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Cars.from(List.of("pobi,jun,pobi"))); + } + + @Test + void 가장_멀리_이동한_사림이_우승한다() { + Cars cars = Cars.from(List.of("pobi", "jun", "khj")); + TestRacingNumberGenerator numberGenerator = new TestRacingNumberGenerator(); + + cars.race(numberGenerator); + cars.race(numberGenerator); + + assertThat(cars.findWinners()) + .contains(CarName.from("pobi"), CarName.from("khj")); + } + + static class TestRacingNumberGenerator implements RacingNumberGenerator { + + private final List<Integer> numbers = newArrayList(4, 1, 4, 4, 1, 4); + + @Override + public int generate() { + return numbers.remove(0); + } + } +}
Java
```java cars.race(() -> new Integer[]{4, 1, 4, 4, 1, 4}) ``` 이런 느낌으로요!
@@ -0,0 +1,65 @@ +package racingcar.model; + +import racingcar.RacingNumberGenerator; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class Cars { + + private static final String DUPLICATED_CAR_NAMES = "자동차들의 이름은 서로 중복될 수 없습니다."; + + private final List<Car> cars; + + private Cars(List<String> names) { + validate(names); + cars = toCars(names); + } + + private List<Car> toCars(List<String> names) { + return names.stream() + .map(Car::from) + .collect(Collectors.toList()); + } + + private void validate(List<String> names) { + if (isDuplicated(names)) { + throw new IllegalArgumentException(DUPLICATED_CAR_NAMES); + } + } + + private boolean isDuplicated(List<String> names) { + Set<String> uniqueNames = new HashSet<>(names); + + return uniqueNames.size() != names.size(); + } + + public static Cars from(List<String> names) { + return new Cars(names); + } + + public void race(RacingNumberGenerator numberGenerator) { + cars.forEach(car -> car.move(numberGenerator.generate())); + } + + public List<CarName> findWinners() { + Car maxPositionCar = getCarWithMaxPosition(); + return cars.stream() + .filter(maxPositionCar::isSamePosition) + .map(Car::getName) + .collect(Collectors.toList()); + } + + private Car getCarWithMaxPosition() { + return cars.stream() + .max(Car::compareTo) + .orElseThrow(() -> new IllegalArgumentException("차량 리스트가 비어있습니다.")); + } + + public List<Car> get() { + return Collections.unmodifiableList(cars); + } +}
Java
숫자 생성하는 부분을 생성자가 아닌 `race`에서 주입받을 수도 있네요! 하나 배워갑니다
@@ -0,0 +1,44 @@ +package racingcar.model; + +import org.junit.jupiter.api.DisplayNameGeneration; +import org.junit.jupiter.api.DisplayNameGenerator; +import org.junit.jupiter.api.Test; +import racingcar.RacingNumberGenerator; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.util.Lists.newArrayList; + +@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) +public class CarsTest { + + @Test + void 자동차들의_이름은_서로_중복될_수_없다() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Cars.from(List.of("pobi,jun,pobi"))); + } + + @Test + void 가장_멀리_이동한_사림이_우승한다() { + Cars cars = Cars.from(List.of("pobi", "jun", "khj")); + TestRacingNumberGenerator numberGenerator = new TestRacingNumberGenerator(); + + cars.race(numberGenerator); + cars.race(numberGenerator); + + assertThat(cars.findWinners()) + .contains(CarName.from("pobi"), CarName.from("khj")); + } + + static class TestRacingNumberGenerator implements RacingNumberGenerator { + + private final List<Integer> numbers = newArrayList(4, 1, 4, 4, 1, 4); + + @Override + public int generate() { + return numbers.remove(0); + } + } +}
Java
저도 피드백 받고 난 뒤 람다로 표현해보려고 했는데 `TestRacingNumberGenerator` 처럼 내부에 상태가 필요한 경우엔 온전히 람다로 표현하는게 힘들더라구요! 만약 람다로 처리하려면 ```java cars.race(() -> newArrayList(4, 1, 4, 4, 1, 4).remove(0)); ``` 과 같은 형태로 사용해야 하는데 이렇게 되면 일단 가독성이 너무 떨어지더라구요. 무엇보다도 `race()` 를 여러 번 반복하더라도 항상 *List*가 초기화 되기 때문에 항상 같은 값만 반복하게 되기도 하구요. ```java cars.race(() -> newArrayList(4, 1, 4, 4, 1, 4).remove(0)); // 4 반환 cars.race(() -> newArrayList(4, 1, 4, 4, 1, 4).remove(0)); // 4 반환 ``` [Functional Interface 란?](https://tecoble.techcourse.co.kr/post/2020-07-17-Functional-Interface/) 을 읽어보니 다음과 같은 대목이 있더라구요! ``` 함수형 개발 방식은 행위에 해당하는 부분도 값으로 취급이 가능해 졌다는 것인데 자바에서 의미하는 기본형의 데이터(Integer 나 String)만 값이 아니라 행위(로직)도 값으로 취급할 수 있게 되었다는 이야기입니다. 이것은 자바가 코드의 재활용 단위가 클래스였던 것이 함수 단위로 재사용이 가능해 지면서 조금 더 개발을 유연하게 할 수 있게 된 점이라고 할 수 있습니다. ``` 함수형 인터페이스의 대상이 되는 것은 클래스에 종속 되어있는 (제가 느끼기엔 상태와 묶여있는) **메서드**가 아니라 오로지 행위 만을 다루고 있는 **함수** 뿐인 것 같습니다. (그러고 보니 이름도 **함수형** 인터페이스네요...) 분명 전에 함수형 인터페이스를 학습했었는데 함수와 메서드의 차이를 생각하지 않고 사용하려고 했네요 흑... 서경님 덕분에 저도 함수형 인터페이스에 대해서 좀 더 명료하게 이해하게 되는 계기가 되었습니다. 좋은 지적 감사드려요!!! :)
@@ -0,0 +1,57 @@ +package racingcar.view; + +import racingcar.model.Car; +import racingcar.model.CarName; +import racingcar.model.Cars; + +import java.util.List; +import java.util.stream.Collectors; + +public class OutputView { + + private static final String NEW_LINE = "\n"; + private static final String SCORE_UNIT = "-"; + private static final String SCORE_BOARD = "%s : %s"; + private static final String WINNER_SEPARATOR = ", "; + private static final String WINNERS_ARE = "최종 우승자 : "; + private static final String ERROR_PREFIX = "[ERROR] "; + private static final String RESULT_INTRO = "실행 결과"; + + public void printResult(Cars cars) { + System.out.println(getScore(cars)); + } + + private String getScore(Cars cars) { + return cars.get().stream() + .map(this::toScoreBoard) + .collect(Collectors.joining(NEW_LINE)); + } + + private String toScoreBoard(Car car) { + return String.format(SCORE_BOARD, car.getName(), convertToScore(car.getPosition())); + } + + private String convertToScore(int position) { + return SCORE_UNIT.repeat(position); + } + + public void printWinners(List<CarName> winners) { + System.out.print(WINNERS_ARE); + System.out.println(getWinnerNames(winners)); + } + + private String getWinnerNames(List<CarName> winners) { + return winners.stream() + .map(CarName::get) + .collect(Collectors.joining(WINNER_SEPARATOR)); + } + + public void printError(IllegalArgumentException error) { + System.out.print(ERROR_PREFIX); + System.out.println(error.getMessage()); + } + + public void printRaceIntro() { + System.out.println(RESULT_INTRO); + } +}
Java
말씀해주신 대로 *UI* 를 다루는 로직을 도메인 내부에서 처리하는 것이 마음에 걸리더라구요... *UI* 요구사항이 변하면 도메인 내부에도 변화가 강제된다 는 게 오히려 객체 독립성을 해친다고 생각했습니다. 그래서 객체를 직접 꺼내오는 대신 다음과 같이 불변 객체로 리스트를 반환하도록 처리해주었습니다. ```java public List<Car> get() { return Collections.unmodifiableList(cars); } ``` 그래도 역시 일급 컬렉션 내의 상태를 직접 꺼내와서 사용하는 게 너무 찝찝하긴 하더라구요... 제 개인적인 생각을 더 자세하게 말씀드리겠습니다. 저는 *UI* 로직을 도메인에 통합하는 것 보다는 `getter()` 를 사용하는 것이 오히려 더 낫다고 판단했습니다. 미션을 진행하면서 저는 `getter()`를 무조건적으로 배제하는게 너무 힘들더라구요... 두 객체를 비교하거나, 진위 여부를 판단하는 로직에서는 메시지만으로도 충분히 구현할 수 있었지만, 두 객체의 값으로 연산을 해야 한다거나, 객체 내부의 값을 출력해야 하는 경우엔 `getter()`를 사용하는 게 오히려 더 효율적이라고 생각했습니다. 그래서 `getter()`를 최대한 지양하는 이유 즉, 캡슐화를 위반하진 않는지, 불변성을 해치진 않는지를 계속 의식하면서 안전하게 `getter()`를 사용해보려고 노력하고 있습니다. 혹시 서경님은 `getter()`를 사용하는 것 보다 UI 로직을 도메인 내부에서 구현하는 것 이 더 합리적이라고 생각하신 또 다른 이유가 있나요? 궁금합니다!
@@ -0,0 +1,37 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; +import racingcar.model.AttemptCount; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class InputView { + + private static final String SPLIT_REGEX = ","; + private static final String NON_NUMERIC_INPUT_MESSAGE = "숫자만 입력할 수 있습니다."; + private static final String REQUEST_ATTEMPT_COUNT_MESSAGE = "시도할 회수는 몇회인가요?"; + + public List<String> readNames() { + String names = Console.readLine(); + + return Arrays.stream(names.split(SPLIT_REGEX)) + .collect(Collectors.toList()); + } + + public AttemptCount readAttemptCount() { + System.out.println(REQUEST_ATTEMPT_COUNT_MESSAGE); + String attemptCount = Console.readLine(); + + return AttemptCount.from(parseInt(attemptCount)); + } + + private int parseInt(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException error) { + throw new IllegalArgumentException(NON_NUMERIC_INPUT_MESSAGE); + } + } +}
Java
제가 생각했을 때 상수를 사용하는 이유에는 - 클래스 간, 메서드 간 값을 재사용하는 측면도 있지만 - **인스턴스 간에 값을 공유**하는 측면도 있다고 알고 있습니다! - (이름을 지어줌으로써 가독성을 고려하는 측면도 있구요!) `InputView` 에서 사용되는 에러 메시지들 같은 경우 인스턴스의 상태와 무관하게 항상 값이 고정되어 있습니다. 이런 경우 하드코딩된 값을 `static final` 로 선언해주면 프로그램 실행 단계에서 딱 한번만 초기화되기 때문에 서로 다른 인스턴스를 여러 번 호출하더라도 인스턴스와 함께 매번 초기화해 줄 필요가 없어지게 됩니다. 그래서 메모리 적으로도 더 효율적이라고 생각해요! (숫자 야구 피드백 영상에서 클래스 변수와 인스턴스 변수의 차이를 떠올리시면 될 것 같아요!!) 이러한 이유에서 저는 하드코딩된 값은 무조건 상수 처리 해버리자! 라는 주의로 프로그래밍 하고있습니다. 자동차 경주 미션에서는 `InputView` 가 여러번 초기화 될 가능성이 거의 없지만 그렇다 하더라도 하드코딩 된 값을 최대한 상수로 처리하는 습관을 들이려고 노력이라고 이해해주시면 될 것 같아요! 혹여나 규모가 커진다면 `InputView` 클래스를 세부 클래스들로 나누는 것도 괜찮은 방법일 것 같아요! 그렇게 되면 클래스가 관련된 상수를 함께 관리할 수 있기 때문에 유지보수 측면에서도 더 유리하다고 생각합니다!
@@ -0,0 +1,37 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; +import racingcar.model.AttemptCount; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class InputView { + + private static final String SPLIT_REGEX = ","; + private static final String NON_NUMERIC_INPUT_MESSAGE = "숫자만 입력할 수 있습니다."; + private static final String REQUEST_ATTEMPT_COUNT_MESSAGE = "시도할 회수는 몇회인가요?"; + + public List<String> readNames() { + String names = Console.readLine(); + + return Arrays.stream(names.split(SPLIT_REGEX)) + .collect(Collectors.toList()); + } + + public AttemptCount readAttemptCount() { + System.out.println(REQUEST_ATTEMPT_COUNT_MESSAGE); + String attemptCount = Console.readLine(); + + return AttemptCount.from(parseInt(attemptCount)); + } + + private int parseInt(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException error) { + throw new IllegalArgumentException(NON_NUMERIC_INPUT_MESSAGE); + } + } +}
Java
오호 좋은 습관인 것 같아요 ㅎㅎ 하드코딩된 값을 사용하지 않다가 사용하는 건 일일이 의식하기 힘들지만, 상수를 사용하는 식으로 코딩하다가 값을 직접 쓰는 방식으로 전환하기 쉬울 테니까요 이러한 피드백을 드린 이유는 프리코스 외에 인턴했던 회사에서 `예외 메세지에 상수 값을 직접 다 받을 경우 상수를 무분별하게 많이 사용하게 돼서 코드를 읽을 때 정작 무엇이 중요한지 판별하기 힘들어지고 코드가 길어진다는 문제점이 발생한다` 라는 피드백을 받았기 때문인데요 말씀하신 것처럼 연습의 과정이라면 오히려 좋은 신호겠네요! 😃
@@ -0,0 +1,44 @@ +package racingcar.model; + +import org.junit.jupiter.api.DisplayNameGeneration; +import org.junit.jupiter.api.DisplayNameGenerator; +import org.junit.jupiter.api.Test; +import racingcar.RacingNumberGenerator; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.util.Lists.newArrayList; + +@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) +public class CarsTest { + + @Test + void 자동차들의_이름은_서로_중복될_수_없다() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Cars.from(List.of("pobi,jun,pobi"))); + } + + @Test + void 가장_멀리_이동한_사림이_우승한다() { + Cars cars = Cars.from(List.of("pobi", "jun", "khj")); + TestRacingNumberGenerator numberGenerator = new TestRacingNumberGenerator(); + + cars.race(numberGenerator); + cars.race(numberGenerator); + + assertThat(cars.findWinners()) + .contains(CarName.from("pobi"), CarName.from("khj")); + } + + static class TestRacingNumberGenerator implements RacingNumberGenerator { + + private final List<Integer> numbers = newArrayList(4, 1, 4, 4, 1, 4); + + @Override + public int generate() { + return numbers.remove(0); + } + } +}
Java
그렇군요! 사실 이 부분은 취향이라 더 간단하게 표현이 가능할 것 같아서 말씀드린 부분이었습니다 ㅎㅎ 저같은 경우에는 js만 사용하다가 이번 프리코스에서 자바를 시작했는데 오히려 메서드적 사고 하는게 힘들더라구요 왜이렇게 지원 안 되는 부분들이 많은지...ㅠㅠ 첨부해주신 내용에 대해 덧붙이자면 저 설명에서 말하고 있는건 함수형 인터페이스를 사용하게 되면 인자로 함수를 넘길 수 있게 된다는 걸 말하는 것 같습니다. (js처럼요!) 이런 특징을 `일급함수`라고 부르는데요, 이 일급함수는 함수형 프로그래밍 수행하기 위한 최소한의 조건이 됩니다. 따라서, 함수형 인터페이스를 넘기면 사실은 익명클래스지만 함수를 넘기는 것처럼 만들어 함수형 프로그래밍을 흉내내는 방식의 코드를 짤 수 있다! 라는거죠
@@ -0,0 +1,57 @@ +package racingcar.view; + +import racingcar.model.Car; +import racingcar.model.CarName; +import racingcar.model.Cars; + +import java.util.List; +import java.util.stream.Collectors; + +public class OutputView { + + private static final String NEW_LINE = "\n"; + private static final String SCORE_UNIT = "-"; + private static final String SCORE_BOARD = "%s : %s"; + private static final String WINNER_SEPARATOR = ", "; + private static final String WINNERS_ARE = "최종 우승자 : "; + private static final String ERROR_PREFIX = "[ERROR] "; + private static final String RESULT_INTRO = "실행 결과"; + + public void printResult(Cars cars) { + System.out.println(getScore(cars)); + } + + private String getScore(Cars cars) { + return cars.get().stream() + .map(this::toScoreBoard) + .collect(Collectors.joining(NEW_LINE)); + } + + private String toScoreBoard(Car car) { + return String.format(SCORE_BOARD, car.getName(), convertToScore(car.getPosition())); + } + + private String convertToScore(int position) { + return SCORE_UNIT.repeat(position); + } + + public void printWinners(List<CarName> winners) { + System.out.print(WINNERS_ARE); + System.out.println(getWinnerNames(winners)); + } + + private String getWinnerNames(List<CarName> winners) { + return winners.stream() + .map(CarName::get) + .collect(Collectors.joining(WINNER_SEPARATOR)); + } + + public void printError(IllegalArgumentException error) { + System.out.print(ERROR_PREFIX); + System.out.println(error.getMessage()); + } + + public void printRaceIntro() { + System.out.println(RESULT_INTRO); + } +}
Java
음 우선은 저는 메세지를 만드는 부분 자체를 UI 로직이라고 생각하기 보다는 도메인에서 해결 가능한 영역이라고 생각했습니다. 왜냐하면 이미 `Car`에서 해당 상태에 대해 모든 걸 알고 있는데 이를 굳이 밖으로 꺼낸다면 캡슐화가 깨진다고 생각했거든요. 그런데 말씀해주신 내용을 읽어보니 이를 UI라고 생각하면 애초에 다른 영역으로 던져주는 것이기 때문에 그대로 꺼낸다고 해서 캡슐화가 깨지는 건 아닌가? 하는 생각도 들고 어렵네요 ㅎㅎ 사실 저도 `getter`를 무조건적으로 배제하는 것은 옳지 않다고 생각하는 주의기도 하구요! 다 필요하니까 쓰는 것인데 하는 생각도 들고요 :D 남겨주신 의견 모두 즐거이 잘 들었습니다 ㅎㅎㅎ 다시 생각해볼 수 있는 계기도 되었구요
@@ -0,0 +1,57 @@ +package racingcar.view; + +import racingcar.model.Car; +import racingcar.model.CarName; +import racingcar.model.Cars; + +import java.util.List; +import java.util.stream.Collectors; + +public class OutputView { + + private static final String NEW_LINE = "\n"; + private static final String SCORE_UNIT = "-"; + private static final String SCORE_BOARD = "%s : %s"; + private static final String WINNER_SEPARATOR = ", "; + private static final String WINNERS_ARE = "최종 우승자 : "; + private static final String ERROR_PREFIX = "[ERROR] "; + private static final String RESULT_INTRO = "실행 결과"; + + public void printResult(Cars cars) { + System.out.println(getScore(cars)); + } + + private String getScore(Cars cars) { + return cars.get().stream() + .map(this::toScoreBoard) + .collect(Collectors.joining(NEW_LINE)); + } + + private String toScoreBoard(Car car) { + return String.format(SCORE_BOARD, car.getName(), convertToScore(car.getPosition())); + } + + private String convertToScore(int position) { + return SCORE_UNIT.repeat(position); + } + + public void printWinners(List<CarName> winners) { + System.out.print(WINNERS_ARE); + System.out.println(getWinnerNames(winners)); + } + + private String getWinnerNames(List<CarName> winners) { + return winners.stream() + .map(CarName::get) + .collect(Collectors.joining(WINNER_SEPARATOR)); + } + + public void printError(IllegalArgumentException error) { + System.out.print(ERROR_PREFIX); + System.out.println(error.getMessage()); + } + + public void printRaceIntro() { + System.out.println(RESULT_INTRO); + } +}
Java
상수처리가 정말 깔끔하네요! 특히 SCORE_BOARD 부분 배워갑니다.
@@ -0,0 +1,57 @@ +package racingcar.view; + +import racingcar.model.Car; +import racingcar.model.CarName; +import racingcar.model.Cars; + +import java.util.List; +import java.util.stream.Collectors; + +public class OutputView { + + private static final String NEW_LINE = "\n"; + private static final String SCORE_UNIT = "-"; + private static final String SCORE_BOARD = "%s : %s"; + private static final String WINNER_SEPARATOR = ", "; + private static final String WINNERS_ARE = "최종 우승자 : "; + private static final String ERROR_PREFIX = "[ERROR] "; + private static final String RESULT_INTRO = "실행 결과"; + + public void printResult(Cars cars) { + System.out.println(getScore(cars)); + } + + private String getScore(Cars cars) { + return cars.get().stream() + .map(this::toScoreBoard) + .collect(Collectors.joining(NEW_LINE)); + } + + private String toScoreBoard(Car car) { + return String.format(SCORE_BOARD, car.getName(), convertToScore(car.getPosition())); + } + + private String convertToScore(int position) { + return SCORE_UNIT.repeat(position); + } + + public void printWinners(List<CarName> winners) { + System.out.print(WINNERS_ARE); + System.out.println(getWinnerNames(winners)); + } + + private String getWinnerNames(List<CarName> winners) { + return winners.stream() + .map(CarName::get) + .collect(Collectors.joining(WINNER_SEPARATOR)); + } + + public void printError(IllegalArgumentException error) { + System.out.print(ERROR_PREFIX); + System.out.println(error.getMessage()); + } + + public void printRaceIntro() { + System.out.println(RESULT_INTRO); + } +}
Java
저도 @khj1 님과 같은 이유로 getter를 사용했는데요, 개인적으로는 `출력을 위한 getter는 캡슐화를 위배하는 게 아니다` 라고 생각합니다. 물론 의도와 다르게 사용되는 경우 캡슐화를 저해시킬 수 있습니다. 이 부분은 어쩔 수 없는 단점이라고 생각해요. 개인적으로 프리코스 기간 동안 '객체의 자율성을 얼마나 허용해줘야 하는지' 를 계속 고민했는데, 제가 다다른 결론은 '객체는 UI 로직 외의 경우에서 자율성을 보장해줘야 한다' 였습니다. 객체지향을 사용하는 이유는 결국 '자율성'보다는 '유연성'이니까요! UI 로직의 변경이 도메인 영역을 침범하는 것은 안된다고 판단했습니다. 저는 이렇게 생각했는데, @JerryK026 님 말씀 들어보니 이 부분은 스타일의 차이일 수도 있겠네요! 업무 환경이나 팀의 코드 스타일에 따라 달라질 것 같기도 합니다. 확실히 이 분야에 정답은 없는 것 같네요.. ㅎㅎ
@@ -0,0 +1,57 @@ +package racingcar.view; + +import racingcar.model.Car; +import racingcar.model.CarName; +import racingcar.model.Cars; + +import java.util.List; +import java.util.stream.Collectors; + +public class OutputView { + + private static final String NEW_LINE = "\n"; + private static final String SCORE_UNIT = "-"; + private static final String SCORE_BOARD = "%s : %s"; + private static final String WINNER_SEPARATOR = ", "; + private static final String WINNERS_ARE = "최종 우승자 : "; + private static final String ERROR_PREFIX = "[ERROR] "; + private static final String RESULT_INTRO = "실행 결과"; + + public void printResult(Cars cars) { + System.out.println(getScore(cars)); + } + + private String getScore(Cars cars) { + return cars.get().stream() + .map(this::toScoreBoard) + .collect(Collectors.joining(NEW_LINE)); + } + + private String toScoreBoard(Car car) { + return String.format(SCORE_BOARD, car.getName(), convertToScore(car.getPosition())); + } + + private String convertToScore(int position) { + return SCORE_UNIT.repeat(position); + } + + public void printWinners(List<CarName> winners) { + System.out.print(WINNERS_ARE); + System.out.println(getWinnerNames(winners)); + } + + private String getWinnerNames(List<CarName> winners) { + return winners.stream() + .map(CarName::get) + .collect(Collectors.joining(WINNER_SEPARATOR)); + } + + public void printError(IllegalArgumentException error) { + System.out.print(ERROR_PREFIX); + System.out.println(error.getMessage()); + } + + public void printRaceIntro() { + System.out.println(RESULT_INTRO); + } +}
Java
저는 개인적으로 MVC 에서 View는 컨트롤러로부터 동적인 정보만 받아야 한다고 생각하는데요! 혹시 이런 접근 방법은 어떠실까요? 제가 이렇게 생각하는 이유는, 관심사가 다르기 때문입니다. 에러 처리에 관한 출력은 해당 try-catch 블록에 책임이 있다고 생각해요. 사실 정답은 없는 것 같으나, 제가 고수하는 방법은 어떤지 제안드려 봅니다.
@@ -0,0 +1,47 @@ +package racingcar.model; + +public class Car implements Comparable<Car> { + private static final int MOVABLE_LOWER_BOUND = 4; + + private final CarName name; + private final Position position = Position.init(); + + private Car(String name) { + this.name = CarName.from(name); + } + + public static Car from(String name) { + return new Car(name); + } + + public void move(int command) { + if (isMovable(command)) { + position.increase(); + } + } + + private static boolean isMovable(int command) { + return command >= MOVABLE_LOWER_BOUND; + } + + public boolean isAt(Position expectedPosition) { + return position.equals(expectedPosition); + } + + public int getPosition() { + return position.getPosition(); + } + + public CarName getName() { + return name; + } + + public boolean isSamePosition(Car other) { + return this.position.equals(other.position); + } + + @Override + public int compareTo(Car other) { + return this.position.compareTo(other.position); + } +}
Java
저도 배워갑니다!! 이런 식으로 비교도 가능하군요..
@@ -0,0 +1,52 @@ +package racingcar.model; + +import java.util.Objects; + +public class CarName { + + private static final String INVALID_NAME_LENGTH = "자동차 이름은 5자를 초과할 수 없습니다."; + private static final int NAME_LENGTH_UPPER_BOUND = 5; + + private final String name; + + public CarName(String name) { + validate(name); + this.name = name; + } + + private void validate(String name) { + if (isInvalidLength(name)) { + throw new IllegalArgumentException(INVALID_NAME_LENGTH); + } + } + + private boolean isInvalidLength(String name) { + return name.length() > NAME_LENGTH_UPPER_BOUND; + } + + public static CarName from(String name) { + return new CarName(name); + } + + public String get() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CarName carName = (CarName) o; + return Objects.equals(name, carName.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + return name; + } +}
Java
hashCode가 사용되지 않는 것 같아, 따로 오버라이딩 하신 이유가 궁금합니다!
@@ -0,0 +1,52 @@ +package racingcar.model; + +import java.util.Objects; + +public class CarName { + + private static final String INVALID_NAME_LENGTH = "자동차 이름은 5자를 초과할 수 없습니다."; + private static final int NAME_LENGTH_UPPER_BOUND = 5; + + private final String name; + + public CarName(String name) { + validate(name); + this.name = name; + } + + private void validate(String name) { + if (isInvalidLength(name)) { + throw new IllegalArgumentException(INVALID_NAME_LENGTH); + } + } + + private boolean isInvalidLength(String name) { + return name.length() > NAME_LENGTH_UPPER_BOUND; + } + + public static CarName from(String name) { + return new CarName(name); + } + + public String get() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CarName carName = (CarName) o; + return Objects.equals(name, carName.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + return name; + } +}
Java
get 메소드가 toString과 중복되는 것 같습니다!
@@ -0,0 +1,63 @@ +package racingcar.cotroller; + +import racingcar.RandomRacingNumberGenerator; +import racingcar.model.AttemptCount; +import racingcar.model.Cars; +import racingcar.view.InputView; +import racingcar.view.OutputView; + +import java.util.List; +import java.util.function.Supplier; + +public class RacingCarController { + + private final InputView inputView; + private final OutputView outputView; + private final Cars cars; + + public RacingCarController() { + inputView = new InputView(); + outputView = new OutputView(); + cars = checkError(this::getCars); + } + + public void run() { + progressGame(); + printWinners(); + } + + private void progressGame() { + AttemptCount attemptCount = checkError(inputView::readAttemptCount); + + outputView.printRaceIntro(); + while (attemptCount.isPlayable()) { + attempt(); + attemptCount.decrease(); + } + } + + private void printWinners() { + outputView.printWinners(cars.findWinners()); + } + + private void attempt() { + RandomRacingNumberGenerator numberGenerator = new RandomRacingNumberGenerator(); + cars.race(numberGenerator); + + outputView.printResult(cars); + } + + private Cars getCars() { + List<String> names = inputView.readNames(); + return Cars.from(names); + } + + private <T> T checkError(Supplier<T> reader) { + try { + return reader.get(); + } catch (IllegalArgumentException error) { + outputView.printError(error); + return checkError(reader); + } + } +}
Java
따로 컨트롤러에서 RandomRacingNumberGenerator를 주입해주신 이유가 궁금합니다. 제 생각에는, RandomRacingNumberGenerator를 race 메소드 내에서 선언하면 컨트롤러에서 알아야 할 관심사가 하나 줄어드는 이점이 있을 것 같아서요!
@@ -1,29 +1,51 @@ package lotto.domain; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; public class Lotto { - private List<Integer> lotto; + private List<LottoNumber> lotto; - public Lotto(List<Integer> list) { - lotto = new ArrayList<>(); - lotto = list; + public Lotto(List<LottoNumber> lotto) { + Collections.sort(lotto); + this.lotto = lotto; + } + + public Lotto() { } - public List<Integer> getLotto() { + public List<LottoNumber> getLotto() { return lotto; } - public void setLotto(List<Integer> lotto) { + public void setLotto(List<LottoNumber> lotto) { this.lotto = lotto; } - public boolean isContain(int number) { - return lotto.contains(number); + public int countMatch(List<LottoNumber> winningNumber) { + int count = 0; + for (LottoNumber lottoNumber : winningNumber) { + count = increaseCount(lottoNumber, count); + } + return count; + } + + public int increaseCount(LottoNumber lottoNumber, int count) { + if (this.hasThisNumber(lottoNumber)) { + count++; + } + return count; + } + + public boolean hasThisNumber(LottoNumber number) { + return lotto.stream() + .filter(lottoNo -> lottoNo.equals(number)).count() != 0; } public String toString() { - return lotto.toString(); + return lotto.stream() + .map(LottoNumber::toString) + .collect(Collectors.joining(", ","[","]")); } -} +} \ No newline at end of file
Java
뭘 포함하고 있다는거죠?
@@ -1,29 +1,51 @@ package lotto.domain; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; public class Lotto { - private List<Integer> lotto; + private List<LottoNumber> lotto; - public Lotto(List<Integer> list) { - lotto = new ArrayList<>(); - lotto = list; + public Lotto(List<LottoNumber> lotto) { + Collections.sort(lotto); + this.lotto = lotto; + } + + public Lotto() { } - public List<Integer> getLotto() { + public List<LottoNumber> getLotto() { return lotto; } - public void setLotto(List<Integer> lotto) { + public void setLotto(List<LottoNumber> lotto) { this.lotto = lotto; } - public boolean isContain(int number) { - return lotto.contains(number); + public int countMatch(List<LottoNumber> winningNumber) { + int count = 0; + for (LottoNumber lottoNumber : winningNumber) { + count = increaseCount(lottoNumber, count); + } + return count; + } + + public int increaseCount(LottoNumber lottoNumber, int count) { + if (this.hasThisNumber(lottoNumber)) { + count++; + } + return count; + } + + public boolean hasThisNumber(LottoNumber number) { + return lotto.stream() + .filter(lottoNo -> lottoNo.equals(number)).count() != 0; } public String toString() { - return lotto.toString(); + return lotto.stream() + .map(LottoNumber::toString) + .collect(Collectors.joining(", ","[","]")); } -} +} \ No newline at end of file
Java
Builder 패턴과 메소드 체이닝 공부하시고 stringBuilder 다시 써보세요
@@ -1,29 +1,51 @@ package lotto.domain; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; public class Lotto { - private List<Integer> lotto; + private List<LottoNumber> lotto; - public Lotto(List<Integer> list) { - lotto = new ArrayList<>(); - lotto = list; + public Lotto(List<LottoNumber> lotto) { + Collections.sort(lotto); + this.lotto = lotto; + } + + public Lotto() { } - public List<Integer> getLotto() { + public List<LottoNumber> getLotto() { return lotto; } - public void setLotto(List<Integer> lotto) { + public void setLotto(List<LottoNumber> lotto) { this.lotto = lotto; } - public boolean isContain(int number) { - return lotto.contains(number); + public int countMatch(List<LottoNumber> winningNumber) { + int count = 0; + for (LottoNumber lottoNumber : winningNumber) { + count = increaseCount(lottoNumber, count); + } + return count; + } + + public int increaseCount(LottoNumber lottoNumber, int count) { + if (this.hasThisNumber(lottoNumber)) { + count++; + } + return count; + } + + public boolean hasThisNumber(LottoNumber number) { + return lotto.stream() + .filter(lottoNo -> lottoNo.equals(number)).count() != 0; } public String toString() { - return lotto.toString(); + return lotto.stream() + .map(LottoNumber::toString) + .collect(Collectors.joining(", ","[","]")); } -} +} \ No newline at end of file
Java
그리고 정말 toString을 이렇게 구현하시겠습니까?
@@ -3,77 +3,78 @@ import lotto.utils.Splitter; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class LottoGame { - private List<Lotto> lottos = new ArrayList<Lotto>(); + private static final int LOTTO_PRICE = 1000; + private List<Lotto> lottos; + private List<WinningLotto> winningLottos; + + public LottoGame() { + lottos = new ArrayList<Lotto>(); + winningLottos = new ArrayList<WinningLotto>(); + } public List<Lotto> getLottos() { return lottos; } - public void setLottos(List<Lotto> lottos) { - this.lottos = lottos; + public List<WinningLotto> getWinningLottos() { + return winningLottos; } - public List<Lotto> purchase(int money) { - for (int numbers = 0; numbers < changeUnit(money); numbers++) { - List<Integer> randomNumber = generateRandomNumbers(); - Collections.sort(randomNumber); - Lotto lotto = new Lotto(randomNumber); - lottos.add(lotto); + public void purchaseManual(String[] continuousNumbers) { + for (String continuousNumber : continuousNumbers) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.manual(continuousNumber)); } - return lottos; } - public static List<Integer> generateRandomNumbers() { - List<Integer> randomNumbers = new ArrayList<Integer>(); - for (int number = 1; number <= 45; number++) { - randomNumbers.add(number); + public void setWinningLottos(String continuousWinningNumbers, LottoNumber bonusNumber) { + List<LottoNumber> winningNumbers = Splitter.splitNumber(continuousWinningNumbers); + winningLottos = new ArrayList<>(); + for (Lotto lotto : lottos) { + setWinningLotto(lotto, lotto.countMatch(winningNumbers), bonusNumber); } - Collections.shuffle(randomNumbers); - return randomNumbers.subList(0, 6); } - public int[] saveLottoResult(String text) { - List<Integer> winnerNumber = Splitter.splitNumber(text); - int[] result = new int[NumberOfHits.values().length]; - for (int index = 0; index < lottos.size(); index++) { - result[countMatch(winnerNumber, index)]++; + public void setWinningLotto(Lotto lotto, int count, LottoNumber bonusNumber) { + if (Rank.lookUpRank(count, lotto.hasThisNumber(bonusNumber)) != Rank.MISS) { + winningLottos.add(new WinningLotto(lotto, count, bonusNumber)); } - return result; } - public int countMatch(List<Integer> winnerNumber, int index) { - int count = 0; - for (int number : winnerNumber) { - count = increaseCount(number, index, count); + public List<Lotto> purchaseAuto(int money, int numberOfManual) { + for (int numbers = 0; numbers < numberOfAutoLotto(money, numberOfManual); numbers++) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.auto()); } - return count; + return lottos; } - public int increaseCount(int number, int index, int count) { - if (lottos.get(index).isContain(number)) { - count++; - } - return count; + public int countSameRank(Rank rank) { + return (int) winningLottos.stream() + .filter(winningLotto -> winningLotto.findRank().equals(rank)) + .count(); } - public double calculateRate(int[] result, int outcome) { - int income = calculateReward(result); - return Math.round((double)income / outcome * 1000.0) / 10.0 ; + public double calculateRate(int outcome) { + return (double) calculateIncome() / outcome * 100.0; } - public int calculateReward(int[] result) { - int total = 0; - for (int index = 0; index < result.length; index++) { - total += result[index] * NumberOfHits.values()[index].getReward(); + public int calculateIncome() { + int income = 0; + for (WinningLotto winningLotto : winningLottos) { + income = winningLotto.findRank().plusReward(income); } - return total; + return income; } public int changeUnit(int totalPrice) { - return totalPrice / 1000; + return totalPrice / LOTTO_PRICE; + } + + public int numberOfAutoLotto(int money, int numberOfManual) { + return changeUnit(money) - numberOfManual; } -} +} \ No newline at end of file
Java
text 보다 좋은 네이밍이 있을 것 같습니다
@@ -3,77 +3,78 @@ import lotto.utils.Splitter; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class LottoGame { - private List<Lotto> lottos = new ArrayList<Lotto>(); + private static final int LOTTO_PRICE = 1000; + private List<Lotto> lottos; + private List<WinningLotto> winningLottos; + + public LottoGame() { + lottos = new ArrayList<Lotto>(); + winningLottos = new ArrayList<WinningLotto>(); + } public List<Lotto> getLottos() { return lottos; } - public void setLottos(List<Lotto> lottos) { - this.lottos = lottos; + public List<WinningLotto> getWinningLottos() { + return winningLottos; } - public List<Lotto> purchase(int money) { - for (int numbers = 0; numbers < changeUnit(money); numbers++) { - List<Integer> randomNumber = generateRandomNumbers(); - Collections.sort(randomNumber); - Lotto lotto = new Lotto(randomNumber); - lottos.add(lotto); + public void purchaseManual(String[] continuousNumbers) { + for (String continuousNumber : continuousNumbers) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.manual(continuousNumber)); } - return lottos; } - public static List<Integer> generateRandomNumbers() { - List<Integer> randomNumbers = new ArrayList<Integer>(); - for (int number = 1; number <= 45; number++) { - randomNumbers.add(number); + public void setWinningLottos(String continuousWinningNumbers, LottoNumber bonusNumber) { + List<LottoNumber> winningNumbers = Splitter.splitNumber(continuousWinningNumbers); + winningLottos = new ArrayList<>(); + for (Lotto lotto : lottos) { + setWinningLotto(lotto, lotto.countMatch(winningNumbers), bonusNumber); } - Collections.shuffle(randomNumbers); - return randomNumbers.subList(0, 6); } - public int[] saveLottoResult(String text) { - List<Integer> winnerNumber = Splitter.splitNumber(text); - int[] result = new int[NumberOfHits.values().length]; - for (int index = 0; index < lottos.size(); index++) { - result[countMatch(winnerNumber, index)]++; + public void setWinningLotto(Lotto lotto, int count, LottoNumber bonusNumber) { + if (Rank.lookUpRank(count, lotto.hasThisNumber(bonusNumber)) != Rank.MISS) { + winningLottos.add(new WinningLotto(lotto, count, bonusNumber)); } - return result; } - public int countMatch(List<Integer> winnerNumber, int index) { - int count = 0; - for (int number : winnerNumber) { - count = increaseCount(number, index, count); + public List<Lotto> purchaseAuto(int money, int numberOfManual) { + for (int numbers = 0; numbers < numberOfAutoLotto(money, numberOfManual); numbers++) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.auto()); } - return count; + return lottos; } - public int increaseCount(int number, int index, int count) { - if (lottos.get(index).isContain(number)) { - count++; - } - return count; + public int countSameRank(Rank rank) { + return (int) winningLottos.stream() + .filter(winningLotto -> winningLotto.findRank().equals(rank)) + .count(); } - public double calculateRate(int[] result, int outcome) { - int income = calculateReward(result); - return Math.round((double)income / outcome * 1000.0) / 10.0 ; + public double calculateRate(int outcome) { + return (double) calculateIncome() / outcome * 100.0; } - public int calculateReward(int[] result) { - int total = 0; - for (int index = 0; index < result.length; index++) { - total += result[index] * NumberOfHits.values()[index].getReward(); + public int calculateIncome() { + int income = 0; + for (WinningLotto winningLotto : winningLottos) { + income = winningLotto.findRank().plusReward(income); } - return total; + return income; } public int changeUnit(int totalPrice) { - return totalPrice / 1000; + return totalPrice / LOTTO_PRICE; + } + + public int numberOfAutoLotto(int money, int numberOfManual) { + return changeUnit(money) - numberOfManual; } -} +} \ No newline at end of file
Java
contrivedNumber 보다 좋은 네이밍이 있을 것 같습니다
@@ -3,77 +3,78 @@ import lotto.utils.Splitter; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class LottoGame { - private List<Lotto> lottos = new ArrayList<Lotto>(); + private static final int LOTTO_PRICE = 1000; + private List<Lotto> lottos; + private List<WinningLotto> winningLottos; + + public LottoGame() { + lottos = new ArrayList<Lotto>(); + winningLottos = new ArrayList<WinningLotto>(); + } public List<Lotto> getLottos() { return lottos; } - public void setLottos(List<Lotto> lottos) { - this.lottos = lottos; + public List<WinningLotto> getWinningLottos() { + return winningLottos; } - public List<Lotto> purchase(int money) { - for (int numbers = 0; numbers < changeUnit(money); numbers++) { - List<Integer> randomNumber = generateRandomNumbers(); - Collections.sort(randomNumber); - Lotto lotto = new Lotto(randomNumber); - lottos.add(lotto); + public void purchaseManual(String[] continuousNumbers) { + for (String continuousNumber : continuousNumbers) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.manual(continuousNumber)); } - return lottos; } - public static List<Integer> generateRandomNumbers() { - List<Integer> randomNumbers = new ArrayList<Integer>(); - for (int number = 1; number <= 45; number++) { - randomNumbers.add(number); + public void setWinningLottos(String continuousWinningNumbers, LottoNumber bonusNumber) { + List<LottoNumber> winningNumbers = Splitter.splitNumber(continuousWinningNumbers); + winningLottos = new ArrayList<>(); + for (Lotto lotto : lottos) { + setWinningLotto(lotto, lotto.countMatch(winningNumbers), bonusNumber); } - Collections.shuffle(randomNumbers); - return randomNumbers.subList(0, 6); } - public int[] saveLottoResult(String text) { - List<Integer> winnerNumber = Splitter.splitNumber(text); - int[] result = new int[NumberOfHits.values().length]; - for (int index = 0; index < lottos.size(); index++) { - result[countMatch(winnerNumber, index)]++; + public void setWinningLotto(Lotto lotto, int count, LottoNumber bonusNumber) { + if (Rank.lookUpRank(count, lotto.hasThisNumber(bonusNumber)) != Rank.MISS) { + winningLottos.add(new WinningLotto(lotto, count, bonusNumber)); } - return result; } - public int countMatch(List<Integer> winnerNumber, int index) { - int count = 0; - for (int number : winnerNumber) { - count = increaseCount(number, index, count); + public List<Lotto> purchaseAuto(int money, int numberOfManual) { + for (int numbers = 0; numbers < numberOfAutoLotto(money, numberOfManual); numbers++) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.auto()); } - return count; + return lottos; } - public int increaseCount(int number, int index, int count) { - if (lottos.get(index).isContain(number)) { - count++; - } - return count; + public int countSameRank(Rank rank) { + return (int) winningLottos.stream() + .filter(winningLotto -> winningLotto.findRank().equals(rank)) + .count(); } - public double calculateRate(int[] result, int outcome) { - int income = calculateReward(result); - return Math.round((double)income / outcome * 1000.0) / 10.0 ; + public double calculateRate(int outcome) { + return (double) calculateIncome() / outcome * 100.0; } - public int calculateReward(int[] result) { - int total = 0; - for (int index = 0; index < result.length; index++) { - total += result[index] * NumberOfHits.values()[index].getReward(); + public int calculateIncome() { + int income = 0; + for (WinningLotto winningLotto : winningLottos) { + income = winningLotto.findRank().plusReward(income); } - return total; + return income; } public int changeUnit(int totalPrice) { - return totalPrice / 1000; + return totalPrice / LOTTO_PRICE; + } + + public int numberOfAutoLotto(int money, int numberOfManual) { + return changeUnit(money) - numberOfManual; } -} +} \ No newline at end of file
Java
어디서는 menual이고 여기서는 manual이고 스펠링이 도대체 뭐죠?
@@ -0,0 +1,67 @@ +package lotto.domain; + +import java.util.Arrays; + +public enum Rank { + FIRST(6, 2000000000), + SECOND(5, 30000000), + THIRD(5, 1500000), + FOURTH(4, 50000), + FIFTH(3, 5000), + MISS(0, 0); + + private static final int PRIZE_MIN_NUMBER = 3; + + private int matchCount; + private int winningPrice; + + private Rank(int matchCount, int winningPrice) { + this.matchCount = matchCount; + this.winningPrice = winningPrice; + } + + public int getMatchCount() { + return matchCount; + } + + public int getWinningPrice() { + return winningPrice; + } + + public static Rank lookUpRank(int matchCount, boolean hasBonusNumber) { + if (matchCount < PRIZE_MIN_NUMBER) { + return MISS; + } + + if (SECOND.isRightCount(matchCount) && hasBonusNumber) { + return SECOND; + } + + if (THIRD.isRightCount(matchCount)) { + return THIRD; + } + + return (Rank) Arrays.stream(values()).filter(rank -> rank.isRightCount(matchCount)).toArray()[0]; + } + + public boolean isRightCount(int matchCount) { + return this.matchCount == matchCount; + } + + public int plusReward(int income) { + return income + winningPrice; + } + + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(this.matchCount) + .append("개 일치"); + if (this.winningPrice == Rank.SECOND.winningPrice) { + stringBuilder.append(", 보너스 볼 일치"); + } + stringBuilder.append("(") + .append(this.winningPrice) + .append(")-"); + return stringBuilder.toString(); + } +} \ No newline at end of file
Java
좀 더 좋은 메소드 네이밍
@@ -0,0 +1,67 @@ +package lotto.domain; + +import java.util.Arrays; + +public enum Rank { + FIRST(6, 2000000000), + SECOND(5, 30000000), + THIRD(5, 1500000), + FOURTH(4, 50000), + FIFTH(3, 5000), + MISS(0, 0); + + private static final int PRIZE_MIN_NUMBER = 3; + + private int matchCount; + private int winningPrice; + + private Rank(int matchCount, int winningPrice) { + this.matchCount = matchCount; + this.winningPrice = winningPrice; + } + + public int getMatchCount() { + return matchCount; + } + + public int getWinningPrice() { + return winningPrice; + } + + public static Rank lookUpRank(int matchCount, boolean hasBonusNumber) { + if (matchCount < PRIZE_MIN_NUMBER) { + return MISS; + } + + if (SECOND.isRightCount(matchCount) && hasBonusNumber) { + return SECOND; + } + + if (THIRD.isRightCount(matchCount)) { + return THIRD; + } + + return (Rank) Arrays.stream(values()).filter(rank -> rank.isRightCount(matchCount)).toArray()[0]; + } + + public boolean isRightCount(int matchCount) { + return this.matchCount == matchCount; + } + + public int plusReward(int income) { + return income + winningPrice; + } + + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(this.matchCount) + .append("개 일치"); + if (this.winningPrice == Rank.SECOND.winningPrice) { + stringBuilder.append(", 보너스 볼 일치"); + } + stringBuilder.append("(") + .append(this.winningPrice) + .append(")-"); + return stringBuilder.toString(); + } +} \ No newline at end of file
Java
set이라는 명칭은 클래스 필드들에 값을 세팅할때 사용하니까 다른 명칭이 좋을 것 같습니다
@@ -3,77 +3,78 @@ import lotto.utils.Splitter; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class LottoGame { - private List<Lotto> lottos = new ArrayList<Lotto>(); + private static final int LOTTO_PRICE = 1000; + private List<Lotto> lottos; + private List<WinningLotto> winningLottos; + + public LottoGame() { + lottos = new ArrayList<Lotto>(); + winningLottos = new ArrayList<WinningLotto>(); + } public List<Lotto> getLottos() { return lottos; } - public void setLottos(List<Lotto> lottos) { - this.lottos = lottos; + public List<WinningLotto> getWinningLottos() { + return winningLottos; } - public List<Lotto> purchase(int money) { - for (int numbers = 0; numbers < changeUnit(money); numbers++) { - List<Integer> randomNumber = generateRandomNumbers(); - Collections.sort(randomNumber); - Lotto lotto = new Lotto(randomNumber); - lottos.add(lotto); + public void purchaseManual(String[] continuousNumbers) { + for (String continuousNumber : continuousNumbers) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.manual(continuousNumber)); } - return lottos; } - public static List<Integer> generateRandomNumbers() { - List<Integer> randomNumbers = new ArrayList<Integer>(); - for (int number = 1; number <= 45; number++) { - randomNumbers.add(number); + public void setWinningLottos(String continuousWinningNumbers, LottoNumber bonusNumber) { + List<LottoNumber> winningNumbers = Splitter.splitNumber(continuousWinningNumbers); + winningLottos = new ArrayList<>(); + for (Lotto lotto : lottos) { + setWinningLotto(lotto, lotto.countMatch(winningNumbers), bonusNumber); } - Collections.shuffle(randomNumbers); - return randomNumbers.subList(0, 6); } - public int[] saveLottoResult(String text) { - List<Integer> winnerNumber = Splitter.splitNumber(text); - int[] result = new int[NumberOfHits.values().length]; - for (int index = 0; index < lottos.size(); index++) { - result[countMatch(winnerNumber, index)]++; + public void setWinningLotto(Lotto lotto, int count, LottoNumber bonusNumber) { + if (Rank.lookUpRank(count, lotto.hasThisNumber(bonusNumber)) != Rank.MISS) { + winningLottos.add(new WinningLotto(lotto, count, bonusNumber)); } - return result; } - public int countMatch(List<Integer> winnerNumber, int index) { - int count = 0; - for (int number : winnerNumber) { - count = increaseCount(number, index, count); + public List<Lotto> purchaseAuto(int money, int numberOfManual) { + for (int numbers = 0; numbers < numberOfAutoLotto(money, numberOfManual); numbers++) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.auto()); } - return count; + return lottos; } - public int increaseCount(int number, int index, int count) { - if (lottos.get(index).isContain(number)) { - count++; - } - return count; + public int countSameRank(Rank rank) { + return (int) winningLottos.stream() + .filter(winningLotto -> winningLotto.findRank().equals(rank)) + .count(); } - public double calculateRate(int[] result, int outcome) { - int income = calculateReward(result); - return Math.round((double)income / outcome * 1000.0) / 10.0 ; + public double calculateRate(int outcome) { + return (double) calculateIncome() / outcome * 100.0; } - public int calculateReward(int[] result) { - int total = 0; - for (int index = 0; index < result.length; index++) { - total += result[index] * NumberOfHits.values()[index].getReward(); + public int calculateIncome() { + int income = 0; + for (WinningLotto winningLotto : winningLottos) { + income = winningLotto.findRank().plusReward(income); } - return total; + return income; } public int changeUnit(int totalPrice) { - return totalPrice / 1000; + return totalPrice / LOTTO_PRICE; + } + + public int numberOfAutoLotto(int money, int numberOfManual) { + return changeUnit(money) - numberOfManual; } -} +} \ No newline at end of file
Java
오타입니다
@@ -3,77 +3,78 @@ import lotto.utils.Splitter; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class LottoGame { - private List<Lotto> lottos = new ArrayList<Lotto>(); + private static final int LOTTO_PRICE = 1000; + private List<Lotto> lottos; + private List<WinningLotto> winningLottos; + + public LottoGame() { + lottos = new ArrayList<Lotto>(); + winningLottos = new ArrayList<WinningLotto>(); + } public List<Lotto> getLottos() { return lottos; } - public void setLottos(List<Lotto> lottos) { - this.lottos = lottos; + public List<WinningLotto> getWinningLottos() { + return winningLottos; } - public List<Lotto> purchase(int money) { - for (int numbers = 0; numbers < changeUnit(money); numbers++) { - List<Integer> randomNumber = generateRandomNumbers(); - Collections.sort(randomNumber); - Lotto lotto = new Lotto(randomNumber); - lottos.add(lotto); + public void purchaseManual(String[] continuousNumbers) { + for (String continuousNumber : continuousNumbers) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.manual(continuousNumber)); } - return lottos; } - public static List<Integer> generateRandomNumbers() { - List<Integer> randomNumbers = new ArrayList<Integer>(); - for (int number = 1; number <= 45; number++) { - randomNumbers.add(number); + public void setWinningLottos(String continuousWinningNumbers, LottoNumber bonusNumber) { + List<LottoNumber> winningNumbers = Splitter.splitNumber(continuousWinningNumbers); + winningLottos = new ArrayList<>(); + for (Lotto lotto : lottos) { + setWinningLotto(lotto, lotto.countMatch(winningNumbers), bonusNumber); } - Collections.shuffle(randomNumbers); - return randomNumbers.subList(0, 6); } - public int[] saveLottoResult(String text) { - List<Integer> winnerNumber = Splitter.splitNumber(text); - int[] result = new int[NumberOfHits.values().length]; - for (int index = 0; index < lottos.size(); index++) { - result[countMatch(winnerNumber, index)]++; + public void setWinningLotto(Lotto lotto, int count, LottoNumber bonusNumber) { + if (Rank.lookUpRank(count, lotto.hasThisNumber(bonusNumber)) != Rank.MISS) { + winningLottos.add(new WinningLotto(lotto, count, bonusNumber)); } - return result; } - public int countMatch(List<Integer> winnerNumber, int index) { - int count = 0; - for (int number : winnerNumber) { - count = increaseCount(number, index, count); + public List<Lotto> purchaseAuto(int money, int numberOfManual) { + for (int numbers = 0; numbers < numberOfAutoLotto(money, numberOfManual); numbers++) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.auto()); } - return count; + return lottos; } - public int increaseCount(int number, int index, int count) { - if (lottos.get(index).isContain(number)) { - count++; - } - return count; + public int countSameRank(Rank rank) { + return (int) winningLottos.stream() + .filter(winningLotto -> winningLotto.findRank().equals(rank)) + .count(); } - public double calculateRate(int[] result, int outcome) { - int income = calculateReward(result); - return Math.round((double)income / outcome * 1000.0) / 10.0 ; + public double calculateRate(int outcome) { + return (double) calculateIncome() / outcome * 100.0; } - public int calculateReward(int[] result) { - int total = 0; - for (int index = 0; index < result.length; index++) { - total += result[index] * NumberOfHits.values()[index].getReward(); + public int calculateIncome() { + int income = 0; + for (WinningLotto winningLotto : winningLottos) { + income = winningLotto.findRank().plusReward(income); } - return total; + return income; } public int changeUnit(int totalPrice) { - return totalPrice / 1000; + return totalPrice / LOTTO_PRICE; + } + + public int numberOfAutoLotto(int money, int numberOfManual) { + return changeUnit(money) - numberOfManual; } -} +} \ No newline at end of file
Java
1000이란 값을 하드코딩중
@@ -0,0 +1,17 @@ +package lotto.domain; + +public class WinningLotto extends Lotto { + private Lotto lotto; + private int matchCount; + private boolean hasbonusNumber; + + public WinningLotto(Lotto lotto, int matchCount, LottoNumber bonusNumber) { + this.hasbonusNumber = lotto.hasThisNumber(bonusNumber); + this.lotto = lotto; + this.matchCount = matchCount; + } + + public Rank findRank() { + return Rank.lookUpRank(matchCount, hasbonusNumber); + } +} \ No newline at end of file
Java
get set 지워보고 생각해보십쇼 (객체지향 생활체조 규칙 get set 사용을 자제한다)
@@ -3,77 +3,78 @@ import lotto.utils.Splitter; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class LottoGame { - private List<Lotto> lottos = new ArrayList<Lotto>(); + private static final int LOTTO_PRICE = 1000; + private List<Lotto> lottos; + private List<WinningLotto> winningLottos; + + public LottoGame() { + lottos = new ArrayList<Lotto>(); + winningLottos = new ArrayList<WinningLotto>(); + } public List<Lotto> getLottos() { return lottos; } - public void setLottos(List<Lotto> lottos) { - this.lottos = lottos; + public List<WinningLotto> getWinningLottos() { + return winningLottos; } - public List<Lotto> purchase(int money) { - for (int numbers = 0; numbers < changeUnit(money); numbers++) { - List<Integer> randomNumber = generateRandomNumbers(); - Collections.sort(randomNumber); - Lotto lotto = new Lotto(randomNumber); - lottos.add(lotto); + public void purchaseManual(String[] continuousNumbers) { + for (String continuousNumber : continuousNumbers) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.manual(continuousNumber)); } - return lottos; } - public static List<Integer> generateRandomNumbers() { - List<Integer> randomNumbers = new ArrayList<Integer>(); - for (int number = 1; number <= 45; number++) { - randomNumbers.add(number); + public void setWinningLottos(String continuousWinningNumbers, LottoNumber bonusNumber) { + List<LottoNumber> winningNumbers = Splitter.splitNumber(continuousWinningNumbers); + winningLottos = new ArrayList<>(); + for (Lotto lotto : lottos) { + setWinningLotto(lotto, lotto.countMatch(winningNumbers), bonusNumber); } - Collections.shuffle(randomNumbers); - return randomNumbers.subList(0, 6); } - public int[] saveLottoResult(String text) { - List<Integer> winnerNumber = Splitter.splitNumber(text); - int[] result = new int[NumberOfHits.values().length]; - for (int index = 0; index < lottos.size(); index++) { - result[countMatch(winnerNumber, index)]++; + public void setWinningLotto(Lotto lotto, int count, LottoNumber bonusNumber) { + if (Rank.lookUpRank(count, lotto.hasThisNumber(bonusNumber)) != Rank.MISS) { + winningLottos.add(new WinningLotto(lotto, count, bonusNumber)); } - return result; } - public int countMatch(List<Integer> winnerNumber, int index) { - int count = 0; - for (int number : winnerNumber) { - count = increaseCount(number, index, count); + public List<Lotto> purchaseAuto(int money, int numberOfManual) { + for (int numbers = 0; numbers < numberOfAutoLotto(money, numberOfManual); numbers++) { + LottoGenerator lottoGenerator = new LottoGenerator(); + lottos.add(lottoGenerator.auto()); } - return count; + return lottos; } - public int increaseCount(int number, int index, int count) { - if (lottos.get(index).isContain(number)) { - count++; - } - return count; + public int countSameRank(Rank rank) { + return (int) winningLottos.stream() + .filter(winningLotto -> winningLotto.findRank().equals(rank)) + .count(); } - public double calculateRate(int[] result, int outcome) { - int income = calculateReward(result); - return Math.round((double)income / outcome * 1000.0) / 10.0 ; + public double calculateRate(int outcome) { + return (double) calculateIncome() / outcome * 100.0; } - public int calculateReward(int[] result) { - int total = 0; - for (int index = 0; index < result.length; index++) { - total += result[index] * NumberOfHits.values()[index].getReward(); + public int calculateIncome() { + int income = 0; + for (WinningLotto winningLotto : winningLottos) { + income = winningLotto.findRank().plusReward(income); } - return total; + return income; } public int changeUnit(int totalPrice) { - return totalPrice / 1000; + return totalPrice / LOTTO_PRICE; + } + + public int numberOfAutoLotto(int money, int numberOfManual) { + return changeUnit(money) - numberOfManual; } -} +} \ No newline at end of file
Java
이 클래스가 너무 무거워보입니다. 너무 많은 책임을 갖고 있는건 아닌지 한번 봐보세요
@@ -0,0 +1,32 @@ +package lotto.domain; + +import lotto.utils.Splitter; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class LottoGenerator { + List<LottoNumber> randomNumbers; + + public LottoGenerator() { + randomNumbers = new ArrayList<>(); + } + + public Lotto manual(String continuousNumber) { + randomNumbers = Splitter.splitNumber(continuousNumber); + return new Lotto(randomNumbers); + } + + public Lotto auto() { + return new Lotto(generateRandomNumbers()); + } + + public List<LottoNumber> generateRandomNumbers() { + for (int number = 1; number <= 45; number++) { + randomNumbers.add(new LottoNumber(number)); + } + Collections.shuffle(randomNumbers); + return randomNumbers.subList(0, 6); + } +} \ No newline at end of file
Java
generateAuto() 가 낫지 않을까요
@@ -0,0 +1,32 @@ +package lotto.domain; + +import lotto.utils.Splitter; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class LottoGenerator { + List<LottoNumber> randomNumbers; + + public LottoGenerator() { + randomNumbers = new ArrayList<>(); + } + + public Lotto manual(String continuousNumber) { + randomNumbers = Splitter.splitNumber(continuousNumber); + return new Lotto(randomNumbers); + } + + public Lotto auto() { + return new Lotto(generateRandomNumbers()); + } + + public List<LottoNumber> generateRandomNumbers() { + for (int number = 1; number <= 45; number++) { + randomNumbers.add(new LottoNumber(number)); + } + Collections.shuffle(randomNumbers); + return randomNumbers.subList(0, 6); + } +} \ No newline at end of file
Java
generateMenual 이 낫지 않을까요. menual인지 manual인지 통일 시켜달라니까 무시당했네요