code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,85 @@ +package model.request; + +import utils.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class HttpRequest { + private HttpRequestLine httpRequestLine; + private HttpRequestHeader httpRequestHeader; + + private String body = ""; + + private HttpRequest(BufferedReader br) throws IOException { + String line = br.readLine(); + httpRequestLine = new HttpRequestLine(line); + httpRequestHeader = new HttpRequestHeader(br); + setBody(br); + } + + public static HttpRequest of(InputStream in) throws IOException { + return new HttpRequest(new BufferedReader(new InputStreamReader(in))); + } + + private void setBody(BufferedReader br) throws IOException { + while(br.ready()){ + body = IOUtils.readData(br, Integer.parseInt(getHeader("Content-Length"))); + } + } + + public String getBody() { + return body; + } + + public Map<String, String> getParsedBody(){ + Map<String, String> parsedBody = new HashMap<>(); + String[] queryParams = body.split("&"); + Arrays.stream(queryParams).forEach((param) -> { + String[] args = param.split("=", 2); + parsedBody.put(args[0].trim(), args[1].trim()); + }); + return parsedBody; + } + + public String getCookie(String cookieParam){ + Map<String, String> parsedCookie = new HashMap<>(); + String cookieHeader = getHeader("Cookie"); + + String[] cookies = cookieHeader.split(";"); + Arrays.stream(cookies).forEach((cookie) -> { + String[] args = cookie.split("=", 2); + parsedCookie.put(args[0].trim(), args[1].trim()); + }); + return parsedCookie.get(cookieParam); + } + + public Map<String, String> getHeaderMap() { + return httpRequestHeader.getHeaderMap(); + } + + public String getHeader(String key){ + return httpRequestHeader.getHeader(key); + } + + public String getMethod() { + return httpRequestLine.getMethod(); + } + + public String getPath() { + return httpRequestLine.getPath(); + } + + public String getProtocol() { + return httpRequestLine.getProtocol(); + } + + public Map<String, String> getQueryParameterMap() { + return httpRequestLine.getQueryParameterMap(); + } +}
Java
InputStream 을 받아서 HttpRequest 인스턴스를 생성하는 static method 로 변경해보는건 어떨까요?
@@ -0,0 +1,12 @@ +.header { + display: flex; + justify-content: space-between; + align-items: center; + position: fixed; + width: calc(430px - 48px); + height: 64px; + padding: 0 24px; + background-color: black; + color: #fff; + z-index: 1000; +}
Unknown
피그마 시안 width가 430px이었고, 양 옆 padding이 24였어서 이런 calc 코드가 나왔습니다.. ✋🏻보통 이렇게 처리하시는지, 혹은 더 유연한 방식이 있는지 궁금합니다.
@@ -4,13 +4,15 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview", "test": "vitest" }, "dependencies": { + "@jaymyong66/simple-modal": "^0.0.7", + "@tanstack/react-query": "^5.40.1", "react": "^18.2.0", "react-dom": "^18.2.0" },
Unknown
굉장히 사소하지만 커밋 메시지 관련 리뷰 남겨봅니다..! 저는 패키지 관련 설치는 chore를 사용합니다..! 이게 완벽하게 정확한 지는 검증해보지 않았으나, 참고해보면 좋을 것 같아요! [좋은 커밋 메시지 작성법](https://velog.io/@iamjm29/Git-%EC%A2%8B%EC%9D%80-%EC%BB%A4%EB%B0%8B-%EB%A9%94%EC%8B%9C%EC%A7%80-%EC%9E%91%EC%84%B1%EB%B2%95) [AngularJS Commit Convention](https://gist.github.com/stephenparish/9941e89d80e2bc58a153)
@@ -0,0 +1,12 @@ +.header { + display: flex; + justify-content: space-between; + align-items: center; + position: fixed; + width: calc(430px - 48px); + height: 64px; + padding: 0 24px; + background-color: black; + color: #fff; + z-index: 1000; +}
Unknown
대박 왜 이제 알았지..? 👍
@@ -0,0 +1,109 @@ +package chess.domain.board; + +import chess.domain.command.MoveOptions; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.player.Player; +import chess.domain.player.Position; + +import java.util.Collection; + +public class Board { + private final Player white; + private final Player black; + + public Board() { + this.white = new Player(Color.WHITE); + this.black = new Player(Color.BLACK); + } + + public void move(final MoveOptions moveOptions, final boolean isWhiteTurn) { + Player player = currentPlayer(isWhiteTurn); + Player enemy = currentPlayer(!isWhiteTurn); + Position source = moveOptions.getSource(); + Position target = moveOptions.getTarget(); + + validate(player, enemy, source, target); + + enemy.removePieceOn(target); + movePiece(player, source, target); + } + + private Player currentPlayer(final boolean isWhiteTurn) { + if (isWhiteTurn) { + return white; + } + return black; + } + + private void validate(final Player player, final Player enemy, final Position source, final Position target) { + validateSourceOwner(enemy, source); + validateSamePosition(source, target); + validateTarget(player, target); + validateKingMovable(player, enemy, source, target); + } + + private void validateSourceOwner(final Player enemy, final Position source) { + if (enemy.hasPieceOn(source)) { + throw new IllegalArgumentException("자신의 기물만 움직일 수 있습니다."); + } + } + + private void validateSamePosition(final Position source, final Position target) { + if (source.equals(target)) { + throw new IllegalArgumentException("출발 위치와 도착 위치가 같을 수 없습니다."); + } + } + + private void validateTarget(final Player player, final Position target) { + if (player.hasPieceOn(target)) { + throw new IllegalArgumentException("같은 색상의 기물은 공격할 수 없습니다."); + } + } + + private void validateKingMovable(final Player player, final Player enemy, final Position source, final Position target) { + if (player.hasKingOn(source) && enemy.canAttack(target)) { + throw new IllegalArgumentException("킹은 상대방이 공격 가능한 위치로 이동할 수 없습니다."); + } + } + + private void movePiece(final Player player, final Position source, final Position target) { + Collection<Position> paths = player.findPaths(source, target); + validatePathsEmpty(paths); + player.update(source, target); + } + + private void validatePathsEmpty(final Collection<Position> paths) { + boolean isWhiteBlocked = paths.stream() + .anyMatch(white::hasPieceOn); + boolean isBlackBlocked = paths.stream() + .anyMatch(black::hasPieceOn); + + if (isWhiteBlocked || isBlackBlocked) { + throw new IllegalArgumentException("기물을 통과하여 이동할 수 없습니다."); + } + } + + public Piece findBy(final Position position) { + if (white.hasPieceOn(position)) { + return white.findPieceBy(position); + } + + return black.findPieceBy(position); + } + + public boolean isEmpty(final Position position) { + return !white.hasPieceOn(position) && !black.hasPieceOn(position); + } + + public Status getStatus() { + double whiteScore = white.sumScores(); + double blackScore = black.sumScores(); + + return new Status(whiteScore, blackScore, white.isKingDead(), black.isKingDead()); + } + + public boolean isEnd() { + return white.isKingDead() || black.isKingDead(); + } +}
Java
점수 계산에 대한 명령어(`status`) 적용이 안되어 있는 것 같아요! :)
@@ -0,0 +1,58 @@ +package chess.domain.command; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public enum Command { + + START("start"), + END("end"), + MOVE("move"), + STATUS("status"); + + private static final Map<String, Command> COMMANDS = createCommands(); + + private static Map<String, Command> createCommands() { + Map<String, Command> commands = new HashMap<>(); + + Arrays.stream(values()) + .forEach(command -> commands.put(command.command, command)); + + return commands; + } + + private final String command; + + Command(final String command) { + this.command = command; + } + + public static Command of(final String command) { + Command foundCommand = COMMANDS.get(command); + + if (foundCommand == null) { + throw new IllegalArgumentException("유효하지 않은 명령어입니다."); + } + + return foundCommand; + } + + public void validateInitialCommand() { + if (isStatus() || isMove()) { + throw new IllegalArgumentException(String.format("%s 또는 %s를 입력해주세요.", START.command, END.command)); + } + } + + public boolean isEnd() { + return this.equals(END); + } + + public boolean isMove() { + return this.equals(MOVE); + } + + public boolean isStatus() { + return this.equals(STATUS); + } +}
Java
Command도 Enum으로 관리해보면 어떨까요? :)
@@ -0,0 +1,127 @@ +package chess.domain.player; + +import chess.domain.board.File; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.piece.PieceResolver; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Player { + + private final Map<Position, Piece> pieces; + private final AttackRange attackRange; + + public Player(final Color color) { + pieces = new HashMap<>(PieceFactory.createPieces(color)); + attackRange = new AttackRange(pieces); + } + + public double sumScores() { + double pawnScores = calculatePawnScores(); + double scoresExceptPawn = calculateScoresExceptPawn(); + + return pawnScores + scoresExceptPawn; + } + + private double calculatePawnScores() { + List<Position> pawnPositions = findPawnPositions(); + Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions); + + return pawnCountsOnSameFile.values() + .stream() + .mapToDouble(PieceResolver::sumPawnScores) + .sum(); + } + + private List<Position> findPawnPositions() { + return pieces.keySet() + .stream() + .filter(position -> { + Piece piece = pieces.get(position); + return piece.isPawn(); + }) + .collect(Collectors.toList()); + } + + private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) { + Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class); + + pawnPositions.stream() + .map(Position::getFile) + .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1)); + + return pawnCountOnSameFile; + } + + private double calculateScoresExceptPawn() { + return pieces.values() + .stream() + .filter(Piece::isNotPawn) + .mapToDouble(PieceResolver::findScoreBy) + .sum(); + } + + public Collection<Position> findPaths(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + + return sourcePiece.findPath(source, target); + } + + public Piece findPieceBy(final Position position) { + if (isEmptyOn(position)) { + throw new IllegalArgumentException("해당 위치에 기물이 존재하지 않습니다."); + } + + return pieces.get(position); + } + + private boolean isEmptyOn(final Position position) { + return !pieces.containsKey(position); + } + + public void update(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + movePiece(source, target, sourcePiece); + attackRange.update(source, target, sourcePiece); + } + + private void movePiece(final Position source, final Position target, final Piece sourcePiece) { + pieces.put(target, sourcePiece); + pieces.remove(source); + } + + public boolean hasKingOn(final Position position) { + Piece piece = findPieceBy(position); + + return piece.isKing(); + } + + public boolean isKingDead() { + return pieces.values().stream() + .noneMatch(Piece::isKing); + } + + public boolean canAttack(final Position position) { + return attackRange.contains(position); + } + + public void removePieceOn(final Position position) { + if (isEmptyOn(position)) { + return; + } + + attackRange.remove(position, pieces.get(position)); + pieces.remove(position); + } + + public boolean hasPieceOn(final Position position) { + return pieces.containsKey(position); + } +}
Java
저는 부정연산자(`!`)를 웬만하면 피하는데요 ㅎㅎ 가독성의 문제도 있고, 읽는 사람이 한번 더 해석을 해야하기 때문에 메서드를 제공하는 쪽에서 한번 더 추상화시키면 좋을 것 같아요 ㅎㅎ `piece.isNotPawn()`
@@ -0,0 +1,127 @@ +package chess.domain.player; + +import chess.domain.board.File; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.piece.PieceResolver; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Player { + + private final Map<Position, Piece> pieces; + private final AttackRange attackRange; + + public Player(final Color color) { + pieces = new HashMap<>(PieceFactory.createPieces(color)); + attackRange = new AttackRange(pieces); + } + + public double sumScores() { + double pawnScores = calculatePawnScores(); + double scoresExceptPawn = calculateScoresExceptPawn(); + + return pawnScores + scoresExceptPawn; + } + + private double calculatePawnScores() { + List<Position> pawnPositions = findPawnPositions(); + Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions); + + return pawnCountsOnSameFile.values() + .stream() + .mapToDouble(PieceResolver::sumPawnScores) + .sum(); + } + + private List<Position> findPawnPositions() { + return pieces.keySet() + .stream() + .filter(position -> { + Piece piece = pieces.get(position); + return piece.isPawn(); + }) + .collect(Collectors.toList()); + } + + private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) { + Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class); + + pawnPositions.stream() + .map(Position::getFile) + .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1)); + + return pawnCountOnSameFile; + } + + private double calculateScoresExceptPawn() { + return pieces.values() + .stream() + .filter(Piece::isNotPawn) + .mapToDouble(PieceResolver::findScoreBy) + .sum(); + } + + public Collection<Position> findPaths(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + + return sourcePiece.findPath(source, target); + } + + public Piece findPieceBy(final Position position) { + if (isEmptyOn(position)) { + throw new IllegalArgumentException("해당 위치에 기물이 존재하지 않습니다."); + } + + return pieces.get(position); + } + + private boolean isEmptyOn(final Position position) { + return !pieces.containsKey(position); + } + + public void update(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + movePiece(source, target, sourcePiece); + attackRange.update(source, target, sourcePiece); + } + + private void movePiece(final Position source, final Position target, final Piece sourcePiece) { + pieces.put(target, sourcePiece); + pieces.remove(source); + } + + public boolean hasKingOn(final Position position) { + Piece piece = findPieceBy(position); + + return piece.isKing(); + } + + public boolean isKingDead() { + return pieces.values().stream() + .noneMatch(Piece::isKing); + } + + public boolean canAttack(final Position position) { + return attackRange.contains(position); + } + + public void removePieceOn(final Position position) { + if (isEmptyOn(position)) { + return; + } + + attackRange.remove(position, pieces.get(position)); + pieces.remove(position); + } + + public boolean hasPieceOn(final Position position) { + return pieces.containsKey(position); + } +}
Java
위에도 부정연산자 피드백을 남겼는데요, 여기도 한번더 추상화시키면 좋을 것 같아요 ㅎㅎ 전체적으로 한번 더 체크해봐도 좋겠네요 :)
@@ -0,0 +1,109 @@ +package chess.domain.board; + +import chess.domain.command.MoveOptions; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.player.Player; +import chess.domain.player.Position; + +import java.util.Collection; + +public class Board { + private final Player white; + private final Player black; + + public Board() { + this.white = new Player(Color.WHITE); + this.black = new Player(Color.BLACK); + } + + public void move(final MoveOptions moveOptions, final boolean isWhiteTurn) { + Player player = currentPlayer(isWhiteTurn); + Player enemy = currentPlayer(!isWhiteTurn); + Position source = moveOptions.getSource(); + Position target = moveOptions.getTarget(); + + validate(player, enemy, source, target); + + enemy.removePieceOn(target); + movePiece(player, source, target); + } + + private Player currentPlayer(final boolean isWhiteTurn) { + if (isWhiteTurn) { + return white; + } + return black; + } + + private void validate(final Player player, final Player enemy, final Position source, final Position target) { + validateSourceOwner(enemy, source); + validateSamePosition(source, target); + validateTarget(player, target); + validateKingMovable(player, enemy, source, target); + } + + private void validateSourceOwner(final Player enemy, final Position source) { + if (enemy.hasPieceOn(source)) { + throw new IllegalArgumentException("자신의 기물만 움직일 수 있습니다."); + } + } + + private void validateSamePosition(final Position source, final Position target) { + if (source.equals(target)) { + throw new IllegalArgumentException("출발 위치와 도착 위치가 같을 수 없습니다."); + } + } + + private void validateTarget(final Player player, final Position target) { + if (player.hasPieceOn(target)) { + throw new IllegalArgumentException("같은 색상의 기물은 공격할 수 없습니다."); + } + } + + private void validateKingMovable(final Player player, final Player enemy, final Position source, final Position target) { + if (player.hasKingOn(source) && enemy.canAttack(target)) { + throw new IllegalArgumentException("킹은 상대방이 공격 가능한 위치로 이동할 수 없습니다."); + } + } + + private void movePiece(final Player player, final Position source, final Position target) { + Collection<Position> paths = player.findPaths(source, target); + validatePathsEmpty(paths); + player.update(source, target); + } + + private void validatePathsEmpty(final Collection<Position> paths) { + boolean isWhiteBlocked = paths.stream() + .anyMatch(white::hasPieceOn); + boolean isBlackBlocked = paths.stream() + .anyMatch(black::hasPieceOn); + + if (isWhiteBlocked || isBlackBlocked) { + throw new IllegalArgumentException("기물을 통과하여 이동할 수 없습니다."); + } + } + + public Piece findBy(final Position position) { + if (white.hasPieceOn(position)) { + return white.findPieceBy(position); + } + + return black.findPieceBy(position); + } + + public boolean isEmpty(final Position position) { + return !white.hasPieceOn(position) && !black.hasPieceOn(position); + } + + public Status getStatus() { + double whiteScore = white.sumScores(); + double blackScore = black.sumScores(); + + return new Status(whiteScore, blackScore, white.isKingDead(), black.isKingDead()); + } + + public boolean isEnd() { + return white.isKingDead() || black.isKingDead(); + } +}
Java
앗.. 페어분 repo에서 pull하고 푸시를 안했었네요 죄송합니다ㅠㅠ 반영하였습니다!
@@ -0,0 +1,127 @@ +package chess.domain.player; + +import chess.domain.board.File; +import chess.domain.piece.Color; +import chess.domain.piece.Piece; +import chess.domain.piece.PieceFactory; +import chess.domain.piece.PieceResolver; + +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Player { + + private final Map<Position, Piece> pieces; + private final AttackRange attackRange; + + public Player(final Color color) { + pieces = new HashMap<>(PieceFactory.createPieces(color)); + attackRange = new AttackRange(pieces); + } + + public double sumScores() { + double pawnScores = calculatePawnScores(); + double scoresExceptPawn = calculateScoresExceptPawn(); + + return pawnScores + scoresExceptPawn; + } + + private double calculatePawnScores() { + List<Position> pawnPositions = findPawnPositions(); + Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions); + + return pawnCountsOnSameFile.values() + .stream() + .mapToDouble(PieceResolver::sumPawnScores) + .sum(); + } + + private List<Position> findPawnPositions() { + return pieces.keySet() + .stream() + .filter(position -> { + Piece piece = pieces.get(position); + return piece.isPawn(); + }) + .collect(Collectors.toList()); + } + + private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) { + Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class); + + pawnPositions.stream() + .map(Position::getFile) + .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1)); + + return pawnCountOnSameFile; + } + + private double calculateScoresExceptPawn() { + return pieces.values() + .stream() + .filter(Piece::isNotPawn) + .mapToDouble(PieceResolver::findScoreBy) + .sum(); + } + + public Collection<Position> findPaths(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + + return sourcePiece.findPath(source, target); + } + + public Piece findPieceBy(final Position position) { + if (isEmptyOn(position)) { + throw new IllegalArgumentException("해당 위치에 기물이 존재하지 않습니다."); + } + + return pieces.get(position); + } + + private boolean isEmptyOn(final Position position) { + return !pieces.containsKey(position); + } + + public void update(final Position source, final Position target) { + Piece sourcePiece = findPieceBy(source); + movePiece(source, target, sourcePiece); + attackRange.update(source, target, sourcePiece); + } + + private void movePiece(final Position source, final Position target, final Piece sourcePiece) { + pieces.put(target, sourcePiece); + pieces.remove(source); + } + + public boolean hasKingOn(final Position position) { + Piece piece = findPieceBy(position); + + return piece.isKing(); + } + + public boolean isKingDead() { + return pieces.values().stream() + .noneMatch(Piece::isKing); + } + + public boolean canAttack(final Position position) { + return attackRange.contains(position); + } + + public void removePieceOn(final Position position) { + if (isEmptyOn(position)) { + return; + } + + attackRange.remove(position, pieces.get(position)); + pieces.remove(position); + } + + public boolean hasPieceOn(final Position position) { + return pieces.containsKey(position); + } +}
Java
넵넵! 해당 피드백 읽은 후 부정연산자 사용하는 곳 모두 수정해주었습니다 :)
@@ -0,0 +1,58 @@ +package chess.domain.command; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public enum Command { + + START("start"), + END("end"), + MOVE("move"), + STATUS("status"); + + private static final Map<String, Command> COMMANDS = createCommands(); + + private static Map<String, Command> createCommands() { + Map<String, Command> commands = new HashMap<>(); + + Arrays.stream(values()) + .forEach(command -> commands.put(command.command, command)); + + return commands; + } + + private final String command; + + Command(final String command) { + this.command = command; + } + + public static Command of(final String command) { + Command foundCommand = COMMANDS.get(command); + + if (foundCommand == null) { + throw new IllegalArgumentException("유효하지 않은 명령어입니다."); + } + + return foundCommand; + } + + public void validateInitialCommand() { + if (isStatus() || isMove()) { + throw new IllegalArgumentException(String.format("%s 또는 %s를 입력해주세요.", START.command, END.command)); + } + } + + public boolean isEnd() { + return this.equals(END); + } + + public boolean isMove() { + return this.equals(MOVE); + } + + public boolean isStatus() { + return this.equals(STATUS); + } +}
Java
상수들이기 때문에 Enum으로 관리하는 편이 더 좋겠네요! Enum 객체로 수정하였습니다 :)
@@ -0,0 +1,46 @@ +package lottodomain; + +import java.util.ArrayList; +import java.util.List; + +public class LottoGame { + private static final int PRICE_PER_LOTTO = 1000; + + private List<Lotto> allLotto; + private int numberOfAllLotto; + + public LottoGame(int inputMoney, List<List<Integer>> manualLottoNos) { + numberOfAllLotto = inputMoney / PRICE_PER_LOTTO; + allLotto = issueLottos(manualLottoNos); + } + + public LottoAnalyzer getLottoAnalyzer(WinningNos winningNos) { + return new LottoAnalyzer(allLotto, winningNos); + } + + public List<Lotto> getAllLotto() { + return allLotto; + } + + private List<Lotto> issueLottos(List<List<Integer>> manualLottoNos) { + List<Lotto> lottos = issueManualLottos(manualLottoNos); + lottos.addAll(issueAutoLottos(numberOfAllLotto - lottos.size())); + return lottos; + } + + private List<Lotto> issueManualLottos(List<List<Integer>> manualLottoNos) { + List<Lotto> ManualLottos = new ArrayList<>(); + for (int i = 0; i < manualLottoNos.size(); i++) { + ManualLottos.add(LottoGenerator.generateLottoWithNos(manualLottoNos.get(i))); + } + return ManualLottos; + } + + private List<Lotto> issueAutoLottos(int numberOfAutoLottos) { + List<Lotto> autoLottos = new ArrayList<>(); + for (int i = 0; i < numberOfAutoLottos; i++) { + autoLottos.add(LottoGenerator.generateAutoLotto()); + } + return autoLottos; + } +}
Java
변수명이 대문자로 시작하네요 ~
@@ -0,0 +1,25 @@ +package lottodomain; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class LottoGenerator { + private static final List<Integer> LOTTO_NO_POOLS = IntStream.rangeClosed(1, 45).boxed().collect(Collectors.toList()); + ; + + public static Lotto generateLottoWithNos(List<Integer> lottoNos) { + return new Lotto(lottoNos); + } + + public static Lotto generateAutoLotto() { + return generateLottoWithNos(getRandomNos()); + } + + + private static List<Integer> getRandomNos() { + Collections.shuffle(LOTTO_NO_POOLS); + return LOTTO_NO_POOLS.subList(0, 6); + } +}
Java
Lotto 에 factory method 을 추가하여 생성해보면 어떨까요? ex> Lotto.ofAuto(), Lotto.ofManual("1,2,3,4,5,6)
@@ -0,0 +1,25 @@ +package lottodomain; + +public class LottoNo { + private Integer value; + + public LottoNo(int number) { + value = number; + } + + public Integer getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNo lottoNo = (LottoNo) o; + return value == lottoNo.value; + } +}
Java
LottoNo 를 생성할 때 range 에 대한 조건을 검증하면 좀 더 의미 있는 wrapping class 가 되지 않을까요?
@@ -0,0 +1,25 @@ +package lottodomain; + +public class LottoNo { + private Integer value; + + public LottoNo(int number) { + value = number; + } + + public Integer getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNo lottoNo = (LottoNo) o; + return value == lottoNo.value; + } +}
Java
문제 : "모든 원시값과 문자열을 포장한다." 원칙에 따라 인스턴스를 생성하다보니 너무 많은 객체가 생성되고, GC가 되어 성능상 문제가 발생한다. 특히 로또 번호 하나까지 객체로 포장할 경우 생성되는 인스턴스의 수는 상당히 늘어나는 문제가 발생한다. 위와 같은 문제는 어떻게 해결할 수 있을까요? (키워드 : static, map)
@@ -0,0 +1,25 @@ +package lottodomain; + +public class LottoNo { + private Integer value; + + public LottoNo(int number) { + value = number; + } + + public Integer getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LottoNo lottoNo = (LottoNo) o; + return value == lottoNo.value; + } +}
Java
불변의 값을 wrapping 한 클래스이므로 final int value; 로 선언해보면 어떨까요?
@@ -0,0 +1,49 @@ +package lottoview; + +import lottodomain.Lotto; +import lottodomain.LottoAnalyzer; +import lottodomain.LottoNo; +import lottodomain.Rank; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class OutputView { + public static void showAllLottos(List<Lotto> allLotto, int numberOfManualLottos) { + int numberOfAutoLottos = allLotto.size() - numberOfManualLottos; + System.out.printf("수동으로 %d장, 자동으로 %d장을 구매했습니다.\n", numberOfManualLottos, numberOfAutoLottos); + allLotto.stream().forEach(lotto -> showLotto(lotto)); + } + + public static void showLotto(Lotto lotto) { + List<LottoNo> lottoNos = lotto.getLottoNos(); + System.out.println(lottoNos.stream().map(LottoNo::getValue).map(number -> number.toString()) + .collect(Collectors.joining(", ", "[", "]"))); + } + + public static void showAnalysis(LottoAnalyzer lottoAnalyzer) { + showWRanks(lottoAnalyzer); + showEarningRate(lottoAnalyzer.calculateEarningRate()); + } + + public static void showRankCount(Rank rank, int count) { + System.out.printf("%d개 일치 (%d원)- %d개\n", rank.getCountOfMatch(), rank.getWinningMoney(), count); + } + + public static void showEarningRate(double earningRate) { + System.out.printf("총 수익률은 %.1f%%입니다.\n", earningRate); + } + + private static void showWRanks(LottoAnalyzer lottoAnalyzer) { + System.out.println("당첨 통계"); + System.out.println("---------"); + List<Rank> prize = Stream.of(Rank.values()).collect(Collectors.toList()); + prize.remove(Rank.MISS); + for (int i = prize.size() - 1; i >= 0; i--) { + int count = lottoAnalyzer.countRank(prize.get(i)); + showRankCount(prize.get(i), count); + } + } +}
Java
analyzer 가 outputview 에 와서 비즈니스 로직을 수행하고 있는데요 게임의 결과를 담는 LottoResults(DTO) 클래스와 Lotto list 를 감싸는 Lottos 클래스를 만들어서 outputview 에서 비즈니스 로직이 실행되지 않도록 변경해보면 어떨까요?
@@ -0,0 +1,63 @@ +package lottodomain; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class LottoAnalyzerTest { + private static final double DELTA = 1e-15; + + private List<Lotto> lottos; + private LottoAnalyzer lottoAnalyzer; + private WinningNos winningNos; + + @Before + public void setUp() throws Exception { + lottos = new ArrayList<>(); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6))); // FIRST + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 7))); // SECOND + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 8))); // THIRD + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 7, 8))); // FOURTH + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 7, 8, 9))); // FIFTH + lottos.add(new Lotto(Arrays.asList(1, 2, 7, 8, 9, 10))); // MISS + winningNos = new WinningNos(Arrays.asList(1, 2, 3, 4, 5, 6), 7); + lottoAnalyzer = new LottoAnalyzer(lottos, winningNos); + } + + @Test + public void calculateRankOfLotto() { + List<Rank> ranks = Arrays.asList(Rank.values()); + for (int i = 0; i < lottos.size(); i++) { + assertEquals(ranks.get(i), lottoAnalyzer.calculateRankOfLotto(lottos.get(i), winningNos)); + } + } + + @Test + public void calculateEarnedMoney() { + assertEquals(2031555000, lottoAnalyzer.calculateEarnedMoney()); + } + + @Test + public void calculateEarningRate() { + assertEquals(33859250.0, lottoAnalyzer.calculateEarningRate(), DELTA); + } + + @Test + public void countRank() { + List<Rank> ranks = Arrays.asList(Rank.values()); + for (int i = 0; i < ranks.size(); i++) { + assertEquals(1, lottoAnalyzer.countRank(ranks.get(i))); + } + } + + @After + public void tearDown() throws Exception { + lottos = null; + } +} \ No newline at end of file
Java
좋은 유닛테스트 작성법에는 F.I.R.S.T 라는 원칙이 있는데요 https://coding-start.tistory.com/261 첨부하고 갑니다 ~
@@ -0,0 +1,47 @@ +package lottodomain; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.Assert.*; + +public class LottoGameTest { + private LottoGame lottoGame; + List<List<Integer>> manualLottoNumbers; + + private void assertArrayEquals(List<Lotto> expectedLottos, List<Lotto> subList) { + for (int i = 0; i < expectedLottos.size(); i++) { + assertEquals(expectedLottos.get(i), subList.get(i)); + } + } + + @Before + public void setUp() throws Exception { + manualLottoNumbers = new ArrayList<>(); + manualLottoNumbers.add(Arrays.asList(1, 2, 3, 4, 5, 6)); + manualLottoNumbers.add(Arrays.asList(1, 4, 11, 15, 19, 23)); + manualLottoNumbers.add(Arrays.asList(4, 10, 17, 25, 34, 42)); + } + + @Test + public void setManualLottos() { + lottoGame = new LottoGame(10000, manualLottoNumbers); + assertEquals(10, lottoGame.getAllLotto().size()); + + List<Lotto> expectedLottos = manualLottoNumbers.stream().map(numbers -> LottoGenerator.generateLottoWithNos(numbers)) + .collect(Collectors.toList()); + assertArrayEquals(expectedLottos, lottoGame.getAllLotto().subList(0, 3)); + } + + @After + public void tearDown() throws Exception { + lottoGame = null; + manualLottoNumbers = null; + } +} \ No newline at end of file
Java
private method 는 public 보다 아래에 위치시켜주는게 가독성에 좋습니다 ~
@@ -0,0 +1,50 @@ +package lottodomain; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class WinningNosTest { + private WinningNos winningNos; + + @Before + public void setUp() throws Exception { + winningNos = new WinningNos(Arrays.asList(1, 2, 3, 4, 5, 6), 7); + } + + @Test + public void countMatchOf() { + List<Lotto> lottos = new ArrayList<>(); + lottos.add(new Lotto(Arrays.asList(8, 9, 10, 11, 12, 13))); + lottos.add(new Lotto(Arrays.asList(1, 8, 9, 10, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 9, 10, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 10, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 11, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 12))); + lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6))); + + for (int i = 0; i < lottos.size(); i++) { + assertEquals(i, winningNos.countMatchOf(lottos.get(i))); + } + } + + @Test + public void isBonus() { + Lotto trueLotto = new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); + Lotto falseLotto = new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6, 8)); + + assertTrue(winningNos.isBonus(trueLotto)); + assertFalse(winningNos.isBonus(falseLotto)); + } + + @After + public void tearDown() throws Exception { + winningNos = null; + } +} \ No newline at end of file
Java
전체적으로 코드에 비해 테스트 쪽이 조금 아쉬워서 시간이 되신다면 TDD 방법론을 통해 로또나 레이싱 게임을 다시 구현해보는 것도 많이 도움이 되실 것 같습니다
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // 메인으로 이동할 때 로직 + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // 회원가입시 사용할 로직 + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // 로그인시 사용할 로직 + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="비밀번호" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="로그인" + onClick={goToMain} + /> + </form> + <p>비밀번호를 잊으셨나요?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
이 두 조건을 &&로 걸면 state를 하나만 사용하고 validation을 확인할 수 있지 않을까요? 왜 유즈이펙트를 쓰셨는지 궁금합니다.
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // 메인으로 이동할 때 로직 + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // 회원가입시 사용할 로직 + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // 로그인시 사용할 로직 + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="비밀번호" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="로그인" + onClick={goToMain} + /> + </form> + <p>비밀번호를 잊으셨나요?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
id와 pw로 한번에 validation하고 activateBtn에 True/false를 지정하면 될 것 같습니다. isValidatedId나 isValidatedPw는 크게 필요하지 않을 것 같아요. 불필요한 리랜더링도 줄일 수 있다고 생각하는데 어떻게 생각하시나요?
@@ -0,0 +1,66 @@ +@use '../../../styles/mixin.scss' as mixin; +@use '../../../styles/color.scss' as clr; + +body { + background: clr.$bg-login; + + .login { + position: relative; + top: -80px; + + #wrapper { + @include mixin.flex($align: center); + position: relative; + flex-direction: column; + width: 700px; + height: 761px; + border: 1px solid clr.$clr-border; + + h1 { + margin-top: 90px; + margin-bottom: 130px; + font-size: 81px; + font-family: 'Lobster', cursive; + } + + .login_form { + input { + display: block; + width: 536px; + height: 76px; + margin-bottom: 12px; + padding-left: 10px; + background: #fafafa; + border: 1px solid clr.$clr-border; + border-radius: 3px; + font-size: 16px; + } + + input[type='button'] { + display: flex; + align-items: center; + justify-content: center; + width: 536px; + height: 60px; + margin-top: 16px; + background-color: clr.$clr-primary; + opacity: 0.5; + border: none; + border-radius: 4px; + font-size: 16px; + color: #fff; + + &.activated { + opacity: 1; + } + } + } + + p { + position: absolute; + bottom: 20px; + color: #043667; + } + } + } +}
Unknown
input이 inline-block이고 수직으로 정렬하려고 display: flex를 쓰신 것 같습니다. 굉장히 좋은데요 저는 Input을 display: block해주는 것도 괜찮은 방법이지 않을까 생각합니다.
@@ -0,0 +1,66 @@ +@use '../../../styles/mixin.scss' as mixin; +@use '../../../styles/color.scss' as clr; + +body { + background: clr.$bg-login; + + .login { + position: relative; + top: -80px; + + #wrapper { + @include mixin.flex($align: center); + position: relative; + flex-direction: column; + width: 700px; + height: 761px; + border: 1px solid clr.$clr-border; + + h1 { + margin-top: 90px; + margin-bottom: 130px; + font-size: 81px; + font-family: 'Lobster', cursive; + } + + .login_form { + input { + display: block; + width: 536px; + height: 76px; + margin-bottom: 12px; + padding-left: 10px; + background: #fafafa; + border: 1px solid clr.$clr-border; + border-radius: 3px; + font-size: 16px; + } + + input[type='button'] { + display: flex; + align-items: center; + justify-content: center; + width: 536px; + height: 60px; + margin-top: 16px; + background-color: clr.$clr-primary; + opacity: 0.5; + border: none; + border-radius: 4px; + font-size: 16px; + color: #fff; + + &.activated { + opacity: 1; + } + } + } + + p { + position: absolute; + bottom: 20px; + color: #043667; + } + } + } +}
Unknown
'로그인' 이라는 글자 센터에 맞추기 위해 display: flex주신 것 같아요. 좋은방법이지만 flex와 그 속성들이 좀 떨어져 있는 것 같습니다. 이렇게 연관되는 css속성은 붙여 주시는 게 나중에 유지보수 측면에서도 좋을 것 같아 추천 드립니다!
@@ -0,0 +1,26 @@ +import React, { useState } from 'react'; +import { AiFillDelete, AiOutlineHeart, AiFillHeart } from 'react-icons/ai'; + +const Comment = ({ id, userId, value, time, handleDelete }) => { + const [isLiked, setIsLiked] = useState(false); + + const toggleLike = () => { + setIsLiked(!isLiked); + }; + + return ( + <span id={id} className="comment"> + <strong>{userId} </strong> + {value} + <small> {time}</small> + <AiFillDelete onClick={handleDelete} className="delete" /> + {isLiked ? ( + <AiFillHeart onClick={toggleLike} className="hearts liked" /> + ) : ( + <AiOutlineHeart onClick={toggleLike} className="hearts" /> + )} + </span> + ); +}; + +export default Comment;
Unknown
저번 세션에서 멘토님이 하신 것처럼 변수명을 조금 더 구체적으로 어떤 내용을 담고 있는지를 작성해 주시면 좋을 것 같습니다. commentVal이 댓글 전체를 관리하는 배열이고 el이 각 배열의 요소이니깐 commentVal대신 allComments, el대신 comment등으로 (이건 저도 조금 애매하네요 .. 죄송합니다) (배열은 s를 붙인 변수명으로 하는 게 좋을 것 같습니다!)
@@ -0,0 +1,43 @@ +span.comment { + padding-left: 10px; + + small { + color: #a3a3a3; + } + + &:first-child { + padding: 10px; + font-weight: bold; + } + + svg { + &.delete { + display: none; + cursor: pointer; + } + + &.hearts { + color: #a3a3a3; + position: absolute; + right: 20px; + transition: color 1s; + cursor: pointer; + + path { + color: #a3a3a3; + } + } + + &.liked { + path { + color: #f00; + } + } + } + + &:hover svg { + &.delete { + display: inline-block; + } + } +}
Unknown
span에 대해서만 스타일링을 해주셨는데 이러면 다른 컴포넌트의 span에도 영향이 가지 않을까 조심스럽게 생각해 봅니다. 개인적으로 className을 주는 게 조금 더 안전할 것 같습니다 추가적으로 svg태그도 span 내부에 nesting해주시면 좋을 것 같아요. ``` svg { &.red {} &.blue {} } ```
@@ -0,0 +1,87 @@ +import React, { useState } from 'react'; +import { AiFillHeart, AiOutlineComment, AiOutlineUpload } from 'react-icons/ai'; +import { BiDotsHorizontalRounded } from 'react-icons/bi'; +import { GrBookmark } from 'react-icons/gr'; +import './Feeds.scss'; +import Comments from './Comment/Comments'; + +export default function Feeds({ userId, profileImg, img, comments }) { + const [commentVal, setCommentVal] = useState(comments); + let addedCommentVal = [...commentVal]; + const [currInputVal, setCurrInputVal] = useState(''); + + const handleInput = e => { + const { value } = e.target; + if (e.keyCode === 13) uploadComment(); + setCurrInputVal(value); + }; + + const uploadComment = e => { + e.preventDefault(); + if (!currInputVal) return; + addedCommentVal.push({ + id: addedCommentVal.length + 1, + userId: 'userid', + value: currInputVal, + time: '방금전', + }); + setCommentVal(addedCommentVal); + setCurrInputVal(''); + }; + + const handleDelete = e => { + const { id } = e.target.parentNode.parentNode; + addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id)); + setCommentVal(addedCommentVal); + }; + + return ( + <div className="feeds"> + <article> + <div className="top_menu"> + <span> + <img src={profileImg} alt="프로필" /> + {userId} + </span> + <span> + <BiDotsHorizontalRounded /> + </span> + </div> + <img src={img} alt="무화과" /> + <div className="bottom_menu"> + <span> + <AiFillHeart className="" /> + </span> + <span> + <AiOutlineComment className="" /> + </span> + <span> + <AiOutlineUpload className="" /> + </span> + <span> + <GrBookmark className="" /> + </span> + </div> + <div className="comments"> + <span>4 Likes</span> + <Comments commentArr={commentVal} handleDelete={handleDelete} /> + </div> + <form className="add_comments"> + <input + type="text" + placeholder="댓글 달기..." + className="input_upload" + onChange={handleInput} + value={currInputVal} + /> + <button + className={currInputVal ? 'activated' : ''} + onClick={uploadComment} + > + 게시 + </button> + </form> + </article> + </div> + ); +}
Unknown
굉장히 잘 짜신 것 같습니다!! 👏 그런데 순서가 조금 애매한 것 같아요. 17)에서 uploadComment 호출을 하고 31)에서 currInputVal( " " ) -> 18 ) 에서 currInputVal( e.target.value ) 순으로 진행이 된다면 댓글을 추가하더라도 input은 비워지지 않을 것 같습니다.
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
Feeds.jsx에서 .feeds의 바로 자식요소가 article이라 article을 .feeds 바로 다음에 써주는 게 좋을 것 같습니다. 그리고 height요소는 자식요소들의 높이에 따라 결정되니깐 height: 100%를 주어도 feeds의 높이가 변하지는 않을 것 같다는 생각이 드는데 혹시 설정하신 이유가 있으신가요?
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // 메인으로 이동할 때 로직 + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // 회원가입시 사용할 로직 + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // 로그인시 사용할 로직 + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="비밀번호" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="로그인" + onClick={goToMain} + /> + </form> + <p>비밀번호를 잊으셨나요?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
이 두 조건을 &&로 걸면 state를 하나만 사용하고 validation을 확인할 수 있지 않을까요? => 맞는 것 같습니다. 수정 전 코드에서 유효성검사를 changeIdInput, changePwInput 내에서 각각 해줬었는데 호환성 검사에 딜레이가 생겨서 useEffect를 사용하는게 해결책이라 생각했습니다. 이 과정에서 changeIdInput, changePwInput 내부의 삼항연산자들을 useEffect 내부로 잘라내어 오게 되면서 로직이 길어진 것 같습니다.
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // 메인으로 이동할 때 로직 + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // 회원가입시 사용할 로직 + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // 로그인시 사용할 로직 + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="비밀번호" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="로그인" + onClick={goToMain} + /> + </form> + <p>비밀번호를 잊으셨나요?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
[공식문서 React로 사고하기](https://ko.reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state) 를 보시면 어떤 값들이 state가 되어야하는지에 대해 적혀있습니다. 각각 살펴보고 해당 데이터는 state로 적절한지 댓글로 남겨주세요. 각 데이터에 대해 아래의 세 가지 질문을 통해 결정할 수 있습니다 > 1. 부모로부터 props를 통해 전달됩니까? 그러면 확실히 state가 아닙니다. > > 2. 시간이 지나도 변하지 않나요? 그러면 확실히 state가 아닙니다. > > 3. 컴포넌트 안의 다른 state나 props를 가지고 계산 가능한가요? 그렇다면 state가 아닙니다. >
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // 메인으로 이동할 때 로직 + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // 회원가입시 사용할 로직 + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // 로그인시 사용할 로직 + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="비밀번호" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="로그인" + onClick={goToMain} + /> + </form> + <p>비밀번호를 잊으셨나요?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
라이브리뷰 때 말씀드린 것처럼 조건의 falsy, truthy한 값을 이용해 리팩토링 해주세요! :) 또는 state를 줄일 경우 불필요할 수도 있겠네요
@@ -0,0 +1,66 @@ +@use '../../../styles/mixin.scss' as mixin; +@use '../../../styles/color.scss' as clr; + +body { + background: clr.$bg-login; + + .login { + position: relative; + top: -80px; + + #wrapper { + @include mixin.flex($align: center); + position: relative; + flex-direction: column; + width: 700px; + height: 761px; + border: 1px solid clr.$clr-border; + + h1 { + margin-top: 90px; + margin-bottom: 130px; + font-size: 81px; + font-family: 'Lobster', cursive; + } + + .login_form { + input { + display: block; + width: 536px; + height: 76px; + margin-bottom: 12px; + padding-left: 10px; + background: #fafafa; + border: 1px solid clr.$clr-border; + border-radius: 3px; + font-size: 16px; + } + + input[type='button'] { + display: flex; + align-items: center; + justify-content: center; + width: 536px; + height: 60px; + margin-top: 16px; + background-color: clr.$clr-primary; + opacity: 0.5; + border: none; + border-radius: 4px; + font-size: 16px; + color: #fff; + + &.activated { + opacity: 1; + } + } + } + + p { + position: absolute; + bottom: 20px; + color: #043667; + } + } + } +}
Unknown
위 코드는 어디에 작성되면 좋을까요?
@@ -0,0 +1,43 @@ +span.comment { + padding-left: 10px; + + small { + color: #a3a3a3; + } + + &:first-child { + padding: 10px; + font-weight: bold; + } + + svg { + &.delete { + display: none; + cursor: pointer; + } + + &.hearts { + color: #a3a3a3; + position: absolute; + right: 20px; + transition: color 1s; + cursor: pointer; + + path { + color: #a3a3a3; + } + } + + &.liked { + path { + color: #f00; + } + } + } + + &:hover svg { + &.delete { + display: inline-block; + } + } +}
Unknown
자주 사용이 되는 컬러값이네요! 이런 경우 sass variables 기능을 이용하는것은 어떨까요?
@@ -0,0 +1,87 @@ +import React, { useState } from 'react'; +import { AiFillHeart, AiOutlineComment, AiOutlineUpload } from 'react-icons/ai'; +import { BiDotsHorizontalRounded } from 'react-icons/bi'; +import { GrBookmark } from 'react-icons/gr'; +import './Feeds.scss'; +import Comments from './Comment/Comments'; + +export default function Feeds({ userId, profileImg, img, comments }) { + const [commentVal, setCommentVal] = useState(comments); + let addedCommentVal = [...commentVal]; + const [currInputVal, setCurrInputVal] = useState(''); + + const handleInput = e => { + const { value } = e.target; + if (e.keyCode === 13) uploadComment(); + setCurrInputVal(value); + }; + + const uploadComment = e => { + e.preventDefault(); + if (!currInputVal) return; + addedCommentVal.push({ + id: addedCommentVal.length + 1, + userId: 'userid', + value: currInputVal, + time: '방금전', + }); + setCommentVal(addedCommentVal); + setCurrInputVal(''); + }; + + const handleDelete = e => { + const { id } = e.target.parentNode.parentNode; + addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id)); + setCommentVal(addedCommentVal); + }; + + return ( + <div className="feeds"> + <article> + <div className="top_menu"> + <span> + <img src={profileImg} alt="프로필" /> + {userId} + </span> + <span> + <BiDotsHorizontalRounded /> + </span> + </div> + <img src={img} alt="무화과" /> + <div className="bottom_menu"> + <span> + <AiFillHeart className="" /> + </span> + <span> + <AiOutlineComment className="" /> + </span> + <span> + <AiOutlineUpload className="" /> + </span> + <span> + <GrBookmark className="" /> + </span> + </div> + <div className="comments"> + <span>4 Likes</span> + <Comments commentArr={commentVal} handleDelete={handleDelete} /> + </div> + <form className="add_comments"> + <input + type="text" + placeholder="댓글 달기..." + className="input_upload" + onChange={handleInput} + value={currInputVal} + /> + <button + className={currInputVal ? 'activated' : ''} + onClick={uploadComment} + > + 게시 + </button> + </form> + </article> + </div> + ); +}
Unknown
.해당 부분도 좀 더 반복되는 단어를 줄일 수 없을지 고민해봅시다. 더불어 불필요한 state값도 보이네요! 위 리뷰를 참고해 수정해주세요!
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
class명은 어떤 형태가 좋을까요?! 해당 class명은 '동작'을 나타내기에 클래스 네임보다는 함수명처럼 느껴집니다!
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // 메인으로 이동할 때 로직 + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // 회원가입시 사용할 로직 + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // 로그인시 사용할 로직 + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('결과: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="전화번호, 사용자 이름 또는 이메일" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="비밀번호" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="로그인" + onClick={goToMain} + /> + </form> + <p>비밀번호를 잊으셨나요?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
- 불필요한 주석처리는 삭제해주세요! - 더불어서 className 자체를 '색'으로 지정하는 것은 좋은 네이밍은 아닌 것 같습니다. 어떤 네이밍이 적합할지 고민하셔서 , 해당 요소가 무엇인지를 잘 나타내는 네이밍으로 수정해주세요. - 플러스! 여기에도 사용하지 않아도 되는 삼항연사자가 숨어있네요! 확인해주세요
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
이렇게 각 요소에 background color를 각각 다 넣어주신 이유가 있으실까요?
@@ -0,0 +1,92 @@ +{ + "stories": [ + { "imgUrl": "images/joonyoung/stories/story1.jpg", "username": "Enna" }, + { "imgUrl": "images/joonyoung/stories/story2.jpg", "username": "Jesy" }, + { "imgUrl": "images/joonyoung/stories/story3.jpg", "username": "Denial" }, + { "imgUrl": "images/joonyoung/stories/story4.jpg", "username": "Meow" }, + { + "imgUrl": "images/joonyoung/stories/story5.jpg", + "username": "Christina" + }, + { "imgUrl": "images/joonyoung/stories/story6.jpg", "username": "Mally" }, + { "imgUrl": "images/joonyoung/stories/story7.jpg", "username": "Karel" }, + { "imgUrl": "images/joonyoung/stories/story8.jpg", "username": "Bred" }, + { "imgUrl": "images/joonyoung/stories/story9.jpg", "username": "Andrew" }, + { "imgUrl": "images/joonyoung/stories/story10.jpg", "username": "Emily" } + ], + "otherProfileInfos": [ + { + "id": 1, + "username": "wecode28기", + "description": "wecode님외 36명이 follow" + }, + { + "id": 2, + "username": "Younha", + "description": "Enna Kim외 10명이 follow" + }, + { + "id": 3, + "username": "wework", + "description": "wecode28님외 236명이 follow" + } + ], + "feed": [ + { + "id": 1, + "feedUpLoader": "Enna", + "uploaderProfileImg": "./images/joonyoung/stories/story1.jpg", + "uploaderInfo": "Enna's Feed icon", + "carouselImages": [ + "./images/joonyoung/feed/feed1/pexels-fauxels-3184291.jpg", + "./images/joonyoung/feed/feed1/pexels-fauxels-3184302.jpg", + "./images/joonyoung/feed/feed1/pexels-fauxels-3184433.jpg", + "./images/joonyoung/feed/feed1/pexels-min-an-853168.jpg", + "./images/joonyoung/feed/feed1/pexels-this-is-zun-1116302.jpg" + ], + "likes": 1129, + "comments": [ + { + "id": 1, + "user": "28기 양대영님", + "comment": "여러분 치킨계 쓰셔야 합니다..!! 👀 👀" + }, + { + "id": 2, + "user": "28기 이아영님", + "comment": "대영님도 안 쓰셨잖아요?! 🤭" + }, + { + "id": 3, + "user": "28기 박윤국님", + "comment": "🎸 🎸 🎸 (신곡 홍보중)" + } + ] + }, + { + "id": 2, + "feedUpLoader": "James", + "uploaderProfileImg": "./images/joonyoung/stories/story2.jpg", + "uploaderInfo": "It's jesy!", + "carouselImages": [ + "./images/joonyoung/feed/feed2/handtohand.jpg", + "./images/joonyoung/feed/feed2/branch.jpg", + "./images/joonyoung/feed/feed2/pexels-te-lensfix-1371360.jpg", + "./images/joonyoung/feed/feed2/pexels-victor-freitas-803105.jpg" + ], + "likes": 1129, + "comments": [ + { + "id": 1, + "user": "멘토 김INTP님", + "comment": "(안경을 치켜 올리며) git branch merge" + }, + { + "id": 2, + "user": "28기 이ESTJ님", + "comment": "아니 계획을 안짜고 여행을 간다고?" + } + ] + } + ] +}
Unknown
mockData king 준영님👍 정말 감사합니다. 세부 내용은 임의로 변경한 후, 데이터의 형식좀 빌려다 쓰겠습니다 감사합니다!
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <link rel="icon" type="image/svg+xml" href="/vite.svg" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>react-shopping-products</title> + <script type="module" crossorigin src="/react-shopping-products/dist/assets/index-B5NHo3G9.js"></script> + <link rel="stylesheet" crossorigin href="/react-shopping-products/dist/assets/index-BlzNY9oW.css"> + </head> + <body> + <div id="root"></div> + </body> +</html>
Unknown
dist 폴더가 git ignore되지 않았군용
@@ -0,0 +1,10 @@ +/** + * generateBasicToken - Basic auth를 위한 토큰을 만드는 함수입니다. + * @param {string} userId - USERNAME입니다. + * @param {string} userPassword - PASSWORD입니다. + * @returns {string} + */ +export function generateBasicToken(userId: string, userPassword: string): string { + const token = btoa(`${userId}:${userPassword}`); + return `Basic ${token}`; +}
TypeScript
섬세한 jsdocs 👍👍👍👍
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * 공통 요청을 처리하는 함수 + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API에서 상품 목록을 fetch합니다. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - 선택한 상품을 장바구니에 추가합니다. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API에서 장바구니 목록을 fetch합니다. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - 선택한 상품을 장바구니에서 삭제합니다. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
공통 로직을 묶어주는 것 너무 좋습니다~!
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * 공통 요청을 처리하는 함수 + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API에서 상품 목록을 fetch합니다. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - 선택한 상품을 장바구니에 추가합니다. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API에서 장바구니 목록을 fetch합니다. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - 선택한 상품을 장바구니에서 삭제합니다. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
장바구니에 100개 넘게 담을 수 있는 case가 존재할 것 같아요~!
@@ -0,0 +1,50 @@ +.loaderContainer { + height: 60px; + display: flex; + justify-content: center; + align-items: center; +} + +.loader { + width: 60px; + display: flex; + justify-content: space-evenly; +} + +.ball { + list-style: none; + width: 12px; + height: 12px; + border-radius: 50%; + background-color: black; +} + +.ball:nth-child(1) { + animation: bounce1 0.4s ease-in-out infinite; +} + +@keyframes bounce1 { + 50% { + transform: translateY(-18px); + } +} + +.ball:nth-child(2) { + animation: bounce2 0.4s ease-in-out 0.2s infinite; +} + +@keyframes bounce2 { + 50% { + transform: translateY(-18px); + } +} + +.ball:nth-child(3) { + animation: bounce3 0.4s ease-in-out 0.4s infinite; +} + +@keyframes bounce3 { + 50% { + transform: translateY(-18px); + } +}
Unknown
귀여운 애니메이션을 만들었군용 🚀🚀🚀
@@ -0,0 +1,15 @@ +export const productCategories = { + all: '전체', + fashion: '패션', + beverage: '음료', + electronics: '전자제품', + kitchen: '주방용품', + fitness: '피트니스', + books: '도서', +} as const; + +export const sortOptions = { priceAsc: '낮은 가격순', priceDesc: '높은 가격순' } as const; + +export const FIRST_FETCH_PAGE = 0; +export const FIRST_FETCH_SIZE = 20; +export const AFTER_FETCH_SIZE = 4;
TypeScript
상수화 👍👍👍
@@ -0,0 +1,32 @@ +import React, { createContext, useState, useCallback, ReactNode } from 'react'; +import ErrorToast from '../components/ErrorToast/ErrorToast'; + +export interface ToastContextType { + showToast: (message: string) => void; +} + +export const ToastContext = createContext<ToastContextType | undefined>(undefined); + +interface ToastProviderProps { + children: ReactNode; +} + +export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => { + const [isOpen, setIsOpen] = useState(false); + const [message, setMessage] = useState(''); + + const showToast = useCallback((message: string) => { + setMessage(message); + setIsOpen(true); + setTimeout(() => { + setIsOpen(false); + }, 3000); + }, []); + + return ( + <ToastContext.Provider value={{ showToast }}> + {children} + {isOpen && <ErrorToast message={message} />} + </ToastContext.Provider> + ); +};
Unknown
별도의 Provider로 만들어 준 것 너무 좋네요
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * 공통 요청을 처리하는 함수 + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API에서 상품 목록을 fetch합니다. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - 선택한 상품을 장바구니에 추가합니다. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API에서 장바구니 목록을 fetch합니다. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - 선택한 상품을 장바구니에서 삭제합니다. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
맞아요... 임시방편이었는데 그냥 까먹고 넘어갔네요 ㅜㅜ
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * 공통 요청을 처리하는 함수 + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API에서 상품 목록을 fetch합니다. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - 선택한 상품을 장바구니에 추가합니다. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API에서 장바구니 목록을 fetch합니다. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - 선택한 상품을 장바구니에서 삭제합니다. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
그런데.. 이번 장바구니 api는 20개만 담을 수 있게 만들어져있더라구요.. 지금 api 구현사항에 맞출지, 아니면 미래의 변경에도 용이하게 코드를 바꿀지는 생각해 봐야할 문제인 것 같아요. 이 부분을 바꿔야 한다면 위의 >if (key === 'category' && value === 'all') 이 코드에서도 default로 들어갈 수 있는 sort=id,asc도 생각해봐야 할 것 같고요
@@ -0,0 +1,21 @@ +import { SelectHTMLAttributes, PropsWithChildren } from 'react'; +import styles from './Select.module.css'; + +interface Props extends PropsWithChildren<SelectHTMLAttributes<HTMLSelectElement>> { + options: Record<string, string>; +} + +const Select = ({ options, defaultValue, children, ...props }: Props) => { + return ( + <select {...props} className={styles.selectContainer} defaultValue={defaultValue}> + {children} + {Object.keys(options).map((option) => ( + <option key={option} value={option}> + {options[option]} + </option> + ))} + </select> + ); +}; + +export default Select;
Unknown
entries라는 함수도 있으니 찾아보시면 좋을 것 같아요..! ``` js Object.entries(options).map([optionEn,optionKo])=>{ ... } ```
@@ -1 +1,5 @@ -export interface IReviewController {} +import { Review, ReviewInputDTO } from '#reviews/review.types.js'; + +export interface IReviewController { + postReview: (driverId: string, body: ReviewInputDTO) => Promise<Review>; +}
TypeScript
프로젝트 타입으로
@@ -1 +1,5 @@ -export interface IReviewService {} +import { Review, ReviewInputDTO } from '#reviews/review.types.js'; + +export interface IReviewService { + postReview: (driverId: string, body: ReviewInputDTO) => Promise<Review>; +}
TypeScript
마찬가지
@@ -30,15 +30,17 @@ const OrderItem = () => { </div> </div> </div> - <div className="flex flex-row justify-center gap-3"> - <Link className="w-1/2" href={ROUTE_PATHS.ORDER_DETAIL}> + <div className="flex flex-row gap-3"> + <Link className="w-full" href={`${ROUTE_PATHS.ORDERS_DETAIL}/1`}> <Button size="s" className="h-10"> 주문 상세 </Button> </Link> - <Button variant="grayFit" size="s" className="h-10 w-1/2"> - 리뷰 달기 - </Button> + <Link className="w-full" href={ROUTE_PATHS.REVIEW}> + <Button variant="grayFit" size="s" className="h-10"> + 리뷰 달기 + </Button> + </Link> </div> </div> )
Unknown
href={`${ROUTE_PATHS.ORDER_DETAIL}/1`} 로 변경해준다면 추후에 route가 변경됐을 때 하나하나 찾아서 변경해주지 않아도 될 거 같아요~ 나중에는 1 대신 ${id} 로 변경해주시구요!
@@ -7,8 +7,8 @@ const buttonVariants = cva('inline-flex items-center justify-center gap-2 whites variants: { variant: { default: 'bg-primary text-white hover:bg-primary/90 w-full px-4', - primaryFit: 'w-fit px-4 text-primary border-solid border border-primary', - grayFit: 'w-fit px-4 text-gray-400 border-solid border border-gray-400', + primaryFit: 'w-full px-4 text-primary border-solid border border-primary', + grayFit: 'w-full px-4 text-gray-400 border-solid border border-gray-400', }, size: { @@ -34,7 +34,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( return ( <button className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} /> ) - }, + } ) Button.displayName = 'Button'
Unknown
공통 컴포넌트를 변경할 때는 꼭 팀원들에게 변경해도 될지 물어봐주시는게 좋아요! 누군가는 w-fit에 맞춰서 개발해놨는데 나중에 들어가보니 ui가 깨져있을 수도 있거든요 ㅠ
@@ -7,8 +7,8 @@ const buttonVariants = cva('inline-flex items-center justify-center gap-2 whites variants: { variant: { default: 'bg-primary text-white hover:bg-primary/90 w-full px-4', - primaryFit: 'w-fit px-4 text-primary border-solid border border-primary', - grayFit: 'w-fit px-4 text-gray-400 border-solid border border-gray-400', + primaryFit: 'w-full px-4 text-primary border-solid border border-primary', + grayFit: 'w-full px-4 text-gray-400 border-solid border border-gray-400', }, size: { @@ -34,7 +34,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( return ( <button className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} /> ) - }, + } ) Button.displayName = 'Button'
Unknown
넵 다음에는 공지 후에 변경하도록 하겠습니다!
@@ -0,0 +1,11 @@ +package baseball.util; + +import java.util.Random; + +public class RamdomNumberGenerator { + private static final Random RANDOM = new Random(); + + public static Integer generate() { + return RANDOM.nextInt(9) + 1; + } +}
Java
무작위의 숫자를 생성하는 클래스를 따로 빼서 테스트를 용이하게 할 수 있게 한 게 좋네요!
@@ -0,0 +1,101 @@ +package baseball.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NumericBalls implements Iterable { + private List<NumericBall> numericBalls; + + public NumericBalls() { + numericBalls = new ArrayList<>(); + } + + public NumericBalls(List<Integer> numbers) { + validate(numbers); + List<NumericBall> newBalls = new ArrayList<>(); + for (Integer number : numbers) { + newBalls.add(new NumericBall(number)); + } + this.numericBalls = newBalls; + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 3) { + throw new IllegalArgumentException(); + } + } + + public List<Integer> match(NumericBalls otherBalls) { + List<Integer> matchPoints = new ArrayList<>(); + int matchedCnt = matchBall(otherBalls); + int strikeCnt = strikeCheck(otherBalls); + matchPoints.add(strikeCnt); + matchPoints.add(matchedCnt - strikeCnt); + return matchPoints; + } + + private Integer matchBall(NumericBalls otherBalls) { + Map<Integer, Integer> map = new HashMap<>(); + for (NumericBall num : numericBalls) { + map.put(num.numericBall(), 0); + } + + int ballCnt = 0; + + Iterator otherIterator = otherBalls.iterator(); + while(otherIterator.hasNext()) { + NumericBall otherBall = otherIterator.next(); + if (map.containsKey(otherBall.numericBall())) { + map.put(otherBall.numericBall(), map.get(otherBall.numericBall()) + 1); + } + } + for (Integer value : map.values()) { + ballCnt += value; + } + return ballCnt; + } + + private Integer strikeCheck(NumericBalls otherBalls) { + int strikeCnt = 0; + for (int i = 0; i < numericBalls.size(); i++) { + if (numericBalls.get(i).equals(otherBalls.numericBall(i))) { + strikeCnt++; + } + } + return strikeCnt; + } + + public NumericBall numericBall(int index) { + return numericBalls.get(index); + } + + public int size() { + return numericBalls.size(); + } + + @Override + public Iterator iterator() { + return new NumericBallsIterator(this); + } + + private static class NumericBallsIterator implements Iterator { + private int index = 0; + private NumericBalls numericBalls; + + public NumericBallsIterator(NumericBalls numericBalls) { + this.numericBalls = numericBalls; + } + + @Override + public boolean hasNext() { + return (this.index < this.numericBalls.size()); + } + + @Override + public NumericBall next() { + return numericBalls.numericBall(this.index++); + } + } +}
Java
리스트에 넣고 맵에 다시 넣는 것보다 처음부터 필드를 맵으로 선언하고 맵의 숫자와 인덱스를 비교하면 효율이 더 좋을 것 같아요.
@@ -0,0 +1,23 @@ +package baseball.view; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class InputView { + private static final Scanner SCANNER = new Scanner(System.in); + public static List<Integer> inputNumbers() { + System.out.println("숫자를 입력해 주세요 : "); + List<Integer> nums = new ArrayList<>(); + nums.addAll(parse(List.of(SCANNER.next().split("")))); + return nums; + } + + private static List<Integer> parse(List<String> strArr) { + List<Integer> nums = new ArrayList<>(); + for (String str : strArr) { + nums.add(Integer.parseInt(str)); + } + return nums; + } +}
Java
객체를 상수로 선언하면 코드가 훨씬 간편해지지만, final임에도 값이 바뀔 수 있어 관련이슈가 있을 수도 있습니다. 유의하고 사용해주세요:)
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)"; + private static final String ASK_TURN = "시도할 회수는 몇회인가요?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
메시지 관리에 대해서 static이 좋은지 enum이 좋은지 이야기 나눠보면 좋을 것 같습니다. 항상 어떤게 나은지 고민해서 매번 쓸때마다 한번은 이렇게 한번은 저렇게 했었거든요.
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)"; + private static final String ASK_TURN = "시도할 회수는 몇회인가요?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
저는 System.out.print~사용하는 부분은 전부 출력으로 사용자에게 보여지는 부분이라고 생각해서 모두 OutputView에 작성하고 있습니다. 사실 첨에 저도 InputView에 써도 될지 고민했는데 이 부분에 대해서는 어떻게 생각하시는지 궁금합니다.
@@ -0,0 +1,38 @@ +package racingcar.view; + +import java.util.stream.Collectors; +import racingcar.domain.RacingCar; +import racingcar.domain.RacingCars; +import racingcar.domain.Winner; + +public class OutputView { + private static final String RACE_RESULT_MESSAGE = "\n실행 결과"; + private static final String DISTANCE_UNIT = "-"; + private static final String RACE_RESULT_FORMAT = "%s : %s%n"; + private static final String WINNER = "최종 우승자 : "; + private static final String DELIMITER = ", "; + + public static void printRaceResultNotice() { + System.out.println(RACE_RESULT_MESSAGE); + } + + public static void printRaceResult(RacingCars racingCars) { + racingCars.getRacingCars() + .forEach(racingCar -> System.out.printf(RACE_RESULT_FORMAT + , racingCar.getCarName(), changeDistanceForm(racingCar.getDistance()))); + System.out.println(); + } + + private static String changeDistanceForm(int distance) { + return DISTANCE_UNIT.repeat(distance); + } + + public static void printWinner(Winner winner) { + System.out.print(WINNER); + String winners = winner.getWinner() + .stream() + .map(RacingCar::getCarName) + .collect(Collectors.joining(DELIMITER)); + System.out.println(winners); + } +}
Java
Winner클래스의 getWinner()에서 아래 연산이 끝난 결과를 리턴하면 getter를 사용하지 않고도 결과를 받아올 수 있다고 생각하는데 어떻게 생각하시나요?
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CarNameTest { + @ParameterizedTest + @DisplayName("차량이름은 1-5글자이고 특수문자를 포함하지 않는다.") + @ValueSource(strings = {"abcdef", "", "$", "&", " ", "!", "(", "$", "%"}) + void createCarName(String input) { + assertThatThrownBy(() -> new CarName(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
assertThatCode를 이용해서 예외가 발생하지 않고 올바르게 되는지 한번 테스트 해보는 것도 추천 드립니다.
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public enum ErrorMessage { + ERROR("[ERROR] "), + INVALID_NAME_LENGTH(ERROR + "차량 이름은 1-5글자 사이여야 합니다."), + INVALID_NAME_TYPE(ERROR + "차량 이름은 특수문자를 포함할 수 없습니다."), + DUPLICATED_NAME(ERROR + "차량 이름은 중복될 수 없습니다."), + INVALID_RACING_CARS_SIZE(ERROR + "경주에는 최소 2대의 차량이 참여해야합니다."), + INVALID_TURN_RANGE(ERROR + "시도횟수는 최소 1회 이상이어야 합니다."), + INVALID_TURN_TYPE(ERROR + "숫자 이외의 값은 입력할 수 없습니다."), + CANT_FIND_CAR(ERROR + "차량을 찾을 수 없습니다."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
ERROR은 변함 없을 것 같은데 상수로 두고 생성자 부분에서 this.message = "ERROR" + message로 한다면 메시지 작성할 때 중복을 피하는데 도움 될 것 같습니다.
@@ -0,0 +1,63 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.CANT_FIND_CAR; +import static racingcar.domain.ErrorMessage.DUPLICATED_NAME; +import static racingcar.domain.ErrorMessage.INVALID_RACING_CARS_SIZE; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingCars { + private static final int MIN_SIZE = 2; + private final List<RacingCar> racingCars; + private RacingCar maxDistanceCar; + + public RacingCars(List<RacingCar> racingCars) { + validateSize(racingCars); + validateDuplicated(racingCars); + this.racingCars = racingCars; + } + + private void validateSize(List<RacingCar> racingCars) { + if (racingCars.size() < MIN_SIZE) { + throw new IllegalArgumentException(INVALID_RACING_CARS_SIZE.getMessage()); + } + } + + private void validateDuplicated(List<RacingCar> racingCars) { + if (isDuplicated(racingCars)) { + throw new IllegalArgumentException(DUPLICATED_NAME.getMessage()); + } + } + + private boolean isDuplicated(List<RacingCar> racingCars) { + int sizeAfterCut = (int) racingCars.stream() + .distinct() + .count(); + return racingCars.size() != sizeAfterCut; + } + + public void startRace() { + racingCars + .forEach(racingCar -> + racingCar.moveForward(RandomNumberGenerator.generateRandomNumber())); + } + + public Winner selectWinner() { + findMaxDistanceCar(); + List<RacingCar> winner = racingCars.stream() + .filter(maxDistanceCar::isWinner) + .collect(Collectors.toList()); + return new Winner(winner); + } + + private void findMaxDistanceCar() { + maxDistanceCar = racingCars.stream() + .max(RacingCar::compareTo) + .orElseThrow(() -> new IllegalArgumentException(CANT_FIND_CAR.getMessage())); + } + + public List<RacingCar> getRacingCars() { + return racingCars; + } +}
Java
return에 바로 작성하면 가독성이 조금 떨어져 보일까요? 이 메소드 처럼 한번만 사용하는 변수라면 변수로 지정하지 않고 바로 작성해도 될 것 같은데... 이러면 가독성이 떨어져 보이기도 할 것 같아 고민이 되서 여쭤봅니다.
@@ -0,0 +1,51 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.INVALID_NAME_LENGTH; +import static racingcar.domain.ErrorMessage.INVALID_NAME_TYPE; + +import java.util.Objects; +import java.util.regex.Pattern; + +public class CarName { + private static final int MAX_LENGTH = 5; + private static final String REGEX = "[0-9|a-zA-Zㄱ-ㅎㅏ-ㅣ가-힣]*"; + private final String carName; + + public CarName(String carName) { + validateLength(carName); + validateType(carName); + this.carName = carName; + } + + private void validateLength(String carName) { + if (carName.isEmpty() || carName.length() > MAX_LENGTH) { + throw new IllegalArgumentException(INVALID_NAME_LENGTH.getMessage()); + } + } + + private void validateType(String carName) { + if (!Pattern.matches(REGEX, carName)) { + throw new IllegalArgumentException(INVALID_NAME_TYPE.getMessage()); + } + } + + public String getCarName() { + return carName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CarName carName1)) { + return false; + } + return Objects.equals(carName, carName1.carName); + } + + @Override + public int hashCode() { + return Objects.hash(carName); + } +}
Java
정규표현식에 문자지정한 후 {1,5}을 사용하면 글자 수 제한 하는데도 도움이 될 거에요.
@@ -0,0 +1,35 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RacingCarsTest { + @ParameterizedTest + @DisplayName("경주에는 최소 2대 이상의 차량이 참여해야 하며 중복될 수 없다.") + @ValueSource(strings = {"상추", "상추,상추"}) + void createRacingCars(String input) { + List<RacingCar> racingCars = InputConvertor.convertToRacingCars(input); + assertThatThrownBy(() -> new RacingCars(racingCars)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("우승자는 상추와 배추다.") + void selectWinner() { + RacingCar sangchu = new RacingCar(new CarName("상추")); + RacingCar baechu = new RacingCar(new CarName("배추")); + RacingCar moodosa = new RacingCar(new CarName("무도사")); + RacingCars racingCars = new RacingCars(List.of(sangchu, baechu, moodosa)); + sangchu.moveForward(5); + baechu.moveForward(6); + Winner winner = racingCars.selectWinner(); + assertThat(winner.getWinner().get(0).getCarName()).isEqualTo("상추"); + assertThat(winner.getWinner().get(1).getCarName()).isEqualTo("배추"); + } +} \ No newline at end of file
Java
2대 이상인 경우 / 이름 중복되면 안되는 경우에 대해 메소드를 나눠서 테스트 해도 좋을거같슴다
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TurnTest { + @ParameterizedTest + @DisplayName("1회 미만, 숫자 이외 값 입력시 예외 발생") + @ValueSource(strings = {"0", "-1", "d", "#", "", " "}) + void createTurn(String input) { + assertThatThrownBy(() -> new Turn(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
저는 validate 로직에 대해서 1. 숫자만 입력 받아야하는 변수에 문자 입력되는 경우 -> input에서 검증 2. 1회 미만으로 입력받는 메소드 관련 검증 -> turn메소드에서 검증 하는 방식으로 항상 작성해 왔는데 이부분에 대해서 어떻게 생각하는지 궁금합니다 !
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)"; + private static final String ASK_TURN = "시도할 회수는 몇회인가요?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
저는 이번에 프리코스를 진행하면서 나름의 기준을 세워봤습니다! 1. enum으로 사용할만큼 상수의 개수가 충분한지? 최소 3개 이상 2. 프로그램이 확장된다면 해당 enum 에 상수가 추가될 가능성이 있는지? 3. 다른 클래스에서도 사용될 가능성이 있는지?
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)"; + private static final String ASK_TURN = "시도할 회수는 몇회인가요?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
저도 처음에 1주차 미션을 진행할 때는 사용자에게 보이는 부분이라고 생각하여 OutputView에 작성했었는데 많은 분들 코드를 보다보니 입력을 요청하는 메시지는 InputView에서 처리하시더라구요. 그리고 결정적으로 우테코에서 제공한 요구사항 부분을 보시면 입력을 요구하는 메시지를 InputView에서 사용하는걸 보실 수 있습니다. <img width="914" alt="image" src="https://github.com/parksangchu/java-racingcar-6/assets/142131857/87aa54ff-07c6-4c03-87fe-331d6aba9664">
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public enum ErrorMessage { + ERROR("[ERROR] "), + INVALID_NAME_LENGTH(ERROR + "차량 이름은 1-5글자 사이여야 합니다."), + INVALID_NAME_TYPE(ERROR + "차량 이름은 특수문자를 포함할 수 없습니다."), + DUPLICATED_NAME(ERROR + "차량 이름은 중복될 수 없습니다."), + INVALID_RACING_CARS_SIZE(ERROR + "경주에는 최소 2대의 차량이 참여해야합니다."), + INVALID_TURN_RANGE(ERROR + "시도횟수는 최소 1회 이상이어야 합니다."), + INVALID_TURN_TYPE(ERROR + "숫자 이외의 값은 입력할 수 없습니다."), + CANT_FIND_CAR(ERROR + "차량을 찾을 수 없습니다."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
enum 생성자에 대한 이해가 부족했던것 같습니다 ! 좋은 조언 감사합니다 ㅎㅎ
@@ -0,0 +1,63 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.CANT_FIND_CAR; +import static racingcar.domain.ErrorMessage.DUPLICATED_NAME; +import static racingcar.domain.ErrorMessage.INVALID_RACING_CARS_SIZE; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingCars { + private static final int MIN_SIZE = 2; + private final List<RacingCar> racingCars; + private RacingCar maxDistanceCar; + + public RacingCars(List<RacingCar> racingCars) { + validateSize(racingCars); + validateDuplicated(racingCars); + this.racingCars = racingCars; + } + + private void validateSize(List<RacingCar> racingCars) { + if (racingCars.size() < MIN_SIZE) { + throw new IllegalArgumentException(INVALID_RACING_CARS_SIZE.getMessage()); + } + } + + private void validateDuplicated(List<RacingCar> racingCars) { + if (isDuplicated(racingCars)) { + throw new IllegalArgumentException(DUPLICATED_NAME.getMessage()); + } + } + + private boolean isDuplicated(List<RacingCar> racingCars) { + int sizeAfterCut = (int) racingCars.stream() + .distinct() + .count(); + return racingCars.size() != sizeAfterCut; + } + + public void startRace() { + racingCars + .forEach(racingCar -> + racingCar.moveForward(RandomNumberGenerator.generateRandomNumber())); + } + + public Winner selectWinner() { + findMaxDistanceCar(); + List<RacingCar> winner = racingCars.stream() + .filter(maxDistanceCar::isWinner) + .collect(Collectors.toList()); + return new Winner(winner); + } + + private void findMaxDistanceCar() { + maxDistanceCar = racingCars.stream() + .max(RacingCar::compareTo) + .orElseThrow(() -> new IllegalArgumentException(CANT_FIND_CAR.getMessage())); + } + + public List<RacingCar> getRacingCars() { + return racingCars; + } +}
Java
제가 3주차 미션을 할때 겪었던 에로사항이 메서드내 모든 코드를 축약을 시키다보니 나중에 제가 그 코드를 보았을때 무슨 코드인지 한눈에 알기가 힘들더군요 ㅜㅜ 그래서 4주차때부터는 어느정도 절제해서 축약을 해보니 가독성이 훨씬 높아졌었던 경험이 있어서 이번에도 이런 방식으로 진행을 해봤습니다!
@@ -0,0 +1,38 @@ +package racingcar.view; + +import java.util.stream.Collectors; +import racingcar.domain.RacingCar; +import racingcar.domain.RacingCars; +import racingcar.domain.Winner; + +public class OutputView { + private static final String RACE_RESULT_MESSAGE = "\n실행 결과"; + private static final String DISTANCE_UNIT = "-"; + private static final String RACE_RESULT_FORMAT = "%s : %s%n"; + private static final String WINNER = "최종 우승자 : "; + private static final String DELIMITER = ", "; + + public static void printRaceResultNotice() { + System.out.println(RACE_RESULT_MESSAGE); + } + + public static void printRaceResult(RacingCars racingCars) { + racingCars.getRacingCars() + .forEach(racingCar -> System.out.printf(RACE_RESULT_FORMAT + , racingCar.getCarName(), changeDistanceForm(racingCar.getDistance()))); + System.out.println(); + } + + private static String changeDistanceForm(int distance) { + return DISTANCE_UNIT.repeat(distance); + } + + public static void printWinner(Winner winner) { + System.out.print(WINNER); + String winners = winner.getWinner() + .stream() + .map(RacingCar::getCarName) + .collect(Collectors.joining(DELIMITER)); + System.out.println(winners); + } +}
Java
받아온 데이터를 어떤식으로 처리할지 결정하는 것은 OutputView의 책임이라고 생각해서 해당 방식으로 진행했습니다~ 3주차 공통 피드백에서도 view에서 사용하는 데이터는 getter를 사용하라고 언급이 되어있구요! <img width="619" alt="image" src="https://github.com/parksangchu/java-racingcar-6/assets/142131857/99c1b2c6-7c6d-49ee-8154-e9d7c306bd0b">
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CarNameTest { + @ParameterizedTest + @DisplayName("차량이름은 1-5글자이고 특수문자를 포함하지 않는다.") + @ValueSource(strings = {"abcdef", "", "$", "&", " ", "!", "(", "$", "%"}) + void createCarName(String input) { + assertThatThrownBy(() -> new CarName(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
처음 보는 메서드였는데 한번 사용해보겠습니다! 감사합니다 ㅎㅎ
@@ -0,0 +1,35 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RacingCarsTest { + @ParameterizedTest + @DisplayName("경주에는 최소 2대 이상의 차량이 참여해야 하며 중복될 수 없다.") + @ValueSource(strings = {"상추", "상추,상추"}) + void createRacingCars(String input) { + List<RacingCar> racingCars = InputConvertor.convertToRacingCars(input); + assertThatThrownBy(() -> new RacingCars(racingCars)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("우승자는 상추와 배추다.") + void selectWinner() { + RacingCar sangchu = new RacingCar(new CarName("상추")); + RacingCar baechu = new RacingCar(new CarName("배추")); + RacingCar moodosa = new RacingCar(new CarName("무도사")); + RacingCars racingCars = new RacingCars(List.of(sangchu, baechu, moodosa)); + sangchu.moveForward(5); + baechu.moveForward(6); + Winner winner = racingCars.selectWinner(); + assertThat(winner.getWinner().get(0).getCarName()).isEqualTo("상추"); + assertThat(winner.getWinner().get(1).getCarName()).isEqualTo("배추"); + } +} \ No newline at end of file
Java
코드를 줄이려고 너무 욕심을 내다보니 그만 ... ㅜ 아무래도 따로 테스트하는게 가독성 측면에서도 좋을거 같습니다
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TurnTest { + @ParameterizedTest + @DisplayName("1회 미만, 숫자 이외 값 입력시 예외 발생") + @ValueSource(strings = {"0", "-1", "d", "#", "", " "}) + void createTurn(String input) { + assertThatThrownBy(() -> new Turn(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
저도 원래는 그런 방식으로 검증을 진행해오다가 이번에 'InputView에서 domain에서 쓰일 데이터 형태를 아는게 맞을까?'하는 의문이 들어 해당 방식으로 진행을 해봤습니다. 그리고 'RacingCar'와 같은 해당 프로그램의 도메인에서 쓰이는 객체를 생성해서 넘기는 것만 아니라면 int와 같은 기본값 형태는 inputView에서 검증해도 괜찮겠다라는 결론을 냈습니다.
@@ -0,0 +1,71 @@ +import { generateBasicToken } from '../utils/auth'; +import convertCartItem from '../utils/convertCartItem'; + +const API_URL = process.env.VITE_API_URL ?? 'undefined_URL'; +const USER_ID = process.env.VITE_API_USER_ID ?? 'undefined_USER_ID'; +const USER_PASSWORD = + process.env.VITE_API_USER_PASSWORD ?? 'undefined_USER_PASSWORD'; + +export const requestCartItemList = async () => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'GET', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + throw new Error('Failed to fetch products:'); + } + const data = await response.json(); + + return convertCartItem(data.content); +}; + +export const requestSetCartItemQuantity = async ( + cartItemId: number, + quantity: number, +) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'PATCH', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + quantity, + }), + }); + + if (!response.ok) { + throw new Error('Failed to setCartItemQuantity'); + } +}; + +export const requestDeleteCartItem = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'DELETE', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + id: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to deleteCartItem'); + } +}; + +// TEST를 위한 cartItem추가 API 실행 +export const requestAddCartItemForTest = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'POST', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + productId: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to addCartItem'); + } +};
TypeScript
요고는 각 api마다 선언해서 사용해주시는 걸로 확인됐는데, 상수로 분리해도 좋을 것 같아요! 🐫
@@ -0,0 +1,87 @@ +import * as S from './CartItem.style'; +import Text from '../common/Text/Text'; +import Button from '../common/Button/Button'; +import Divider from '../common/Divider/Divider'; +import Checkbox from '../common/Checkbox/Checkbox'; +import ImageBox from '../common/ImageBox/ImageBox'; +import useCartItemList from '../../hooks/cartItem/useCartItemList'; +import ChangeQuantity from '../common/ChangeQuantity/ChangeQuantity'; +import { useCartItemQuantity } from '../../hooks/cartItem/useCartItemQuantity'; +import { useSelectedCartItemId } from '../../hooks/cartItem/useSelectedCartItemId'; +import useApiErrorState from '../../hooks/error/useApiErrorState'; + +export type CartItemProps = { + type?: 'cart' | 'confirm'; + cartItem: CartItem; +}; + +const CartItem = ({ type = 'cart', cartItem }: CartItemProps) => { + const { id, name, price, imageUrl } = cartItem; + const { apiError } = useApiErrorState(); + const { cartItemQuantity, increaseQuantity, decreaseQuantity } = + useCartItemQuantity(); + const { isSelectedId, selectCartItem, unselectCartItem } = + useSelectedCartItemId(); + const { deleteCartItem } = useCartItemList(); + + if ( + apiError?.name === 'FailedDeleteCartItemError' || + apiError?.name === 'FailedSetCartItemQuantityError' + ) { + throw apiError; + } + + return ( + <S.CartItem> + <Divider /> + {type === 'cart' ? ( + <S.ItemHeader> + <Checkbox + state={isSelectedId(id)} + handleClick={ + isSelectedId(id) + ? () => unselectCartItem(id) + : () => selectCartItem(id) + } + /> + <Button size="s" radius="s" onClick={() => deleteCartItem(id)}> + 삭제 + </Button> + </S.ItemHeader> + ) : null} + <S.ItemBody> + <ImageBox + width={112} + height={112} + radius="m" + border="lightGray" + src={imageUrl} + alt="상품 이미지" + /> + <S.ItemDetail> + <S.ItemNameAndCost> + <Text size="s" weight="m"> + {name} + </Text> + <Text size="l" weight="l"> + {`${price.toLocaleString('ko-KR')}원`} + </Text> + </S.ItemNameAndCost> + {type === 'cart' ? ( + <ChangeQuantity + quantity={cartItemQuantity(id)} + increaseQuantity={() => increaseQuantity(id)} + decreaseQuantity={() => decreaseQuantity(id)} + /> + ) : ( + <Text size="s" weight="m"> + {`${cartItemQuantity(id)}개`} + </Text> + )} + </S.ItemDetail> + </S.ItemBody> + </S.CartItem> + ); +}; + +export default CartItem;
Unknown
type을 2개로 분리해서 구현하신 이유가 있을까요? 제가 느끼기에는 컴포넌트를 분리했어도 괜찮지 않나 싶은 생각도 들어서요!
@@ -1,10 +1,41 @@ -import "./App.css"; +import { Suspense } from 'react'; + +import styled from 'styled-components'; +import { ErrorBoundary } from 'react-error-boundary'; +import { BrowserRouter, Route, Routes } from 'react-router-dom'; + +import CartPage from './pages/CartPage'; +import ConfirmPurchasePage from './pages/ConfirmPurchasePage'; +import CompletePurchasePage from './pages/CompletePurchasePage'; +import ErrorFallback from './components/ErrorFallback/ErrorFallback'; +import LoadingFallback from './components/LoadingFallback/LoadingFallback'; + +const AppContainer = styled.div` + max-width: 768px; + width: 100%; +`; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <AppContainer> + <ErrorBoundary FallbackComponent={ErrorFallback}> + <Suspense fallback={<LoadingFallback />}> + <Routes> + <Route path="/" element={<CartPage />} /> + <Route + path="/confirm-purchase" + element={<ConfirmPurchasePage />} + /> + <Route + path="/complete-purchase" + element={<CompletePurchasePage />} + /> + </Routes> + </Suspense> + </ErrorBoundary> + </AppContainer> + </BrowserRouter> ); }
Unknown
사소하지만 RESTful하게 path를 작성해주셨네요 👏👏👏👏
@@ -1,10 +1,41 @@ -import "./App.css"; +import { Suspense } from 'react'; + +import styled from 'styled-components'; +import { ErrorBoundary } from 'react-error-boundary'; +import { BrowserRouter, Route, Routes } from 'react-router-dom'; + +import CartPage from './pages/CartPage'; +import ConfirmPurchasePage from './pages/ConfirmPurchasePage'; +import CompletePurchasePage from './pages/CompletePurchasePage'; +import ErrorFallback from './components/ErrorFallback/ErrorFallback'; +import LoadingFallback from './components/LoadingFallback/LoadingFallback'; + +const AppContainer = styled.div` + max-width: 768px; + width: 100%; +`; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <AppContainer> + <ErrorBoundary FallbackComponent={ErrorFallback}> + <Suspense fallback={<LoadingFallback />}> + <Routes> + <Route path="/" element={<CartPage />} /> + <Route + path="/confirm-purchase" + element={<ConfirmPurchasePage />} + /> + <Route + path="/complete-purchase" + element={<CompletePurchasePage />} + /> + </Routes> + </Suspense> + </ErrorBoundary> + </AppContainer> + </BrowserRouter> ); }
Unknown
사소하지만, 다음 미션부터는 [createBrowserRouter](https://reactrouter.com/en/main/routers/create-browser-router)를 사용해봐도 괜찮을 것 같아서 공유드려요! 관련해서 수야와도 리뷰를 한 적이 있어서 첨부합니다! https://github.com/cys4585/react-shopping-cart/pull/1/files/0636ab3b3126ca9b8873cb7fec59c13b05c81985#r1603187152
@@ -0,0 +1,71 @@ +import { generateBasicToken } from '../utils/auth'; +import convertCartItem from '../utils/convertCartItem'; + +const API_URL = process.env.VITE_API_URL ?? 'undefined_URL'; +const USER_ID = process.env.VITE_API_USER_ID ?? 'undefined_USER_ID'; +const USER_PASSWORD = + process.env.VITE_API_USER_PASSWORD ?? 'undefined_USER_PASSWORD'; + +export const requestCartItemList = async () => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'GET', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + throw new Error('Failed to fetch products:'); + } + const data = await response.json(); + + return convertCartItem(data.content); +}; + +export const requestSetCartItemQuantity = async ( + cartItemId: number, + quantity: number, +) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'PATCH', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + quantity, + }), + }); + + if (!response.ok) { + throw new Error('Failed to setCartItemQuantity'); + } +}; + +export const requestDeleteCartItem = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'DELETE', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + id: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to deleteCartItem'); + } +}; + +// TEST를 위한 cartItem추가 API 실행 +export const requestAddCartItemForTest = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'POST', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + productId: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to addCartItem'); + } +};
TypeScript
제가 지난 번에 남겼던 리뷰를 반영해주신것 같아서 기분이 조으네요..ㅎㅎ
@@ -0,0 +1,121 @@ +import { render, screen, fireEvent } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import CartItem, { CartItemProps } from './CartItem'; +import { RecoilRoot } from 'recoil'; +import { useCartItemQuantity } from '../../recoil/cartItem/useCartItemQuantity'; +import { useCartItemSelectedIdList } from '../../recoil/cartItem/useCartItemSelectedIdList'; +import useCartItemList from '../../recoil/cartItemList/useCartItemList'; + +// Mock Recoil hooks +jest.mock('../../recoil/cartItem/useCartItemQuantity'); +jest.mock('../../recoil/cartItem/useCartItemSelectedIdList'); +jest.mock('../../recoil/cartItemList/useCartItemList'); + +const mockedUseCartItemQuantity = useCartItemQuantity as jest.Mock; +const mockedUseCartItemSelectedIdList = useCartItemSelectedIdList as jest.Mock; +const mockedUseCartItemList = useCartItemList as jest.Mock; + +// Sample product data +const product = { + productId: 3, + name: '아디다스', + price: 2000, + imageUrl: 'https://sitem.ssgcdn.com/74/25/04/item/1000373042574_i1_750.jpg', + category: 'fashion', +}; + +const mockCartItemProps: CartItemProps = { + product, + quantity: 5, + cartItemId: 1, +}; + +describe('CartItem 컴포넌트', () => { + beforeEach(() => { + mockedUseCartItemQuantity.mockReturnValue({ + quantity: 5, + updateQuantity: jest.fn(), + increaseQuantity: jest.fn(), + decreaseQuantity: jest.fn(), + }); + + mockedUseCartItemSelectedIdList.mockReturnValue({ + getIsSelected: jest.fn().mockReturnValue(false), + addSelectedId: jest.fn(), + removeSelectedId: jest.fn(), + }); + + mockedUseCartItemList.mockReturnValue({ + deleteCartItem: jest.fn(), + }); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test('컴포넌트가 올바르게 렌더링된다', () => { + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + expect(screen.getByText('아디다스')).toBeInTheDocument(); + expect(screen.getByText('2,000원')).toBeInTheDocument(); + expect(screen.getByText('5')).toBeInTheDocument(); + }); + + test('삭제 버튼을 클릭했을 때 deleteCartItem 함수가 호출된다', () => { + const { deleteCartItem } = mockedUseCartItemList(); + + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + fireEvent.click(screen.getByText('삭제')); + expect(deleteCartItem).toHaveBeenCalledWith(mockCartItemProps.cartItemId); + }); + + test('체크박스를 클릭했을 때 선택 상태가 변경된다', () => { + const { addSelectedId, removeSelectedId, getIsSelected } = mockedUseCartItemSelectedIdList(); + + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + // Initially not selected + getIsSelected.mockReturnValue(false); + const checkbox = screen.getByAltText('Checkbox'); + fireEvent.click(checkbox); + expect(addSelectedId).toHaveBeenCalledWith(mockCartItemProps.cartItemId); + + // Now selected + getIsSelected.mockReturnValue(true); + fireEvent.click(checkbox); + expect(removeSelectedId).toHaveBeenCalledWith(mockCartItemProps.cartItemId); + }); + + test('수량 증가 및 감소 버튼이 제대로 작동한다', () => { + const { increaseQuantity, decreaseQuantity } = mockedUseCartItemQuantity(); + + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + const increaseButton = screen.getByLabelText('plus'); + const decreaseButton = screen.getByLabelText('minus'); + + fireEvent.click(increaseButton); + expect(increaseQuantity).toHaveBeenCalledTimes(1); + + fireEvent.click(decreaseButton); + expect(decreaseQuantity).toHaveBeenCalledTimes(1); + }); +});
Unknown
ui테스트도 작성을 해주셨네요...!! 굿굿~~!
@@ -0,0 +1,87 @@ +import * as S from './CartItem.style'; +import Text from '../common/Text/Text'; +import Button from '../common/Button/Button'; +import Divider from '../common/Divider/Divider'; +import Checkbox from '../common/Checkbox/Checkbox'; +import ImageBox from '../common/ImageBox/ImageBox'; +import useCartItemList from '../../hooks/cartItem/useCartItemList'; +import ChangeQuantity from '../common/ChangeQuantity/ChangeQuantity'; +import { useCartItemQuantity } from '../../hooks/cartItem/useCartItemQuantity'; +import { useSelectedCartItemId } from '../../hooks/cartItem/useSelectedCartItemId'; +import useApiErrorState from '../../hooks/error/useApiErrorState'; + +export type CartItemProps = { + type?: 'cart' | 'confirm'; + cartItem: CartItem; +}; + +const CartItem = ({ type = 'cart', cartItem }: CartItemProps) => { + const { id, name, price, imageUrl } = cartItem; + const { apiError } = useApiErrorState(); + const { cartItemQuantity, increaseQuantity, decreaseQuantity } = + useCartItemQuantity(); + const { isSelectedId, selectCartItem, unselectCartItem } = + useSelectedCartItemId(); + const { deleteCartItem } = useCartItemList(); + + if ( + apiError?.name === 'FailedDeleteCartItemError' || + apiError?.name === 'FailedSetCartItemQuantityError' + ) { + throw apiError; + } + + return ( + <S.CartItem> + <Divider /> + {type === 'cart' ? ( + <S.ItemHeader> + <Checkbox + state={isSelectedId(id)} + handleClick={ + isSelectedId(id) + ? () => unselectCartItem(id) + : () => selectCartItem(id) + } + /> + <Button size="s" radius="s" onClick={() => deleteCartItem(id)}> + 삭제 + </Button> + </S.ItemHeader> + ) : null} + <S.ItemBody> + <ImageBox + width={112} + height={112} + radius="m" + border="lightGray" + src={imageUrl} + alt="상품 이미지" + /> + <S.ItemDetail> + <S.ItemNameAndCost> + <Text size="s" weight="m"> + {name} + </Text> + <Text size="l" weight="l"> + {`${price.toLocaleString('ko-KR')}원`} + </Text> + </S.ItemNameAndCost> + {type === 'cart' ? ( + <ChangeQuantity + quantity={cartItemQuantity(id)} + increaseQuantity={() => increaseQuantity(id)} + decreaseQuantity={() => decreaseQuantity(id)} + /> + ) : ( + <Text size="s" weight="m"> + {`${cartItemQuantity(id)}개`} + </Text> + )} + </S.ItemDetail> + </S.ItemBody> + </S.CartItem> + ); +}; + +export default CartItem;
Unknown
저도 비슷하게 생각하는데요. 체크, 삭제버튼, 숫자 버튼 등 지금은 경우의 수가 2**3개 밖에 없어서 타입으로 일일히 지정해줄 수 있지만, 요구사항이 늘어나면 타입으로는 버거울수도 있다는 생각이 들어요..!
@@ -0,0 +1,172 @@ +import type { Meta, StoryObj } from '@storybook/react'; +<<<<<<< HEAD +import CartItemList from './CartItemList'; +import { RecoilRoot } from 'recoil'; +import { cartItemListState } from '../../recoil/cartItem/atom'; + +const MOCK_DATA = [ + { + id: 586, + quantity: 4, + name: '나이키', + price: 1000, + imageUrl: + 'https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/a28864e3-de02-48bb-b861-9c592bc9a68b/%EB%B6%81-1-ep-%EB%86%8D%EA%B5%AC%ED%99%94-UOp6QQvg.png', + }, + { + id: 587, + quantity: 3, + + name: '아디다스', + price: 2000, + imageUrl: 'https://sitem.ssgcdn.com/74/25/04/item/1000373042574_i1_750.jpg', + }, + { + id: 588, + quantity: 1, + name: '퓨마', + price: 10000, + imageUrl: 'https://sitem.ssgcdn.com/47/78/22/item/1000031227847_i1_750.jpg', + }, + { + id: 589, + quantity: 4, + + name: '리복', + price: 20000, + imageUrl: + 'https://image.msscdn.net/images/goods_img/20221031/2909092/2909092_6_500.jpg', + }, + { + id: 590, + quantity: 5, + + name: '컨버스', + price: 20000, + imageUrl: 'https://sitem.ssgcdn.com/65/73/69/item/1000163697365_i1_750.jpg', + }, +]; +======= +import CartItemList, { CartItemListProps } from './CartItemList'; +import { RecoilRoot } from 'recoil'; +>>>>>>> todari + +const meta = { + title: 'Components/CartItemList', + component: CartItemList, + tags: ['autodocs'], + argTypes: { +<<<<<<< HEAD + type: { + description: '', + control: { type: 'radio' }, + options: ['cart', 'confirm'], + }, + cartItemList: { + description: '', + control: { type: 'object' }, + }, + }, + args: { + type: 'cart', + cartItemList: MOCK_DATA, + }, +======= + itemList: { + description: '', + control: { type: 'object' }, + } + }, + args: { + itemList: [ + { + "cartItemId": 586, + "quantity": 4, + "product": { + "productId": 2, + "name": "나이키", + "price": 1000, + "imageUrl": "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/a28864e3-de02-48bb-b861-9c592bc9a68b/%EB%B6%81-1-ep-%EB%86%8D%EA%B5%AC%ED%99%94-UOp6QQvg.png", + "category": "fashion" + } + }, + { + "cartItemId": 587, + "quantity": 3, + "product": { + "productId": 3, + "name": "아디다스", + "price": 2000, + "imageUrl": "https://sitem.ssgcdn.com/74/25/04/item/1000373042574_i1_750.jpg", + "category": "fashion" + } + }, + { + "cartItemId": 588, + "quantity": 1, + "product": { + "productId": 10, + "name": "퓨마", + "price": 10000, + "imageUrl": "https://sitem.ssgcdn.com/47/78/22/item/1000031227847_i1_750.jpg", + "category": "fashion" + } + }, + { + "cartItemId": 589, + "quantity": 4, + "product": { + "productId": 11, + "name": "리복", + "price": 20000, + "imageUrl": "https://image.msscdn.net/images/goods_img/20221031/2909092/2909092_6_500.jpg", + "category": "fashion" + } + }, + { + "cartItemId": 590, + "quantity": 5, + "product": { + "productId": 12, + "name": "컨버스", + "price": 20000, + "imageUrl": "https://sitem.ssgcdn.com/65/73/69/item/1000163697365_i1_750.jpg", + "category": "fashion" + } + } + ], + } +>>>>>>> todari +} satisfies Meta<typeof CartItemList>; + +export default meta; + +type Story = StoryObj<typeof meta>; + +<<<<<<< HEAD +export const Playground: Story = { + render: ({ type, cartItemList }) => { + return ( + <RecoilRoot + initializeState={({ set }) => set(cartItemListState, MOCK_DATA)} + > + <div style={{ width: '430px' }}> + <CartItemList type={type} cartItemList={cartItemList} /> + </div> + </RecoilRoot> + ); + }, +======= +// TODO : decorator 사용하여 동작할 수 있도록 current: recoil로 인해 작동 x +export const Playground: Story = { + render: ({ ...args }: CartItemListProps) => { + return ( + <RecoilRoot> + <div style={{ width: '430px' }}> + <CartItemList {...args} /> + </div> + </RecoilRoot> + ) + } +>>>>>>> todari +};
Unknown
리베이스의 흔적이ㅠ
@@ -1,7 +1,14 @@ package christmas; +import christmas.controller.ChristmasController; +import christmas.exception.ExceptionHandler; +import christmas.exception.RetryExceptionHandler; + public class Application { public static void main(String[] args) { - // TODO: 프로그램 구현 + ExceptionHandler handler = new RetryExceptionHandler(); + + ChristmasController controller = new ChristmasController(handler); + controller.service(); } }
Java
메서드는 동사로 하는 것이 좋다고 생각하는데, service() 는 정비하다 라는 의미라고 해요! 물론, 서비스 하다~ 라는 느낌인 건 이해하지만 execute()나 operate() 와 같은 동작을 강조하는 동사를 사용하는 건 어떨까 하는 개인적 의견입니다!
@@ -0,0 +1,25 @@ +package christmas.constant; + +public enum Badge { + NONE("없음", 0), + STAR("별", 5_000), + TREE("트리", 10_000), + SANTA("산타", 20_000); + + + private final String badgeName; + private final long prize; + + Badge(String badgeName, long prize){ + this.badgeName = badgeName; + this.prize = prize; + } + + public String getBadgeName(){ + return badgeName; + } + + public long getPrize(){ + return prize; + } +}
Java
이 부분 참 고민 많이 헀는데요, 저도 "없음" 배지를 만든 뒤 고민해보니 도메인 쪽에서 출력 로직을 알아야하는 것 같아서 없음 배지를 삭제하고, Dto에 비어있는 badgeName 값을 넣는 식으로 구현한 후 OutputView에서 전달받은 이벤트 배지 값이 비어있는 String이면 없애는 식으로 처리했습니다. 수진님은 어떻게 생각하시나요?
@@ -0,0 +1,41 @@ +package christmas.constant; + +public enum Menu { + YANGSONGSOUP("양송이수프", 6000, MenuType.APPETIZER), + TAPAS("타파스", 5500, MenuType.APPETIZER), + CAESAR_SALAD("시저샐러드", 8000, MenuType.APPETIZER), + + T_BONE_STEAK("티본스테이크", 55000, MenuType.MAIN), + BBQ_RIB("바비큐립", 54000, MenuType.MAIN), + SEAFOOD_PASTA("해산물파스타", 35000, MenuType.MAIN), + CHRISTMAS_PASTA("크리스마스파스타", 25000, MenuType.MAIN), + + CHOCO_CAKE("초코케이크", 15000, MenuType.DESSERT), + ICE_CREAM("아이스크림", 5000, MenuType.DESSERT), + + ZERO_COLA("제로콜라", 3000, MenuType.BEVERAGE), + RED_WINE("레드와인", 60000, MenuType.BEVERAGE), + CHAMPAGNE("샴페인", 25000, MenuType.BEVERAGE); + + private final String name; + private final int price; + private final MenuType menuType; + + Menu(String name, int price, MenuType menuType) { + this.name = name; + this.price = price; + this.menuType = menuType; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public MenuType getMenuType() { + return menuType; + } +}
Java
MenuType을 static import 하면 좀 더 짧게 코드를 작성할 수 있을거 같아요!
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.constant.Menu; +import christmas.domain.BenefitStorage; +import christmas.dto.BenefitResult; +import christmas.domain.Customer; +import christmas.domain.EventPlanner; +import christmas.dto.OrderMenu; +import christmas.exception.ExceptionHandler; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.Map; + +public class ChristmasController { + + private final ExceptionHandler handler; + private Customer customer; + private EventPlanner eventPlanner; + + + public ChristmasController(ExceptionHandler handler){ + this.handler = handler; + } + + public void service(){ + order(); + searchPromotion(customer); + } + + public void order(){ + int date = getDate(); + Map<Menu, Integer> menu = getMenu(); + customer = new Customer(date, menu); + + displayOrder(date, menu); + } + + private int getDate(){ + return handler.getResult(InputView::readVisitDate); + } + + private Map<Menu, Integer> getMenu(){ + return handler.getResult(InputView::readMenu); + } + + private void searchPromotion(Customer customer){ + eventPlanner = new EventPlanner(); + eventPlanner.findPromotion(customer); + + BenefitStorage benefitStorage = storeBenefits(); + previewEventBenefits(benefitStorage); + } + + private BenefitStorage storeBenefits(){ + if(eventPlanner.hasGiftMenu()){ + return new BenefitStorage(customer.getTotalOrderAmount(), true, eventPlanner.getPromotionResult()); + } + return new BenefitStorage(customer.getTotalOrderAmount(), false, eventPlanner.getPromotionResult()); + } + + private void displayOrder(int date, Map<Menu, Integer> menu){ + OrderMenu orderMenu = new OrderMenu(date, menu); + OutputView.printOrder(orderMenu); + } + + + private void previewEventBenefits(BenefitStorage benefitStorage){ + BenefitResult benefitResult = new BenefitResult(benefitStorage.getBeforeDiscountAmount(), + benefitStorage.isGiftMenu(), benefitStorage.getPromotionResult(), benefitStorage.totalBenefitAmount(), + benefitStorage.afterDiscountAmount(), benefitStorage.determineBadge()); + OutputView.printPreview(benefitResult); + } + +}
Java
사소하지만 네이밍을 `OrderedMenu` 로 하면 어떨까요?
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.constant.Menu; +import christmas.domain.BenefitStorage; +import christmas.dto.BenefitResult; +import christmas.domain.Customer; +import christmas.domain.EventPlanner; +import christmas.dto.OrderMenu; +import christmas.exception.ExceptionHandler; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.Map; + +public class ChristmasController { + + private final ExceptionHandler handler; + private Customer customer; + private EventPlanner eventPlanner; + + + public ChristmasController(ExceptionHandler handler){ + this.handler = handler; + } + + public void service(){ + order(); + searchPromotion(customer); + } + + public void order(){ + int date = getDate(); + Map<Menu, Integer> menu = getMenu(); + customer = new Customer(date, menu); + + displayOrder(date, menu); + } + + private int getDate(){ + return handler.getResult(InputView::readVisitDate); + } + + private Map<Menu, Integer> getMenu(){ + return handler.getResult(InputView::readMenu); + } + + private void searchPromotion(Customer customer){ + eventPlanner = new EventPlanner(); + eventPlanner.findPromotion(customer); + + BenefitStorage benefitStorage = storeBenefits(); + previewEventBenefits(benefitStorage); + } + + private BenefitStorage storeBenefits(){ + if(eventPlanner.hasGiftMenu()){ + return new BenefitStorage(customer.getTotalOrderAmount(), true, eventPlanner.getPromotionResult()); + } + return new BenefitStorage(customer.getTotalOrderAmount(), false, eventPlanner.getPromotionResult()); + } + + private void displayOrder(int date, Map<Menu, Integer> menu){ + OrderMenu orderMenu = new OrderMenu(date, menu); + OutputView.printOrder(orderMenu); + } + + + private void previewEventBenefits(BenefitStorage benefitStorage){ + BenefitResult benefitResult = new BenefitResult(benefitStorage.getBeforeDiscountAmount(), + benefitStorage.isGiftMenu(), benefitStorage.getPromotionResult(), benefitStorage.totalBenefitAmount(), + benefitStorage.afterDiscountAmount(), benefitStorage.determineBadge()); + OutputView.printPreview(benefitResult); + } + +}
Java
`customer = new Customer(getDate(), getMenu());` 로 한번에 해도 좋을 거 같아요. `getDate()` 나 `getMenu()` 둘 다 메서드 이름으로 뭐를 하는지 정확히 알 수 있어보입니다.
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
Map 타입으로 인스턴스 변수를 가지면 추후 세부 구현 자료구조가 바뀔 때 능동적으로 대처할 수 있을거 같아요!
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
어찌보면 Dto에 가까운 성격을 가지는 클래스인데 도메인 로직을 다 넣어둔 느낌을 받았습니다. 결국 출력때 필요한 자료들을 다 가지고 있어서 도메인을 다른 방식으로 분리해보는 것을 고려해보면 어떨까요?
@@ -0,0 +1,71 @@ +package christmas.domain; + +import christmas.constant.MenuType; +import christmas.constant.PromotionType; +import christmas.domain.promotion.ChristmasPromotion; +import christmas.domain.promotion.DdayPromotion; +import christmas.domain.promotion.GiftPromotion; +import christmas.domain.promotion.SpecialPromotion; +import christmas.domain.promotion.WeekDayPromotion; +import christmas.domain.promotion.WeekendPromotion; +import java.util.HashMap; +import java.util.Map; + +public class EventPlanner { + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public EventPlanner(){ + promotionResult = new HashMap<>(); + promotionResult.put(new DdayPromotion(), 0L); + promotionResult.put(new GiftPromotion(), 0L); + promotionResult.put(new SpecialPromotion(), 0L); + promotionResult.put(new WeekDayPromotion(), 0L); + promotionResult.put(new WeekendPromotion(), 0L); + } + + public void findPromotion(Customer customer){ + for(ChristmasPromotion promotion : promotionResult.keySet()){ + checkPromotionConditions(promotion, customer); + } + } + + public boolean hasGiftMenu(){ + return promotionResult.entrySet() + .stream() + .filter(entry -> entry.getKey() instanceof GiftPromotion) + .mapToLong(Map.Entry::getValue) + .sum() > 0; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult(){ + return promotionResult; + } + + private void checkPromotionConditions(ChristmasPromotion promotion, Customer customer){ + long discount = customer.applicablePromotion(promotion); + + if (isContainWeekOrWeekend(promotion)) { + discount *= checkMenuCount(customer, promotion.getPromotionType()); + } + promotionResult.put(promotion, promotionResult.get(promotion) + discount); + } + + private int checkMenuCount(Customer customer, PromotionType promotionType) { + Map<PromotionType, MenuType> promotionTypeMenuTypeMap = Map.of( + PromotionType.WEEKDAY, MenuType.DESSERT, + PromotionType.WEEKEND, MenuType.MAIN + ); + + MenuType menuType = promotionTypeMenuTypeMap.getOrDefault(promotionType, MenuType.NONE); + return customer.countMenuType(menuType); + } + + private boolean isContainWeekOrWeekend(ChristmasPromotion promotion){ + if(promotion.getPromotionType() == PromotionType.WEEKDAY + || promotion.getPromotionType() == PromotionType.WEEKEND) + return true; + + return false; + } + +}
Java
변수 명에 Map 을 사용하는 것보다는 `PromotionsAppliedToEachMenu` 와 같이 사용하는 것은 어떨까요?
@@ -0,0 +1,43 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class DdayPromotion extends ChristmasPromotion{ + + private static final int START_DATE = 1; + private static final int END_DATE = 25; + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + + public DdayPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.DDAY; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(data); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return date >= period.get(0) && date <= period.get(1); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + public long getDiscountAmount(int date) { + return discountAmount + 100L * (date - 1); + } +}
Java
매직넘버를 상수로 두는건 어떨까요?
@@ -0,0 +1,39 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class GiftPromotion extends ChristmasPromotion{ + + private static final long PRICETHRESHOLD = 120000; + private static final int START_DATE = 1; + private static final int END_DATE = 31; + private static final int INIT_DISCOUNT_AMOUNT = 25000; + + public GiftPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.GIFT_CHAMPAGNE; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.GIFT; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return date >= period.get(0) && date <= period.get(1); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= PRICETHRESHOLD; + } + +}
Java
`PRICE_THRESHOLD` 와 같이 나눠주면 가독성이 더 좋아질 것 같습니다!
@@ -0,0 +1,38 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class SpecialPromotion extends ChristmasPromotion{ + + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + public SpecialPromotion(){ + this.period = Arrays.asList(3, 10, 17, 24, 25, 31); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.SPECIAL; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return period.contains(date); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + +}
Java
요것도 매직넘버! 혹은 1~31 값 중 7로 나누었을 때 나머지가 3인 날짜로 초기화해줘도 좋을 거 같아요
@@ -0,0 +1,38 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class SpecialPromotion extends ChristmasPromotion{ + + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + public SpecialPromotion(){ + this.period = Arrays.asList(3, 10, 17, 24, 25, 31); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.SPECIAL; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return period.contains(date); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + +}
Java
공백도 코딩컨벤션이라, 다른 클래스 파일과 맞춰주는게 어떨까요?
@@ -0,0 +1,47 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.time.LocalDate; +import java.time.DayOfWeek; +import java.util.Arrays; + +public class WeekDayPromotion extends ChristmasPromotion{ + + private static final int START_DATE = 1; + private static final int END_DATE = 31; + private static final int INIT_DISCOUNT_AMOUNT = 2023; + private static final int MIN_ORDER_AMOUNT = 10000; + + public WeekDayPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.DESSERT_MENU; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.WEEKDAY; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + LocalDate orderDate = LocalDate.of(2023, 12, date); + + return isWeekday(orderDate); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + private boolean isWeekday(LocalDate date) { + DayOfWeek dayOfWeek = date.getDayOfWeek(); + return dayOfWeek != DayOfWeek.FRIDAY && dayOfWeek != DayOfWeek.SATURDAY; + } +}
Java
내부 상수로 두는 것보다, 생성될 때 위의 상수 값으로 초기화 시키고 객체를 싱글톤으로 관리하는 것도 좋을 것 같아요
@@ -0,0 +1,7 @@ +package christmas.exception; + +import java.util.function.Supplier; + +public interface ExceptionHandler { + <T> T getResult(Supplier<T> supplier); +}
Java
`Supplier` 라는 문법은 처음보네요! 함수형 프로그래밍? 인가 보네요 ㅎㅎ 배워갑니다.
@@ -0,0 +1,28 @@ +package christmas.exception; + +import christmas.view.OutputView; +import java.util.function.Supplier; + +public class RetryExceptionHandler implements ExceptionHandler{ + + @Override + public <T> T getResult(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (IllegalArgumentException e) { + printException(e); + } finally { + afterHandlingException(); + } + } + } + + private void printException(IllegalArgumentException e) { + OutputView.printErrorMessage(e); + } + + private void afterHandlingException() { + OutputView.printEmptyLine(); + } +}
Java
이렇게 하면 try-catch문의 중복 로직을 뺄 수 있겠군요.!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
해당 메서드는 Map을 반환하기 보다는 void 형식으로 예외를 던질 것 같은 네이밍이라 느껴져요. 역할을 검증 및 반환 두개를 하는 것 같은데 각 역할에 맞는 메서드로 나눠보는 것은 어떻게 생각하시나요?
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
조건문의 조건을 하나의 메서드로 빼는 것도 좋을 것 같습니다.
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
null 을 직접 다루는 것보다, Menu 내에서 이름을 받아서 Menu의 유무를 처리하는 메서드를 만드는 것은 어떨까요?
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
이 부분에서 Exception을 던져주는 것도 좋을 것 같아요!