Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2단계 - 사다리 게임 실행] 페드로(류형욱) 미션 제출합니다. #404

Merged
merged 31 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
1f48eb7
style(lineTest): 테스트 메서드 설명을 명확하게 변경
hw0603 Feb 28, 2024
621c559
refactor(ladder): view로 전달하기 위한 DTO의 생성 위치 변경
hw0603 Feb 28, 2024
10cfc58
refactor(ladder): 랜덤 경로 생성 후 부족한 경로를 채우는 로직의 메서드 분리
hw0603 Feb 28, 2024
d18fcdd
refactor(LadderPath): LadderPath enum에서 방향과 연결 여부를 모두 관리하도록 변경
hw0603 Feb 28, 2024
006a734
docs(README): 2단계(사다리 게임 실행) 기능 요구사항 명세 추가
hw0603 Feb 29, 2024
0ce5689
feat(player): 사용자 이름이 'all' 일 경우 예외 처리
hw0603 Feb 29, 2024
e52bc3d
fix(LadderPath): isPathExist() 논리 오류 수정
hw0603 Feb 29, 2024
39e37ec
feat(ladderGame): 사다리 한 줄을 내려오는 기능 구현
hw0603 Feb 29, 2024
f99df60
feat(LadderGame): 참여자들의 최종 도착지를 계산하는 기능 추가
hw0603 Feb 29, 2024
f98adf7
feat(inputView): 결과를 보고 싶은 사람을 입력받는 기능 구현
hw0603 Feb 29, 2024
72af0bf
feat: Line 하나를 내려왔을 때 위치를 구하는 기능 구현
hw0603 Mar 1, 2024
a587612
feat(ladderGame): 사다리 전체를 내려오는 기능 구현
hw0603 Mar 1, 2024
bd777cc
refactor(ladderController): 불 필요 필드 제거
hw0603 Mar 1, 2024
64be7f9
feat(OutputView): 실행 결과 출력 기능 구현
hw0603 Mar 1, 2024
a7e4b26
feat(ladderGame): LadderGame 생성 시 참여자 수, 실행 결과 수, 사다리 폭에 대한 검증 추가
hw0603 Mar 1, 2024
0932791
refactor(ladderGameTest): Players, Rewards 생성 로직 메서드 추출
hw0603 Mar 1, 2024
87b4691
comment: 미 사용 TODO 삭제
hw0603 Mar 2, 2024
6caa9fc
refactor(line): connected 리스트를 인스턴스 생성 당시 계산하도록 변경
hw0603 Mar 2, 2024
27e6322
refactor(ladder): Ladder에서 자신의 폭을 반환할 수 있도록 변경
hw0603 Mar 2, 2024
f4ce0d4
refactor(ladderController): Ladder 필드 삭제
hw0603 Mar 2, 2024
a403b73
refactor(outputView): 생성된 사다리를 출력하는 형태를 View가 직접 결정하도록 변경
hw0603 Mar 2, 2024
b559835
refactor(ladderController): 상수 포장
hw0603 Mar 2, 2024
0352e17
fix: fix typo
hw0603 Mar 2, 2024
8f9d7cd
refactor(lineDto): Ladder를 List<LineDto>로 변환하는 팩토리 메서드 추가
hw0603 Mar 2, 2024
9d12d61
style(ladderGameTest): 파라미터로 사용되는 스트림의 지역 변수 추출
hw0603 Mar 2, 2024
43cdd0a
refactor(Ladder): 랜덤 경로 생성 시 루프 순회 한번 당 하나의 경로를 추가하도록 변경
hw0603 Mar 3, 2024
4fc0172
refactor(ladderGame): 사다리를 타도록 하는 주체를 LadderGame 에서 Ladder로 변경
hw0603 Mar 3, 2024
ad64fa5
refactor(line): climeDown() 에서 swap 방식 대신 Path 내의 direction 값을 활용하도록 변경
hw0603 Mar 3, 2024
63a7802
style(lineTest): 테스트 메서드 설명 변경
hw0603 Mar 3, 2024
2432fd4
style(line): 코드 스타일 수정
hw0603 Mar 4, 2024
1a255a0
refactor(line, ladder): 사다리를 내려오는 방식 변경
hw0603 Mar 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# 1단계 - 사다리 생성

## 주요 기능

1. 참여할 사람 이름 입력
Expand Down Expand Up @@ -27,15 +29,34 @@
- 왼쪽 경로 왼쪽에 항상 오른쪽 경로가 있어야 한다.

### 실행 결과 출력

- [x] “실행 결과” 문구 출력
- [x] 참여자 이름 출력
- [x] 사다리 출력

### 예외 처리

- [x] 유효한 참여자 이름이 아닐 경우 예외 발생
- 이름의 길이는 1 이상 5이하여야 함
- 이름에 포함되는 문자는 영문자와 숫자만 허용함
- [x] 유효한 사다리 높이가 아닐 경우 예외 발생
- 높이는 항상 자연수여야 함
- 높이는 항상 자연수여야 함

# 2단계 - 사다리 게임 실행

## 기능 요구사항
- 사다리 실행 결과를 출력해야 함
- 개인별 이름을 입력하면 개인별 결과를 출력함
- `all` 을 입력하면 전체 참여자의 실행 결과를 출력함

### 참여할 사람의 이름
- [x] 참여자의 이름은 `all` 일 수 없다.

### 실행 결과 입력
- [x] 실행 결과 입력
- 입력된 실행 결과의 개수는 참여자 수와 같아야 함

### 사다리 타고 결과 출력
- [x] 참여자들의 최종 도착지를 계산하는 기능
- [x] 결과를 보고 싶은 사람을 입력받는 기능
- [x] 실행 결과를 출력하는 기능
- 한 명의 결과를 출력하는 경우 '도착지' 만 출력
- 전체의 결과를 출력하는 경우 각 참여자의 이름과 도착지를 출력
45 changes: 36 additions & 9 deletions src/main/java/ladder/controller/LadderController.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
package ladder.controller;

import java.util.Map;
import ladder.dto.LineDto;
import ladder.model.Ladder;
import ladder.model.Players;
import ladder.service.LadderGame;
import ladder.view.InputView;
import ladder.view.OutputView;

import java.util.List;

public class LadderController {
private Players ladderPlayers;
private Ladder ladder;
private static final String QUERY_FOR_ALL_REWARD = "all";
private LadderGame ladderGame;

public void start() {
init();
printResult();
showGame();
showReward(readLookupTarget());
}

private void init() {
ladderPlayers = Players.from(readPlayerNames());
Players ladderPlayers = Players.from(readPlayerNames());

int height = readLadderHeight();
int width = ladderPlayers.getSize();
ladder = Ladder.of(height, width);

List<String> rewards = readRewards();
Ladder ladder = Ladder.of(height, width);
ladderGame = LadderGame.from(ladderPlayers, rewards, ladder);
}

private List<String> readPlayerNames() {
Expand All @@ -32,9 +39,29 @@ private int readLadderHeight() {
return InputView.inputLadderHeight();
}

private void printResult() {
OutputView.printResultDescription();
OutputView.printPlayerNames(ladderPlayers.getPlayerNames());
OutputView.printLadder(ladder.toLineDtoList());
private List<String> readRewards() {
return InputView.inputRewards();
}

private String readLookupTarget() {
return InputView.inputLookupTarget();
}

private void showGame() {
OutputView.printGame(
ladderGame.getPlayerNames(),
LineDto.asList(ladderGame.getLadder()),
ladderGame.getRewards()
);
}

private void showReward(String target) {
Map<String, String> result = ladderGame.play();

if (target.equals(QUERY_FOR_ALL_REWARD)) {
OutputView.printRewardForAll(result);
return;
}
OutputView.printRewardForTarget(result.get(target));
}
}
7 changes: 7 additions & 0 deletions src/main/java/ladder/dto/LineDto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package ladder.dto;

import ladder.model.Ladder;
import ladder.model.Line;

import java.util.List;
Expand All @@ -15,6 +16,12 @@ public static LineDto from(Line line) {
return new LineDto(line.getConnected());
}

public static List<LineDto> asList(Ladder ladder) {
return ladder.getLadder().stream()
.map(LineDto::from)
.toList();
}

public List<Boolean> getConnected() {
return connected;
}
Expand Down
58 changes: 38 additions & 20 deletions src/main/java/ladder/model/Ladder.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package ladder.model;

import java.util.Collections;
import java.util.stream.IntStream;
import ladder.dto.LineDto;

import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -36,37 +36,55 @@ private static boolean notNaturalNumber(int value) {
}

private static List<LadderPath> makeRandomRow(int width) {
List<LadderPath> randomPath = new ArrayList<>(generatePairableRandomPath(width));
List<LadderPath> randomPaths = new ArrayList<>();

if (randomPath.size() < width) {
randomPath.add(LadderPath.STAY);
while (randomPaths.size() < width) {
randomPaths.add(generateRandomPath(randomPaths, width));
}

return randomPath;
return randomPaths;
}

private static List<LadderPath> generatePairableRandomPath(int maxWidth) {
List<LadderPath> randomPathWithPair = new ArrayList<>();

while (randomPathWithPair.size() < maxWidth - 1) {
randomPathWithPair.addAll(generateRandomPath());
private static LadderPath generateRandomPath(List<LadderPath> currentPaths, int width) {
if (isLastPathConnected(currentPaths)) {
return LadderPath.LEFT;
}

return randomPathWithPair;
}
boolean isLastElement = currentPaths.size() == width - 1;
if (isLastElement) {
return LadderPath.STAY;
}

private static List<LadderPath> generateRandomPath() {
boolean isConnectedPath = random.nextBoolean();

if (isConnectedPath) {
return List.of(LadderPath.RIGHT, LadderPath.LEFT);
return LadderPath.RIGHT;
}
return List.of(LadderPath.STAY);
return LadderPath.STAY;
}

public List<LineDto> toLineDtoList() {
return ladder.stream()
.map(LineDto::from)
.toList();
private static boolean isLastPathConnected(List<LadderPath> currentPaths) {
if (currentPaths.isEmpty()) {
return false;
}

LadderPath lastPath = currentPaths.get(currentPaths.size() - 1);
return lastPath.equals(LadderPath.RIGHT);
}

public List<Integer> climb() {
List<Integer> result = new ArrayList<>(IntStream.range(0, getWidth())
.boxed()
.toList());
ladder.forEach(line -> result.replaceAll(line::climbDown));

return result;
}

public List<Line> getLadder() {
return Collections.unmodifiableList(ladder);
}

public int getWidth() {
return ladder.get(0).size();
}
}
16 changes: 15 additions & 1 deletion src/main/java/ladder/model/LadderPath.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
package ladder.model;

public enum LadderPath {
STAY, LEFT, RIGHT;
LEFT(true, -1),
STAY(false, 0),
RIGHT(true, 1);

final boolean connected;
final int direction;

LadderPath(boolean connected, int direction) {
this.connected = connected;
this.direction = direction;
}

public static boolean isPathExist(LadderPath leftPath, LadderPath rightPath) {
return leftPath.equals(RIGHT) && rightPath.equals(LEFT);
}
Comment on lines 3 to +18
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enum 사용, DTO와 도메인의 의존 관계

우선 해당 리뷰에서 제가 말한 dto 에서의 전환 은 dto <-> domain 의 의미가 아니라 방향 <-> 연결유무 의 변환이었어요.

오히려 '방향' 과 '연결 여부' 를 어떻게 관리할 것인지 고민해보는게 이 미션의 핵심 포인트 중 하나라고 생각했어요. 그 해결책이 dto 에서의 전환은 아니라고도 생각했구요.

제가 step 1 초반부 코드를 봤을 때 dto 에 있는 변환 로직이 방향을 연결유무로 전환하는 로직이었거든요 :

        List<Boolean> connected = IntStream.range(0, row.size() - 1)
                .mapToObj(idx -> row.get(idx).equals(LadderPath.RIGHT))
                .toList();

물론 DTO 가 boolean 형태로 정보를 담고 있어서 생기는 전환이기도 하지만, 나름 이게 도메인 로직으로 사용될수도 있을만큼 중요한 로직이라고 생각했어요. 이 부분 혹시 아직 이해가 안된다면 언제든 알려주세요.

Q. DTO에서는 도메인을 알고 있지만, 도메인에서는 DTO를 모르고, enum을 통해 연결 여부와 방향을 한 번에 관리할 수 있게 되었습니다.
아주 좋은 구조라고 생각해요. DTO 에 dto <-> domain 전환 로직이 들어가도 괜찮습니다. enum 을 통해 연결 여부와 방향을 한 번에 관리하는 것도 좋은 것 같아요. 방향을 로직에서 사용하면 더 좋겠네요...! 사용하지 않는다면 지워도 좋구요.

Q. (위의 질문과 중복된 느낌은 있지만) 도메인에서 DTO에 의존하는 것은 좋지 않다. DTO에서는 도메인을 알아도 된다?
제가 생각했을 때 도메인은 java 에서 제공하는 라이브러리나 다른 도메인, 그리고 어쩔 땐 프로젝트 특성상 추가해야하는 DB 관련된 의존성 외에는 다른 의존성이 전혀 없어야 한다고 생각해요. 그렇기 때문에 네, 도메인이 DTO 에 의존하는 것은 그리 좋은 방식은 아닌 것 같아요. DTO 에서는 도메인을 몰라도 되고 (순수하게 데이터 전달만 담당, domain 에서 dto 로 변환하는 로직은 다른 곳에 위치), 알아도 괜찮다고 생각해요. 단, 알고 있을 땐 우리가 저번에 말했던 것처럼 도메인에서 최대한 getter 만을 호출하는 방식으로 만들어져야겠죠.

Q. Ladder처럼 별개의 DTO 없이도 List 형태로 나타낼 수 있는 객체들은 DTO로의 변환을 어디서 해야 하는가?

페드로의 생각 : '뷰'와 '모델'을 이어주는 책임은 컨트롤러에 있으므로, 변환은 컨트롤러에서 이루어지는 것이 자연스럽다.

저도 페드로의 생각과 완전 같아요. 그런 상황이라면 controller 에서 만들 것 같습니다. 다음과 같은 두 방법도 존재해요 :

  1. LadderDto 를 만든다
  2. LineDto.asList(ladder) 또는 LineDto.asList(ladder.getLadder()) 와 같은 정적 팩토리 메서드를 LineDto 쪽에 만들어준다.

Copy link
Member Author

@hw0603 hw0603 Mar 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이제야 생각 정리가 좀 된 것 같아요! 감사합니다🙂

LineDto.asList(ladder) 또는 LineDto.asList(ladder.getLadder()) 와 같은 정적 팩토리 메서드를 LineDto 쪽에 만들어준다.

LineDto 라는 객체에서 List<LineDto>를 만들 수 있는 건 어색하지 않은 상황인가요? 저런 구현을 생각을 하긴 했었는데 저렇게 해도 되나 싶어서 우선 적용하지 않았었거든요🤔

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

음 누군가는 어색하다고 할 수도 있을 것 같은데, 저는 딱히 문제 없다고 생각해요!

}
21 changes: 16 additions & 5 deletions src/main/java/ladder/model/Line.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

public class Line {
private final List<LadderPath> row;
private final List<Boolean> connected;

public Line(List<LadderPath> row) {
validate(row);
this.row = row;
this.connected = calculateConnectedPosition();
}

private void validate(List<LadderPath> row) {
Expand All @@ -22,6 +24,12 @@ private void validate(List<LadderPath> row) {
}
}

private List<Boolean> calculateConnectedPosition() {
return IntStream.range(0, row.size() - 1)
.mapToObj(idx -> LadderPath.isPathExist(row.get(idx), row.get(idx + 1)))
.toList();
}

private boolean isLeftOnFirst(List<LadderPath> row) {
return row.get(0) == LEFT;
}
Expand All @@ -44,13 +52,16 @@ private boolean isRightAlwaysExistBeforeLeft(List<LadderPath> row) {
.allMatch(idx -> row.get(idx).equals(RIGHT));
}

public int size() {
return row.size();
public int climbDown(int position) {
LadderPath path = row.get(position);
return position + path.direction;
}

public List<Boolean> getConnected() {
return IntStream.range(0, row.size() - 1)
.mapToObj(idx -> row.get(idx).equals(RIGHT))
.toList();
return connected;
}

public int size() {
return row.size();
}
}
9 changes: 8 additions & 1 deletion src/main/java/ladder/model/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ public Player(String name) {

private void validate(String name) {
if (isNameLengthLongerThanMaxLength(name)) {
throw new IllegalArgumentException("이름의 길이는 5를 초과할 수 없다.");
throw new IllegalArgumentException("이름의 길이는 5를 초과할 수 없습니다.");
}
if (isNameEmpty(name)) {
throw new IllegalArgumentException("이름이 비어 있습니다.");
}
if (!isNameFormatValid(name)) {
throw new IllegalArgumentException("이름은 영문자와 숫자로 구성되어야 합니다.");
}
if (isProhibitedName(name)) {
throw new IllegalArgumentException("사용할 수 없는 이름입니다.");
}
}

private boolean isNameLengthLongerThanMaxLength(String name) {
Expand All @@ -35,6 +38,10 @@ private boolean isNameFormatValid(String name) {
return name.matches(NAME_PATTERN);
}

private boolean isProhibitedName(String name) {
return name.equals("all");
}

public String getName() {
return name;
}
Expand Down
69 changes: 69 additions & 0 deletions src/main/java/ladder/service/LadderGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package ladder.service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import ladder.model.Ladder;
import ladder.model.Players;

public class LadderGame {
private final Players players;
private final List<String> rewards;
private final Ladder ladder;

private LadderGame(Players ladderPlayers, List<String> rewards, Ladder ladder) {
this.players = ladderPlayers;
this.rewards = rewards;
this.ladder = ladder;
}

public static LadderGame from(Players ladderPlayers, List<String> rewards, Ladder ladder) {
validate(ladderPlayers, rewards, ladder);
return new LadderGame(ladderPlayers, rewards, ladder);
}

private static void validate(Players players, List<String> rewards, Ladder ladder) {
if (playerAndLadderDoesNotMatch(players, ladder)) {
throw new IllegalArgumentException("참여자의 수와 사다리의 폭이 일치하지 않습니다.");
}
if (playerAndRewardDoesNotMatch(players, rewards)) {
throw new IllegalArgumentException("참여자의 수와 실행 결과의 수가 일치하지 않습니다.");
}
}

private static boolean playerAndLadderDoesNotMatch(Players players, Ladder ladder) {
return players.getSize() != ladder.getWidth();
}

private static boolean playerAndRewardDoesNotMatch(Players players, List<String> rewards) {
return players.getSize() != rewards.size();
}

public Map<String, String> play() {
List<Integer> positionAfterClimb = ladder.climb();
List<String> playersPositionAfterClimb = positionAfterClimb.stream()
.map(players.getPlayerNames()::get)
.toList();

return createGameResult(playersPositionAfterClimb);
}

private Map<String, String> createGameResult(List<String> finalPosition) {
return IntStream.range(0, finalPosition.size())
.boxed()
.collect(Collectors.toMap(finalPosition::get, rewards::get));
}

public List<String> getPlayerNames() {
return players.getPlayerNames();
}

public List<String> getRewards() {
return rewards;
}

public Ladder getLadder() {
return ladder;
}
}
Loading