code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,25 @@ +package store.constant.message; + +public enum ErrorMessage { + + INVALID_FORMAT("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요."), + NOT_FOUND_PRODUCT("존재하지 않는 상품입니다. 다시 입력해 주세요."), + INSUFFICIENT_STOCK("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."), + GENERAL_INVALID_INPUT("잘못된 입력입니다. 다시 입력해 주세요."), + NOT_FOUND_FILE("파일이 존재하지 않습니다."), + INVALID_FILE_VALUE("파일의 값이 유효하지 않습니다."), + NOT_FOUND_PROMOTION("존재하지 않는 프로모션입니다."), + NOT_FOUND_RECEIPT("영수증이 존재하지 않습니다."), + ; + + private static final String PREFIX = "[ERROR] "; + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return PREFIX + message; + } +}
Java
`다시 입력해 주세요.`가 반복되고 있네요! 별도 상수로 분리해보는 건 어떨까요!?
@@ -0,0 +1,25 @@ +package store.constant.message; + +public enum ErrorMessage { + + INVALID_FORMAT("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요."), + NOT_FOUND_PRODUCT("존재하지 않는 상품입니다. 다시 입력해 주세요."), + INSUFFICIENT_STOCK("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."), + GENERAL_INVALID_INPUT("잘못된 입력입니다. 다시 입력해 주세요."), + NOT_FOUND_FILE("파일이 존재하지 않습니다."), + INVALID_FILE_VALUE("파일의 값이 유효하지 않습니다."), + NOT_FOUND_PROMOTION("존재하지 않는 프로모션입니다."), + NOT_FOUND_RECEIPT("영수증이 존재하지 않습니다."), + ; + + private static final String PREFIX = "[ERROR] "; + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return PREFIX + message; + } +}
Java
공통되는 문구를 상수로 분리해주셨네요! 👍
@@ -0,0 +1,37 @@ +package store.constant.message; + +public enum OutputMessage { + START_GUIDANCE("안녕하세요. W편의점입니다."), + EXISTING_STOCKS_GUIDANCE("현재 보유하고 있는 상품입니다."), + EXISTING_STOCKS("- %s %,d원 %s %s"), + STOCKS_COUNT("%%s개"), + PURCHASE_PRODUCTS_GUIDANCE("구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])"), + ADDING_QUANTITY_STATUS_GUIDANCE("현재 %s은(는) %d개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N))"), + REGULAR_PRICE_PAYMENT_STATUS_GUIDANCE("현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)"), + MEMBERSHIP_APPLICATION_STATUS_GUIDANCE("멤버십 할인을 받으시겠습니까? (Y/N)"), + ADDITIONAL_PURCHASE_STATUS_GUIDANCE("감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)"), + + RECEIPT_TITLE_HEADER("===========W 편의점============="), + RECEIPT_PURCHASE_PRODUCTS_HEADER("상품명\t\t\t수량\t\t금액"), + RECEIPT_GIFTS_HEADER("===========증\t정============="), + RECEIPT_DIVISION_HEADER("=============================="), + RECEIPT_TOTAL_PURCHASE_AMOUNT("총구매액\t\t\t%d\t%,10d"), + RECEIPT_PROMOTION_DISCOUNT("행사할인\t\t\t\t\t-%,d"), + RECEIPT_MEMBERSHIP_DISCOUNT("멤버십할인\t\t\t\t\t-%,d"), + RECEIPT_FINAL_AMOUNT("내실돈\t%,22d"), + RECEIPT_PURCHASE_PRODUCT_LINE("%-11s\t%d\t%,10d"), + RECEIPT_GIFT_LINE("%-11s\t%d"), + + NEW_LINE("%n"), + ; + + private final String message; + + OutputMessage(String message) { + this.message = message; + } + + public String getMessage(Object... args) { + return String.format(message, args); + } +}
Java
가변인자를 잘 활용해주셨네요! 👍
@@ -0,0 +1,130 @@ +package store.controller; + +import static store.constant.ConvenienceConstant.MAX_RETRIES; + +import java.util.List; +import java.util.function.Supplier; +import store.model.Status; +import store.dto.request.input.AddingQuantityStatusRequest; +import store.dto.request.input.AdditionalPurchaseStatusRequest; +import store.dto.request.input.MembershipApplicationStatusRequest; +import store.dto.request.input.PurchaseProductsRequest; +import store.dto.request.input.RegularPricePaymentStatusRequest; +import store.dto.response.ReceiptResponse; +import store.dto.response.StocksResponse; +import store.dto.server.StatusDto; +import store.service.convenience.ConvenienceService; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceController { + + private final ConvenienceService convenienceService; + + public ConvenienceController(ConvenienceService convenienceService) { + this.convenienceService = convenienceService; + } + + public void run() { + do { + execute(this::processStart); + execute(() -> processStatuses(processPurchaseProducts())); + execute(this::processMembershipApplicationStatus); + execute(this::processReceipt); + } while (execute(this::processAdditionalPurchaseStatus)); + } + + private void processStart() { + OutputView.printStartGuidance(); + StocksResponse stocksResponse = convenienceService.createStocksResponse(); + OutputView.printStocks(stocksResponse); + } + + private List<StatusDto> processPurchaseProducts() { + OutputView.printPurchaseProductsGuidance(); + PurchaseProductsRequest purchaseProductsRequest = InputView.readPurchaseProducts(); + convenienceService.createReceipt(); + return convenienceService.purchaseProducts(purchaseProductsRequest); + } + + private void processStatuses(List<StatusDto> statusDtos) { + for (StatusDto statusDto : statusDtos) { + if (statusDto.getStatus().equals(Status.ADDING_QUANTITY)) { + execute(() -> processAddingQuantityStatus(statusDto)); + continue; + } + if (statusDto.getStatus().equals(Status.REGULAR_PRICE_PAYMENT)) { + execute(() -> processRegularPricePaymentStatus(statusDto)); + } + } + } + + private void processAddingQuantityStatus(StatusDto statusDto) { + OutputView.printAddingQuantityStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + AddingQuantityStatusRequest addingQuantityStatusRequest = InputView.readAddingQuantityStatus(); + if (addingQuantityStatusRequest.isAddingQuantityStatus()) { + convenienceService.applyAddingQuantity(statusDto); + } + } + + private void processRegularPricePaymentStatus(StatusDto statusDto) { + OutputView.printRegularPricePaymentStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + RegularPricePaymentStatusRequest regularPricePaymentStatusRequest = InputView.readRegularPricePaymentStatus(); + if (regularPricePaymentStatusRequest.isRegularPricePaymentStatus()) { + convenienceService.applyRegularPricePayment(statusDto); + } + } + + private void processMembershipApplicationStatus() { + OutputView.printMembershipApplicationStatusGuidance(); + MembershipApplicationStatusRequest membershipApplicationStatusRequest = InputView.readMembershipApplicationStatus(); + if (membershipApplicationStatusRequest.isMembershipApplicationStatus()) { + convenienceService.applyMembership(); + } + } + + private void processReceipt() { + ReceiptResponse receiptResponse = convenienceService.createReceiptResponse(); + OutputView.printReceipt(receiptResponse); + } + + private boolean processAdditionalPurchaseStatus() { + OutputView.printAdditionalPurchaseStatusGuidance(); + AdditionalPurchaseStatusRequest additionalPurchaseStatusRequest = InputView.readAdditionalPurchaseStatus(); + return additionalPurchaseStatusRequest.isAdditionalPurchaseStatus(); + } + + private void execute(Runnable action) { + execute(action, 0); + } + + private void execute(Runnable action, int attempts) { + try { + action.run(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return; + } + OutputView.printErrorMessage(e); + execute(action, attempts + 1); + } + } + + private boolean execute(Supplier<Boolean> action) { + return execute(action, 0); + } + + private boolean execute(Supplier<Boolean> action, int attempts) { + try { + return action.get(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return false; + } + OutputView.printErrorMessage(e); + return execute(action, attempts + 1); + } + } +}
Java
processStatuses가 무슨 역할을 하는지 직관적으로 이해하기 힘든 것 같아요..!! 무슨 의미로 네이밍하신 건지 궁금해요!
@@ -0,0 +1,130 @@ +package store.controller; + +import static store.constant.ConvenienceConstant.MAX_RETRIES; + +import java.util.List; +import java.util.function.Supplier; +import store.model.Status; +import store.dto.request.input.AddingQuantityStatusRequest; +import store.dto.request.input.AdditionalPurchaseStatusRequest; +import store.dto.request.input.MembershipApplicationStatusRequest; +import store.dto.request.input.PurchaseProductsRequest; +import store.dto.request.input.RegularPricePaymentStatusRequest; +import store.dto.response.ReceiptResponse; +import store.dto.response.StocksResponse; +import store.dto.server.StatusDto; +import store.service.convenience.ConvenienceService; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceController { + + private final ConvenienceService convenienceService; + + public ConvenienceController(ConvenienceService convenienceService) { + this.convenienceService = convenienceService; + } + + public void run() { + do { + execute(this::processStart); + execute(() -> processStatuses(processPurchaseProducts())); + execute(this::processMembershipApplicationStatus); + execute(this::processReceipt); + } while (execute(this::processAdditionalPurchaseStatus)); + } + + private void processStart() { + OutputView.printStartGuidance(); + StocksResponse stocksResponse = convenienceService.createStocksResponse(); + OutputView.printStocks(stocksResponse); + } + + private List<StatusDto> processPurchaseProducts() { + OutputView.printPurchaseProductsGuidance(); + PurchaseProductsRequest purchaseProductsRequest = InputView.readPurchaseProducts(); + convenienceService.createReceipt(); + return convenienceService.purchaseProducts(purchaseProductsRequest); + } + + private void processStatuses(List<StatusDto> statusDtos) { + for (StatusDto statusDto : statusDtos) { + if (statusDto.getStatus().equals(Status.ADDING_QUANTITY)) { + execute(() -> processAddingQuantityStatus(statusDto)); + continue; + } + if (statusDto.getStatus().equals(Status.REGULAR_PRICE_PAYMENT)) { + execute(() -> processRegularPricePaymentStatus(statusDto)); + } + } + } + + private void processAddingQuantityStatus(StatusDto statusDto) { + OutputView.printAddingQuantityStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + AddingQuantityStatusRequest addingQuantityStatusRequest = InputView.readAddingQuantityStatus(); + if (addingQuantityStatusRequest.isAddingQuantityStatus()) { + convenienceService.applyAddingQuantity(statusDto); + } + } + + private void processRegularPricePaymentStatus(StatusDto statusDto) { + OutputView.printRegularPricePaymentStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + RegularPricePaymentStatusRequest regularPricePaymentStatusRequest = InputView.readRegularPricePaymentStatus(); + if (regularPricePaymentStatusRequest.isRegularPricePaymentStatus()) { + convenienceService.applyRegularPricePayment(statusDto); + } + } + + private void processMembershipApplicationStatus() { + OutputView.printMembershipApplicationStatusGuidance(); + MembershipApplicationStatusRequest membershipApplicationStatusRequest = InputView.readMembershipApplicationStatus(); + if (membershipApplicationStatusRequest.isMembershipApplicationStatus()) { + convenienceService.applyMembership(); + } + } + + private void processReceipt() { + ReceiptResponse receiptResponse = convenienceService.createReceiptResponse(); + OutputView.printReceipt(receiptResponse); + } + + private boolean processAdditionalPurchaseStatus() { + OutputView.printAdditionalPurchaseStatusGuidance(); + AdditionalPurchaseStatusRequest additionalPurchaseStatusRequest = InputView.readAdditionalPurchaseStatus(); + return additionalPurchaseStatusRequest.isAdditionalPurchaseStatus(); + } + + private void execute(Runnable action) { + execute(action, 0); + } + + private void execute(Runnable action, int attempts) { + try { + action.run(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return; + } + OutputView.printErrorMessage(e); + execute(action, attempts + 1); + } + } + + private boolean execute(Supplier<Boolean> action) { + return execute(action, 0); + } + + private boolean execute(Supplier<Boolean> action, int attempts) { + try { + return action.get(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return false; + } + OutputView.printErrorMessage(e); + return execute(action, attempts + 1); + } + } +}
Java
사소하지만 StatusDto.status에 null이 들어있으면 NPE가 발생할 수 있을 것 같습니다! 어떻게 개선할 수 있을까요..!?
@@ -0,0 +1,130 @@ +package store.controller; + +import static store.constant.ConvenienceConstant.MAX_RETRIES; + +import java.util.List; +import java.util.function.Supplier; +import store.model.Status; +import store.dto.request.input.AddingQuantityStatusRequest; +import store.dto.request.input.AdditionalPurchaseStatusRequest; +import store.dto.request.input.MembershipApplicationStatusRequest; +import store.dto.request.input.PurchaseProductsRequest; +import store.dto.request.input.RegularPricePaymentStatusRequest; +import store.dto.response.ReceiptResponse; +import store.dto.response.StocksResponse; +import store.dto.server.StatusDto; +import store.service.convenience.ConvenienceService; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceController { + + private final ConvenienceService convenienceService; + + public ConvenienceController(ConvenienceService convenienceService) { + this.convenienceService = convenienceService; + } + + public void run() { + do { + execute(this::processStart); + execute(() -> processStatuses(processPurchaseProducts())); + execute(this::processMembershipApplicationStatus); + execute(this::processReceipt); + } while (execute(this::processAdditionalPurchaseStatus)); + } + + private void processStart() { + OutputView.printStartGuidance(); + StocksResponse stocksResponse = convenienceService.createStocksResponse(); + OutputView.printStocks(stocksResponse); + } + + private List<StatusDto> processPurchaseProducts() { + OutputView.printPurchaseProductsGuidance(); + PurchaseProductsRequest purchaseProductsRequest = InputView.readPurchaseProducts(); + convenienceService.createReceipt(); + return convenienceService.purchaseProducts(purchaseProductsRequest); + } + + private void processStatuses(List<StatusDto> statusDtos) { + for (StatusDto statusDto : statusDtos) { + if (statusDto.getStatus().equals(Status.ADDING_QUANTITY)) { + execute(() -> processAddingQuantityStatus(statusDto)); + continue; + } + if (statusDto.getStatus().equals(Status.REGULAR_PRICE_PAYMENT)) { + execute(() -> processRegularPricePaymentStatus(statusDto)); + } + } + } + + private void processAddingQuantityStatus(StatusDto statusDto) { + OutputView.printAddingQuantityStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + AddingQuantityStatusRequest addingQuantityStatusRequest = InputView.readAddingQuantityStatus(); + if (addingQuantityStatusRequest.isAddingQuantityStatus()) { + convenienceService.applyAddingQuantity(statusDto); + } + } + + private void processRegularPricePaymentStatus(StatusDto statusDto) { + OutputView.printRegularPricePaymentStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + RegularPricePaymentStatusRequest regularPricePaymentStatusRequest = InputView.readRegularPricePaymentStatus(); + if (regularPricePaymentStatusRequest.isRegularPricePaymentStatus()) { + convenienceService.applyRegularPricePayment(statusDto); + } + } + + private void processMembershipApplicationStatus() { + OutputView.printMembershipApplicationStatusGuidance(); + MembershipApplicationStatusRequest membershipApplicationStatusRequest = InputView.readMembershipApplicationStatus(); + if (membershipApplicationStatusRequest.isMembershipApplicationStatus()) { + convenienceService.applyMembership(); + } + } + + private void processReceipt() { + ReceiptResponse receiptResponse = convenienceService.createReceiptResponse(); + OutputView.printReceipt(receiptResponse); + } + + private boolean processAdditionalPurchaseStatus() { + OutputView.printAdditionalPurchaseStatusGuidance(); + AdditionalPurchaseStatusRequest additionalPurchaseStatusRequest = InputView.readAdditionalPurchaseStatus(); + return additionalPurchaseStatusRequest.isAdditionalPurchaseStatus(); + } + + private void execute(Runnable action) { + execute(action, 0); + } + + private void execute(Runnable action, int attempts) { + try { + action.run(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return; + } + OutputView.printErrorMessage(e); + execute(action, attempts + 1); + } + } + + private boolean execute(Supplier<Boolean> action) { + return execute(action, 0); + } + + private boolean execute(Supplier<Boolean> action, int attempts) { + try { + return action.get(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return false; + } + OutputView.printErrorMessage(e); + return execute(action, attempts + 1); + } + } +}
Java
REGULAR_PRICE_PAYMENT 상수에 대해 static import를 하는 것도 좋을 것 같아요!
@@ -0,0 +1,130 @@ +package store.controller; + +import static store.constant.ConvenienceConstant.MAX_RETRIES; + +import java.util.List; +import java.util.function.Supplier; +import store.model.Status; +import store.dto.request.input.AddingQuantityStatusRequest; +import store.dto.request.input.AdditionalPurchaseStatusRequest; +import store.dto.request.input.MembershipApplicationStatusRequest; +import store.dto.request.input.PurchaseProductsRequest; +import store.dto.request.input.RegularPricePaymentStatusRequest; +import store.dto.response.ReceiptResponse; +import store.dto.response.StocksResponse; +import store.dto.server.StatusDto; +import store.service.convenience.ConvenienceService; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceController { + + private final ConvenienceService convenienceService; + + public ConvenienceController(ConvenienceService convenienceService) { + this.convenienceService = convenienceService; + } + + public void run() { + do { + execute(this::processStart); + execute(() -> processStatuses(processPurchaseProducts())); + execute(this::processMembershipApplicationStatus); + execute(this::processReceipt); + } while (execute(this::processAdditionalPurchaseStatus)); + } + + private void processStart() { + OutputView.printStartGuidance(); + StocksResponse stocksResponse = convenienceService.createStocksResponse(); + OutputView.printStocks(stocksResponse); + } + + private List<StatusDto> processPurchaseProducts() { + OutputView.printPurchaseProductsGuidance(); + PurchaseProductsRequest purchaseProductsRequest = InputView.readPurchaseProducts(); + convenienceService.createReceipt(); + return convenienceService.purchaseProducts(purchaseProductsRequest); + } + + private void processStatuses(List<StatusDto> statusDtos) { + for (StatusDto statusDto : statusDtos) { + if (statusDto.getStatus().equals(Status.ADDING_QUANTITY)) { + execute(() -> processAddingQuantityStatus(statusDto)); + continue; + } + if (statusDto.getStatus().equals(Status.REGULAR_PRICE_PAYMENT)) { + execute(() -> processRegularPricePaymentStatus(statusDto)); + } + } + } + + private void processAddingQuantityStatus(StatusDto statusDto) { + OutputView.printAddingQuantityStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + AddingQuantityStatusRequest addingQuantityStatusRequest = InputView.readAddingQuantityStatus(); + if (addingQuantityStatusRequest.isAddingQuantityStatus()) { + convenienceService.applyAddingQuantity(statusDto); + } + } + + private void processRegularPricePaymentStatus(StatusDto statusDto) { + OutputView.printRegularPricePaymentStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + RegularPricePaymentStatusRequest regularPricePaymentStatusRequest = InputView.readRegularPricePaymentStatus(); + if (regularPricePaymentStatusRequest.isRegularPricePaymentStatus()) { + convenienceService.applyRegularPricePayment(statusDto); + } + } + + private void processMembershipApplicationStatus() { + OutputView.printMembershipApplicationStatusGuidance(); + MembershipApplicationStatusRequest membershipApplicationStatusRequest = InputView.readMembershipApplicationStatus(); + if (membershipApplicationStatusRequest.isMembershipApplicationStatus()) { + convenienceService.applyMembership(); + } + } + + private void processReceipt() { + ReceiptResponse receiptResponse = convenienceService.createReceiptResponse(); + OutputView.printReceipt(receiptResponse); + } + + private boolean processAdditionalPurchaseStatus() { + OutputView.printAdditionalPurchaseStatusGuidance(); + AdditionalPurchaseStatusRequest additionalPurchaseStatusRequest = InputView.readAdditionalPurchaseStatus(); + return additionalPurchaseStatusRequest.isAdditionalPurchaseStatus(); + } + + private void execute(Runnable action) { + execute(action, 0); + } + + private void execute(Runnable action, int attempts) { + try { + action.run(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return; + } + OutputView.printErrorMessage(e); + execute(action, attempts + 1); + } + } + + private boolean execute(Supplier<Boolean> action) { + return execute(action, 0); + } + + private boolean execute(Supplier<Boolean> action, int attempts) { + try { + return action.get(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return false; + } + OutputView.printErrorMessage(e); + return execute(action, attempts + 1); + } + } +}
Java
함수형 인터페이스를 적극적으로 활용해주셨네요! 💯
@@ -0,0 +1,130 @@ +package store.controller; + +import static store.constant.ConvenienceConstant.MAX_RETRIES; + +import java.util.List; +import java.util.function.Supplier; +import store.model.Status; +import store.dto.request.input.AddingQuantityStatusRequest; +import store.dto.request.input.AdditionalPurchaseStatusRequest; +import store.dto.request.input.MembershipApplicationStatusRequest; +import store.dto.request.input.PurchaseProductsRequest; +import store.dto.request.input.RegularPricePaymentStatusRequest; +import store.dto.response.ReceiptResponse; +import store.dto.response.StocksResponse; +import store.dto.server.StatusDto; +import store.service.convenience.ConvenienceService; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceController { + + private final ConvenienceService convenienceService; + + public ConvenienceController(ConvenienceService convenienceService) { + this.convenienceService = convenienceService; + } + + public void run() { + do { + execute(this::processStart); + execute(() -> processStatuses(processPurchaseProducts())); + execute(this::processMembershipApplicationStatus); + execute(this::processReceipt); + } while (execute(this::processAdditionalPurchaseStatus)); + } + + private void processStart() { + OutputView.printStartGuidance(); + StocksResponse stocksResponse = convenienceService.createStocksResponse(); + OutputView.printStocks(stocksResponse); + } + + private List<StatusDto> processPurchaseProducts() { + OutputView.printPurchaseProductsGuidance(); + PurchaseProductsRequest purchaseProductsRequest = InputView.readPurchaseProducts(); + convenienceService.createReceipt(); + return convenienceService.purchaseProducts(purchaseProductsRequest); + } + + private void processStatuses(List<StatusDto> statusDtos) { + for (StatusDto statusDto : statusDtos) { + if (statusDto.getStatus().equals(Status.ADDING_QUANTITY)) { + execute(() -> processAddingQuantityStatus(statusDto)); + continue; + } + if (statusDto.getStatus().equals(Status.REGULAR_PRICE_PAYMENT)) { + execute(() -> processRegularPricePaymentStatus(statusDto)); + } + } + } + + private void processAddingQuantityStatus(StatusDto statusDto) { + OutputView.printAddingQuantityStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + AddingQuantityStatusRequest addingQuantityStatusRequest = InputView.readAddingQuantityStatus(); + if (addingQuantityStatusRequest.isAddingQuantityStatus()) { + convenienceService.applyAddingQuantity(statusDto); + } + } + + private void processRegularPricePaymentStatus(StatusDto statusDto) { + OutputView.printRegularPricePaymentStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + RegularPricePaymentStatusRequest regularPricePaymentStatusRequest = InputView.readRegularPricePaymentStatus(); + if (regularPricePaymentStatusRequest.isRegularPricePaymentStatus()) { + convenienceService.applyRegularPricePayment(statusDto); + } + } + + private void processMembershipApplicationStatus() { + OutputView.printMembershipApplicationStatusGuidance(); + MembershipApplicationStatusRequest membershipApplicationStatusRequest = InputView.readMembershipApplicationStatus(); + if (membershipApplicationStatusRequest.isMembershipApplicationStatus()) { + convenienceService.applyMembership(); + } + } + + private void processReceipt() { + ReceiptResponse receiptResponse = convenienceService.createReceiptResponse(); + OutputView.printReceipt(receiptResponse); + } + + private boolean processAdditionalPurchaseStatus() { + OutputView.printAdditionalPurchaseStatusGuidance(); + AdditionalPurchaseStatusRequest additionalPurchaseStatusRequest = InputView.readAdditionalPurchaseStatus(); + return additionalPurchaseStatusRequest.isAdditionalPurchaseStatus(); + } + + private void execute(Runnable action) { + execute(action, 0); + } + + private void execute(Runnable action, int attempts) { + try { + action.run(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return; + } + OutputView.printErrorMessage(e); + execute(action, attempts + 1); + } + } + + private boolean execute(Supplier<Boolean> action) { + return execute(action, 0); + } + + private boolean execute(Supplier<Boolean> action, int attempts) { + try { + return action.get(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return false; + } + OutputView.printErrorMessage(e); + return execute(action, attempts + 1); + } + } +}
Java
최대 시도 횟수를 제한하신 이유가 무엇인가요!?
@@ -0,0 +1,130 @@ +package store.controller; + +import static store.constant.ConvenienceConstant.MAX_RETRIES; + +import java.util.List; +import java.util.function.Supplier; +import store.model.Status; +import store.dto.request.input.AddingQuantityStatusRequest; +import store.dto.request.input.AdditionalPurchaseStatusRequest; +import store.dto.request.input.MembershipApplicationStatusRequest; +import store.dto.request.input.PurchaseProductsRequest; +import store.dto.request.input.RegularPricePaymentStatusRequest; +import store.dto.response.ReceiptResponse; +import store.dto.response.StocksResponse; +import store.dto.server.StatusDto; +import store.service.convenience.ConvenienceService; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceController { + + private final ConvenienceService convenienceService; + + public ConvenienceController(ConvenienceService convenienceService) { + this.convenienceService = convenienceService; + } + + public void run() { + do { + execute(this::processStart); + execute(() -> processStatuses(processPurchaseProducts())); + execute(this::processMembershipApplicationStatus); + execute(this::processReceipt); + } while (execute(this::processAdditionalPurchaseStatus)); + } + + private void processStart() { + OutputView.printStartGuidance(); + StocksResponse stocksResponse = convenienceService.createStocksResponse(); + OutputView.printStocks(stocksResponse); + } + + private List<StatusDto> processPurchaseProducts() { + OutputView.printPurchaseProductsGuidance(); + PurchaseProductsRequest purchaseProductsRequest = InputView.readPurchaseProducts(); + convenienceService.createReceipt(); + return convenienceService.purchaseProducts(purchaseProductsRequest); + } + + private void processStatuses(List<StatusDto> statusDtos) { + for (StatusDto statusDto : statusDtos) { + if (statusDto.getStatus().equals(Status.ADDING_QUANTITY)) { + execute(() -> processAddingQuantityStatus(statusDto)); + continue; + } + if (statusDto.getStatus().equals(Status.REGULAR_PRICE_PAYMENT)) { + execute(() -> processRegularPricePaymentStatus(statusDto)); + } + } + } + + private void processAddingQuantityStatus(StatusDto statusDto) { + OutputView.printAddingQuantityStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + AddingQuantityStatusRequest addingQuantityStatusRequest = InputView.readAddingQuantityStatus(); + if (addingQuantityStatusRequest.isAddingQuantityStatus()) { + convenienceService.applyAddingQuantity(statusDto); + } + } + + private void processRegularPricePaymentStatus(StatusDto statusDto) { + OutputView.printRegularPricePaymentStatusGuidance(statusDto.getProductName(), statusDto.getQuantity()); + RegularPricePaymentStatusRequest regularPricePaymentStatusRequest = InputView.readRegularPricePaymentStatus(); + if (regularPricePaymentStatusRequest.isRegularPricePaymentStatus()) { + convenienceService.applyRegularPricePayment(statusDto); + } + } + + private void processMembershipApplicationStatus() { + OutputView.printMembershipApplicationStatusGuidance(); + MembershipApplicationStatusRequest membershipApplicationStatusRequest = InputView.readMembershipApplicationStatus(); + if (membershipApplicationStatusRequest.isMembershipApplicationStatus()) { + convenienceService.applyMembership(); + } + } + + private void processReceipt() { + ReceiptResponse receiptResponse = convenienceService.createReceiptResponse(); + OutputView.printReceipt(receiptResponse); + } + + private boolean processAdditionalPurchaseStatus() { + OutputView.printAdditionalPurchaseStatusGuidance(); + AdditionalPurchaseStatusRequest additionalPurchaseStatusRequest = InputView.readAdditionalPurchaseStatus(); + return additionalPurchaseStatusRequest.isAdditionalPurchaseStatus(); + } + + private void execute(Runnable action) { + execute(action, 0); + } + + private void execute(Runnable action, int attempts) { + try { + action.run(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return; + } + OutputView.printErrorMessage(e); + execute(action, attempts + 1); + } + } + + private boolean execute(Supplier<Boolean> action) { + return execute(action, 0); + } + + private boolean execute(Supplier<Boolean> action, int attempts) { + try { + return action.get(); + } catch (RuntimeException e) { + if (attempts == MAX_RETRIES) { + OutputView.printErrorMessage(e); + return false; + } + OutputView.printErrorMessage(e); + return execute(action, attempts + 1); + } + } +}
Java
반환형이 다른데 Runnable을 활용하는 메서드와 함께 오버로딩으로 가져가는 게 조금 우려되는 것 같아요..! `executeAndGet`처럼 반환형이 존재함을 강조하는 네이밍은 어떨까요!?
@@ -0,0 +1,90 @@ +package store.dto.request.file; + +import java.time.LocalDate; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PromotionRequest { + + private final String name; + private final Integer requiredCount; + private final Integer giftCount; + private final LocalDate startDate; + private final LocalDate endDate; + + private PromotionRequest(String name, Integer requiredCount, Integer giftCount, + LocalDate startDate, LocalDate endDate) { + this.name = name; + this.requiredCount = requiredCount; + this.giftCount = giftCount; + this.startDate = startDate; + this.endDate = endDate; + } + + public static PromotionRequest from(String line) { + List<String> separatedLine = CommonParser.separateBySeparator(line, ","); + + String name = parseName(separatedLine); + Integer requiredCount = parseRequiredCount(separatedLine); + Integer giftCount = parseGiftCount(separatedLine); + LocalDate startDate = parseStartDate(separatedLine); + LocalDate endDate = parseEndDate(separatedLine); + + return new PromotionRequest(name, requiredCount, giftCount, startDate, endDate); + } + + private static String parseName(List<String> line) { + String name = line.get(0); + CommonValidator.validateNotNull(name); + return name; + } + + private static Integer parseRequiredCount(List<String> line) { + String purchaseRequiredCount = line.get(1); + CommonValidator.validateNotNull(purchaseRequiredCount); + CommonValidator.validateNumeric(purchaseRequiredCount); + return CommonParser.convertStringToInteger(purchaseRequiredCount); + } + + private static Integer parseGiftCount(List<String> line) { + String giftCount = line.get(2); + CommonValidator.validateNotNull(giftCount); + CommonValidator.validateNumeric(giftCount); + return CommonParser.convertStringToInteger(giftCount); + } + + private static LocalDate parseStartDate(List<String> line) { + String startDate = line.get(3); + CommonValidator.validateNotNull(startDate); + CommonValidator.validateDate(startDate); + return CommonParser.parseDate(startDate); + } + + private static LocalDate parseEndDate(List<String> line) { + String endDate = line.get(4); + CommonValidator.validateNotNull(endDate); + CommonValidator.validateDate(endDate); + return CommonParser.parseDate(endDate); + } + + public String getName() { + return name; + } + + public Integer getRequiredCount() { + return requiredCount; + } + + public Integer getGiftCount() { + return giftCount; + } + + public LocalDate getStartDate() { + return startDate; + } + + public LocalDate getEndDate() { + return endDate; + } +}
Java
","은 상수화할 수 있을 것 같아요!
@@ -0,0 +1,90 @@ +package store.dto.request.file; + +import java.time.LocalDate; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PromotionRequest { + + private final String name; + private final Integer requiredCount; + private final Integer giftCount; + private final LocalDate startDate; + private final LocalDate endDate; + + private PromotionRequest(String name, Integer requiredCount, Integer giftCount, + LocalDate startDate, LocalDate endDate) { + this.name = name; + this.requiredCount = requiredCount; + this.giftCount = giftCount; + this.startDate = startDate; + this.endDate = endDate; + } + + public static PromotionRequest from(String line) { + List<String> separatedLine = CommonParser.separateBySeparator(line, ","); + + String name = parseName(separatedLine); + Integer requiredCount = parseRequiredCount(separatedLine); + Integer giftCount = parseGiftCount(separatedLine); + LocalDate startDate = parseStartDate(separatedLine); + LocalDate endDate = parseEndDate(separatedLine); + + return new PromotionRequest(name, requiredCount, giftCount, startDate, endDate); + } + + private static String parseName(List<String> line) { + String name = line.get(0); + CommonValidator.validateNotNull(name); + return name; + } + + private static Integer parseRequiredCount(List<String> line) { + String purchaseRequiredCount = line.get(1); + CommonValidator.validateNotNull(purchaseRequiredCount); + CommonValidator.validateNumeric(purchaseRequiredCount); + return CommonParser.convertStringToInteger(purchaseRequiredCount); + } + + private static Integer parseGiftCount(List<String> line) { + String giftCount = line.get(2); + CommonValidator.validateNotNull(giftCount); + CommonValidator.validateNumeric(giftCount); + return CommonParser.convertStringToInteger(giftCount); + } + + private static LocalDate parseStartDate(List<String> line) { + String startDate = line.get(3); + CommonValidator.validateNotNull(startDate); + CommonValidator.validateDate(startDate); + return CommonParser.parseDate(startDate); + } + + private static LocalDate parseEndDate(List<String> line) { + String endDate = line.get(4); + CommonValidator.validateNotNull(endDate); + CommonValidator.validateDate(endDate); + return CommonParser.parseDate(endDate); + } + + public String getName() { + return name; + } + + public Integer getRequiredCount() { + return requiredCount; + } + + public Integer getGiftCount() { + return giftCount; + } + + public LocalDate getStartDate() { + return startDate; + } + + public LocalDate getEndDate() { + return endDate; + } +}
Java
각 index가 어떤 필드를 의미하는지를 상수화하는 것도 좋을 것 같아요!
@@ -0,0 +1,90 @@ +package store.dto.request.file; + +import java.time.LocalDate; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PromotionRequest { + + private final String name; + private final Integer requiredCount; + private final Integer giftCount; + private final LocalDate startDate; + private final LocalDate endDate; + + private PromotionRequest(String name, Integer requiredCount, Integer giftCount, + LocalDate startDate, LocalDate endDate) { + this.name = name; + this.requiredCount = requiredCount; + this.giftCount = giftCount; + this.startDate = startDate; + this.endDate = endDate; + } + + public static PromotionRequest from(String line) { + List<String> separatedLine = CommonParser.separateBySeparator(line, ","); + + String name = parseName(separatedLine); + Integer requiredCount = parseRequiredCount(separatedLine); + Integer giftCount = parseGiftCount(separatedLine); + LocalDate startDate = parseStartDate(separatedLine); + LocalDate endDate = parseEndDate(separatedLine); + + return new PromotionRequest(name, requiredCount, giftCount, startDate, endDate); + } + + private static String parseName(List<String> line) { + String name = line.get(0); + CommonValidator.validateNotNull(name); + return name; + } + + private static Integer parseRequiredCount(List<String> line) { + String purchaseRequiredCount = line.get(1); + CommonValidator.validateNotNull(purchaseRequiredCount); + CommonValidator.validateNumeric(purchaseRequiredCount); + return CommonParser.convertStringToInteger(purchaseRequiredCount); + } + + private static Integer parseGiftCount(List<String> line) { + String giftCount = line.get(2); + CommonValidator.validateNotNull(giftCount); + CommonValidator.validateNumeric(giftCount); + return CommonParser.convertStringToInteger(giftCount); + } + + private static LocalDate parseStartDate(List<String> line) { + String startDate = line.get(3); + CommonValidator.validateNotNull(startDate); + CommonValidator.validateDate(startDate); + return CommonParser.parseDate(startDate); + } + + private static LocalDate parseEndDate(List<String> line) { + String endDate = line.get(4); + CommonValidator.validateNotNull(endDate); + CommonValidator.validateDate(endDate); + return CommonParser.parseDate(endDate); + } + + public String getName() { + return name; + } + + public Integer getRequiredCount() { + return requiredCount; + } + + public Integer getGiftCount() { + return giftCount; + } + + public LocalDate getStartDate() { + return startDate; + } + + public LocalDate getEndDate() { + return endDate; + } +}
Java
DTO에 record를 활용하지 않은 이유가 있는지 궁금해요! 😄
@@ -0,0 +1,25 @@ +package store.dto.request.input; + +import store.util.CommonParser; +import store.util.CommonValidator; + +public class AddingQuantityStatusRequest { + + private final boolean addingQuantityStatus; + + private AddingQuantityStatusRequest(boolean addingQuantityStatus) { + this.addingQuantityStatus = addingQuantityStatus; + } + + public static AddingQuantityStatusRequest from(String input) { + CommonValidator.validateNotNull(input); + CommonValidator.validateYesOrNo(input); + boolean status = CommonParser.parseBoolean(input); + + return new AddingQuantityStatusRequest(status); + } + + public boolean isAddingQuantityStatus() { + return addingQuantityStatus; + } +}
Java
공통되는 검증 로직을 util 클래스로 분리해서 활용하는 부분이 인상깊네요!! 💯
@@ -0,0 +1,25 @@ +package store.dto.request.input; + +import store.util.CommonParser; +import store.util.CommonValidator; + +public class AddingQuantityStatusRequest { + + private final boolean addingQuantityStatus; + + private AddingQuantityStatusRequest(boolean addingQuantityStatus) { + this.addingQuantityStatus = addingQuantityStatus; + } + + public static AddingQuantityStatusRequest from(String input) { + CommonValidator.validateNotNull(input); + CommonValidator.validateYesOrNo(input); + boolean status = CommonParser.parseBoolean(input); + + return new AddingQuantityStatusRequest(status); + } + + public boolean isAddingQuantityStatus() { + return addingQuantityStatus; + } +}
Java
addingQuantityStatus가 어떤 용도로 활용되는 것인지 알려주실 수 있을까요!?
@@ -0,0 +1,25 @@ +package store.dto.request.input; + +import store.util.CommonParser; +import store.util.CommonValidator; + +public class AdditionalPurchaseStatusRequest { + + private final boolean additionalPurchaseStatus; + + private AdditionalPurchaseStatusRequest(boolean additionalPurchaseStatus) { + this.additionalPurchaseStatus = additionalPurchaseStatus; + } + + public static AdditionalPurchaseStatusRequest from(String input) { + CommonValidator.validateNotNull(input); + CommonValidator.validateYesOrNo(input); + boolean status = CommonParser.parseBoolean(input); + + return new AdditionalPurchaseStatusRequest(status); + } + + public boolean isAdditionalPurchaseStatus() { + return additionalPurchaseStatus; + } +}
Java
정적 팩토리 메서드를 통해 검증 및 가공 로직을 캡슐화한 게 좋아보이네요! 👍
@@ -0,0 +1,70 @@ +package store.dto.request.input; + +import static store.constant.InputConstant.PRODUCT_SEPARATOR; + +import java.util.ArrayList; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PurchaseProductsRequest { + + private final List<InnerPurchaseProductRequest> purchaseProductsRequests; + + private PurchaseProductsRequest(List<InnerPurchaseProductRequest> purchaseProductsRequests) { + this.purchaseProductsRequests = purchaseProductsRequests; + } + + public static PurchaseProductsRequest from(String input) { + CommonValidator.validateNotNull(input); + + List<InnerPurchaseProductRequest> newPurchaseProductRequests = new ArrayList<>(); + List<String> separatedProducts = CommonParser.separateBySeparator(input, PRODUCT_SEPARATOR.getContent()); + for (String separatedProduct : separatedProducts) { + String replacedProduct = CommonParser.replaceSquareBrackets(separatedProduct); + InnerPurchaseProductRequest newPurchaseProductRequest = InnerPurchaseProductRequest.from(replacedProduct); + newPurchaseProductRequests.add(newPurchaseProductRequest); + } + return new PurchaseProductsRequest(newPurchaseProductRequests); + } + + public List<InnerPurchaseProductRequest> getPurchaseProductsRequests() { + return purchaseProductsRequests; + } + + public static class InnerPurchaseProductRequest { + + private final String productName; + private final Integer productQuantity; + + private InnerPurchaseProductRequest(String productName, Integer productQuantity) { + this.productName = productName; + this.productQuantity = productQuantity; + } + + private static InnerPurchaseProductRequest from(String separatedProduct) { + List<String> productEntry = CommonParser.separateBySeparator(separatedProduct, "-"); + String productName = parseProductName(productEntry); + Integer productQuantity = parseProductQuantity(productEntry); + return new InnerPurchaseProductRequest(productName, productQuantity); + } + + private static String parseProductName(List<String> productEntry) { + return productEntry.getFirst(); + } + + private static Integer parseProductQuantity(List<String> productEntry) { + String productQuantity = productEntry.getLast(); + CommonValidator.validateNumeric(productQuantity); + return CommonParser.convertStringToInteger(productQuantity); + } + + public String getProductName() { + return productName; + } + + public Integer getProductQuantity() { + return productQuantity; + } + } +}
Java
메서드의 큰 틀에서 보면 newPurchaseProductRequests 리스트를 완성하는 것이 책임인 것 같은데 for문 내부 로직을 별도 메서드로 분리한다면`return separatedProducts.stream().` 형태로 리팩토링해볼 수 있을 것 같아요!
@@ -0,0 +1,70 @@ +package store.dto.request.input; + +import static store.constant.InputConstant.PRODUCT_SEPARATOR; + +import java.util.ArrayList; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PurchaseProductsRequest { + + private final List<InnerPurchaseProductRequest> purchaseProductsRequests; + + private PurchaseProductsRequest(List<InnerPurchaseProductRequest> purchaseProductsRequests) { + this.purchaseProductsRequests = purchaseProductsRequests; + } + + public static PurchaseProductsRequest from(String input) { + CommonValidator.validateNotNull(input); + + List<InnerPurchaseProductRequest> newPurchaseProductRequests = new ArrayList<>(); + List<String> separatedProducts = CommonParser.separateBySeparator(input, PRODUCT_SEPARATOR.getContent()); + for (String separatedProduct : separatedProducts) { + String replacedProduct = CommonParser.replaceSquareBrackets(separatedProduct); + InnerPurchaseProductRequest newPurchaseProductRequest = InnerPurchaseProductRequest.from(replacedProduct); + newPurchaseProductRequests.add(newPurchaseProductRequest); + } + return new PurchaseProductsRequest(newPurchaseProductRequests); + } + + public List<InnerPurchaseProductRequest> getPurchaseProductsRequests() { + return purchaseProductsRequests; + } + + public static class InnerPurchaseProductRequest { + + private final String productName; + private final Integer productQuantity; + + private InnerPurchaseProductRequest(String productName, Integer productQuantity) { + this.productName = productName; + this.productQuantity = productQuantity; + } + + private static InnerPurchaseProductRequest from(String separatedProduct) { + List<String> productEntry = CommonParser.separateBySeparator(separatedProduct, "-"); + String productName = parseProductName(productEntry); + Integer productQuantity = parseProductQuantity(productEntry); + return new InnerPurchaseProductRequest(productName, productQuantity); + } + + private static String parseProductName(List<String> productEntry) { + return productEntry.getFirst(); + } + + private static Integer parseProductQuantity(List<String> productEntry) { + String productQuantity = productEntry.getLast(); + CommonValidator.validateNumeric(productQuantity); + return CommonParser.convertStringToInteger(productQuantity); + } + + public String getProductName() { + return productName; + } + + public Integer getProductQuantity() { + return productQuantity; + } + } +}
Java
"-"는 상수화할 수 있을 것 같아요!
@@ -0,0 +1,70 @@ +package store.dto.request.input; + +import static store.constant.InputConstant.PRODUCT_SEPARATOR; + +import java.util.ArrayList; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PurchaseProductsRequest { + + private final List<InnerPurchaseProductRequest> purchaseProductsRequests; + + private PurchaseProductsRequest(List<InnerPurchaseProductRequest> purchaseProductsRequests) { + this.purchaseProductsRequests = purchaseProductsRequests; + } + + public static PurchaseProductsRequest from(String input) { + CommonValidator.validateNotNull(input); + + List<InnerPurchaseProductRequest> newPurchaseProductRequests = new ArrayList<>(); + List<String> separatedProducts = CommonParser.separateBySeparator(input, PRODUCT_SEPARATOR.getContent()); + for (String separatedProduct : separatedProducts) { + String replacedProduct = CommonParser.replaceSquareBrackets(separatedProduct); + InnerPurchaseProductRequest newPurchaseProductRequest = InnerPurchaseProductRequest.from(replacedProduct); + newPurchaseProductRequests.add(newPurchaseProductRequest); + } + return new PurchaseProductsRequest(newPurchaseProductRequests); + } + + public List<InnerPurchaseProductRequest> getPurchaseProductsRequests() { + return purchaseProductsRequests; + } + + public static class InnerPurchaseProductRequest { + + private final String productName; + private final Integer productQuantity; + + private InnerPurchaseProductRequest(String productName, Integer productQuantity) { + this.productName = productName; + this.productQuantity = productQuantity; + } + + private static InnerPurchaseProductRequest from(String separatedProduct) { + List<String> productEntry = CommonParser.separateBySeparator(separatedProduct, "-"); + String productName = parseProductName(productEntry); + Integer productQuantity = parseProductQuantity(productEntry); + return new InnerPurchaseProductRequest(productName, productQuantity); + } + + private static String parseProductName(List<String> productEntry) { + return productEntry.getFirst(); + } + + private static Integer parseProductQuantity(List<String> productEntry) { + String productQuantity = productEntry.getLast(); + CommonValidator.validateNumeric(productQuantity); + return CommonParser.convertStringToInteger(productQuantity); + } + + public String getProductName() { + return productName; + } + + public Integer getProductQuantity() { + return productQuantity; + } + } +}
Java
내부 클래스를 static으로 정의하신 이유가 무엇인가요!?
@@ -0,0 +1,70 @@ +package store.dto.request.input; + +import static store.constant.InputConstant.PRODUCT_SEPARATOR; + +import java.util.ArrayList; +import java.util.List; +import store.util.CommonParser; +import store.util.CommonValidator; + +public class PurchaseProductsRequest { + + private final List<InnerPurchaseProductRequest> purchaseProductsRequests; + + private PurchaseProductsRequest(List<InnerPurchaseProductRequest> purchaseProductsRequests) { + this.purchaseProductsRequests = purchaseProductsRequests; + } + + public static PurchaseProductsRequest from(String input) { + CommonValidator.validateNotNull(input); + + List<InnerPurchaseProductRequest> newPurchaseProductRequests = new ArrayList<>(); + List<String> separatedProducts = CommonParser.separateBySeparator(input, PRODUCT_SEPARATOR.getContent()); + for (String separatedProduct : separatedProducts) { + String replacedProduct = CommonParser.replaceSquareBrackets(separatedProduct); + InnerPurchaseProductRequest newPurchaseProductRequest = InnerPurchaseProductRequest.from(replacedProduct); + newPurchaseProductRequests.add(newPurchaseProductRequest); + } + return new PurchaseProductsRequest(newPurchaseProductRequests); + } + + public List<InnerPurchaseProductRequest> getPurchaseProductsRequests() { + return purchaseProductsRequests; + } + + public static class InnerPurchaseProductRequest { + + private final String productName; + private final Integer productQuantity; + + private InnerPurchaseProductRequest(String productName, Integer productQuantity) { + this.productName = productName; + this.productQuantity = productQuantity; + } + + private static InnerPurchaseProductRequest from(String separatedProduct) { + List<String> productEntry = CommonParser.separateBySeparator(separatedProduct, "-"); + String productName = parseProductName(productEntry); + Integer productQuantity = parseProductQuantity(productEntry); + return new InnerPurchaseProductRequest(productName, productQuantity); + } + + private static String parseProductName(List<String> productEntry) { + return productEntry.getFirst(); + } + + private static Integer parseProductQuantity(List<String> productEntry) { + String productQuantity = productEntry.getLast(); + CommonValidator.validateNumeric(productQuantity); + return CommonParser.convertStringToInteger(productQuantity); + } + + public String getProductName() { + return productName; + } + + public Integer getProductQuantity() { + return productQuantity; + } + } +}
Java
Integer는 null값이 담길 수 있는데 int로 유지하는 것은 어떻게 생각하시나요!?
@@ -0,0 +1,118 @@ +package store.dto.response; + +import java.util.ArrayList; +import java.util.List; +import store.model.domain.Receipt.InnerReceipt; +import store.model.domain.Receipt; + +public class ReceiptResponse { + + private final List<InnerReceiptStockResponse> purchaseStocks; + private final List<InnerReceiptStockResponse> giftStocks; + private final Integer totalPurchaseQuantity; + private final Integer totalPurchaseAmount; + private final Integer promotionDiscount; + private final Integer membershipDiscount; + private final Integer finalAmount; + + private ReceiptResponse(List<InnerReceiptStockResponse> purchaseStocks, + List<InnerReceiptStockResponse> giftStocks, + Integer totalPurchaseQuantity, + Integer totalPurchaseAmount, + Integer promotionDiscount, + Integer membershipDiscount, + Integer finalAmount + ) { + this.purchaseStocks = purchaseStocks; + this.giftStocks = giftStocks; + this.totalPurchaseQuantity = totalPurchaseQuantity; + this.totalPurchaseAmount = totalPurchaseAmount; + this.promotionDiscount = promotionDiscount; + this.membershipDiscount = membershipDiscount; + this.finalAmount = finalAmount; + } + + public static ReceiptResponse from(Receipt receipt) { + List<InnerReceiptStockResponse> purchasedStocks = convertToInnerReceiptStocks(receipt.getPurchasedStocks()); + List<InnerReceiptStockResponse> giftStocks = convertToInnerReceiptStocks(receipt.getGiftStocks()); + + return new ReceiptResponse( + purchasedStocks, + giftStocks, + receipt.calculateTotalPurchaseQuantity(), + receipt.calculateTotalPurchaseAmount(), + receipt.calculatePromotionDiscount(), + receipt.calculateMembershipDiscount(), + receipt.calculateFinalAmount() + ); + } + + private static List<InnerReceiptStockResponse> convertToInnerReceiptStocks(List<InnerReceipt> stocks) { + List<InnerReceiptStockResponse> convertToInnerReceiptStocks = new ArrayList<>(); + for (InnerReceipt stock : stocks) { + convertToInnerReceiptStocks.add(InnerReceiptStockResponse.from(stock)); + } + return convertToInnerReceiptStocks; + } + + public List<InnerReceiptStockResponse> getPurchaseStocks() { + return purchaseStocks; + } + + public List<InnerReceiptStockResponse> getGiftStocks() { + return giftStocks; + } + + public Integer getTotalPurchaseQuantity() { + return totalPurchaseQuantity; + } + + public Integer getTotalPurchaseAmount() { + return totalPurchaseAmount; + } + + public Integer getPromotionDiscount() { + return promotionDiscount; + } + + public Integer getMembershipDiscount() { + return membershipDiscount; + } + + public Integer getFinalAmount() { + return finalAmount; + } + + public static class InnerReceiptStockResponse { + + private final String productName; + private final Integer quantity; + private final Integer totalPrice; + + private InnerReceiptStockResponse(String productName, Integer quantity, Integer totalPrice) { + this.productName = productName; + this.quantity = quantity; + this.totalPrice = totalPrice; + } + + public static InnerReceiptStockResponse from(InnerReceipt stock) { + return new InnerReceiptStockResponse( + stock.getProductName(), + stock.getQuantity(), + stock.getProductPrice() * stock.getQuantity() + ); + } + + public String getProductName() { + return productName; + } + + public Integer getQuantity() { + return quantity; + } + + public Integer getTotalPrice() { + return totalPrice; + } + } +}
Java
완~~전 사소한 내용인데 `(` 열고 개행 한 번 넣어주고 포맷팅하면 조금 더 보기 좋아질 것 같아요! ```suggestion private ReceiptResponse( List<InnerReceiptStockResponse> purchaseStocks, List<InnerReceiptStockResponse> giftStocks, Integer totalPurchaseQuantity, Integer totalPurchaseAmount, Integer promotionDiscount, Integer membershipDiscount, Integer finalAmount ) { ```
@@ -0,0 +1,118 @@ +package store.dto.response; + +import java.util.ArrayList; +import java.util.List; +import store.model.domain.Receipt.InnerReceipt; +import store.model.domain.Receipt; + +public class ReceiptResponse { + + private final List<InnerReceiptStockResponse> purchaseStocks; + private final List<InnerReceiptStockResponse> giftStocks; + private final Integer totalPurchaseQuantity; + private final Integer totalPurchaseAmount; + private final Integer promotionDiscount; + private final Integer membershipDiscount; + private final Integer finalAmount; + + private ReceiptResponse(List<InnerReceiptStockResponse> purchaseStocks, + List<InnerReceiptStockResponse> giftStocks, + Integer totalPurchaseQuantity, + Integer totalPurchaseAmount, + Integer promotionDiscount, + Integer membershipDiscount, + Integer finalAmount + ) { + this.purchaseStocks = purchaseStocks; + this.giftStocks = giftStocks; + this.totalPurchaseQuantity = totalPurchaseQuantity; + this.totalPurchaseAmount = totalPurchaseAmount; + this.promotionDiscount = promotionDiscount; + this.membershipDiscount = membershipDiscount; + this.finalAmount = finalAmount; + } + + public static ReceiptResponse from(Receipt receipt) { + List<InnerReceiptStockResponse> purchasedStocks = convertToInnerReceiptStocks(receipt.getPurchasedStocks()); + List<InnerReceiptStockResponse> giftStocks = convertToInnerReceiptStocks(receipt.getGiftStocks()); + + return new ReceiptResponse( + purchasedStocks, + giftStocks, + receipt.calculateTotalPurchaseQuantity(), + receipt.calculateTotalPurchaseAmount(), + receipt.calculatePromotionDiscount(), + receipt.calculateMembershipDiscount(), + receipt.calculateFinalAmount() + ); + } + + private static List<InnerReceiptStockResponse> convertToInnerReceiptStocks(List<InnerReceipt> stocks) { + List<InnerReceiptStockResponse> convertToInnerReceiptStocks = new ArrayList<>(); + for (InnerReceipt stock : stocks) { + convertToInnerReceiptStocks.add(InnerReceiptStockResponse.from(stock)); + } + return convertToInnerReceiptStocks; + } + + public List<InnerReceiptStockResponse> getPurchaseStocks() { + return purchaseStocks; + } + + public List<InnerReceiptStockResponse> getGiftStocks() { + return giftStocks; + } + + public Integer getTotalPurchaseQuantity() { + return totalPurchaseQuantity; + } + + public Integer getTotalPurchaseAmount() { + return totalPurchaseAmount; + } + + public Integer getPromotionDiscount() { + return promotionDiscount; + } + + public Integer getMembershipDiscount() { + return membershipDiscount; + } + + public Integer getFinalAmount() { + return finalAmount; + } + + public static class InnerReceiptStockResponse { + + private final String productName; + private final Integer quantity; + private final Integer totalPrice; + + private InnerReceiptStockResponse(String productName, Integer quantity, Integer totalPrice) { + this.productName = productName; + this.quantity = quantity; + this.totalPrice = totalPrice; + } + + public static InnerReceiptStockResponse from(InnerReceipt stock) { + return new InnerReceiptStockResponse( + stock.getProductName(), + stock.getQuantity(), + stock.getProductPrice() * stock.getQuantity() + ); + } + + public String getProductName() { + return productName; + } + + public Integer getQuantity() { + return quantity; + } + + public Integer getTotalPrice() { + return totalPrice; + } + } +}
Java
stream을 활용할 수 있을 것 같아요!
@@ -0,0 +1,118 @@ +package store.dto.response; + +import java.util.ArrayList; +import java.util.List; +import store.model.domain.Receipt.InnerReceipt; +import store.model.domain.Receipt; + +public class ReceiptResponse { + + private final List<InnerReceiptStockResponse> purchaseStocks; + private final List<InnerReceiptStockResponse> giftStocks; + private final Integer totalPurchaseQuantity; + private final Integer totalPurchaseAmount; + private final Integer promotionDiscount; + private final Integer membershipDiscount; + private final Integer finalAmount; + + private ReceiptResponse(List<InnerReceiptStockResponse> purchaseStocks, + List<InnerReceiptStockResponse> giftStocks, + Integer totalPurchaseQuantity, + Integer totalPurchaseAmount, + Integer promotionDiscount, + Integer membershipDiscount, + Integer finalAmount + ) { + this.purchaseStocks = purchaseStocks; + this.giftStocks = giftStocks; + this.totalPurchaseQuantity = totalPurchaseQuantity; + this.totalPurchaseAmount = totalPurchaseAmount; + this.promotionDiscount = promotionDiscount; + this.membershipDiscount = membershipDiscount; + this.finalAmount = finalAmount; + } + + public static ReceiptResponse from(Receipt receipt) { + List<InnerReceiptStockResponse> purchasedStocks = convertToInnerReceiptStocks(receipt.getPurchasedStocks()); + List<InnerReceiptStockResponse> giftStocks = convertToInnerReceiptStocks(receipt.getGiftStocks()); + + return new ReceiptResponse( + purchasedStocks, + giftStocks, + receipt.calculateTotalPurchaseQuantity(), + receipt.calculateTotalPurchaseAmount(), + receipt.calculatePromotionDiscount(), + receipt.calculateMembershipDiscount(), + receipt.calculateFinalAmount() + ); + } + + private static List<InnerReceiptStockResponse> convertToInnerReceiptStocks(List<InnerReceipt> stocks) { + List<InnerReceiptStockResponse> convertToInnerReceiptStocks = new ArrayList<>(); + for (InnerReceipt stock : stocks) { + convertToInnerReceiptStocks.add(InnerReceiptStockResponse.from(stock)); + } + return convertToInnerReceiptStocks; + } + + public List<InnerReceiptStockResponse> getPurchaseStocks() { + return purchaseStocks; + } + + public List<InnerReceiptStockResponse> getGiftStocks() { + return giftStocks; + } + + public Integer getTotalPurchaseQuantity() { + return totalPurchaseQuantity; + } + + public Integer getTotalPurchaseAmount() { + return totalPurchaseAmount; + } + + public Integer getPromotionDiscount() { + return promotionDiscount; + } + + public Integer getMembershipDiscount() { + return membershipDiscount; + } + + public Integer getFinalAmount() { + return finalAmount; + } + + public static class InnerReceiptStockResponse { + + private final String productName; + private final Integer quantity; + private final Integer totalPrice; + + private InnerReceiptStockResponse(String productName, Integer quantity, Integer totalPrice) { + this.productName = productName; + this.quantity = quantity; + this.totalPrice = totalPrice; + } + + public static InnerReceiptStockResponse from(InnerReceipt stock) { + return new InnerReceiptStockResponse( + stock.getProductName(), + stock.getQuantity(), + stock.getProductPrice() * stock.getQuantity() + ); + } + + public String getProductName() { + return productName; + } + + public Integer getQuantity() { + return quantity; + } + + public Integer getTotalPrice() { + return totalPrice; + } + } +}
Java
record를 활용한다면 이런 getter들은 생략할 수 있을 것 같아요!
@@ -0,0 +1,83 @@ +package store.dto.response; + +import static store.constant.ConvenienceConstant.*; +import static store.constant.message.OutputMessage.*; + +import java.util.ArrayList; +import java.util.List; +import store.model.domain.Stock; + +public class StocksResponse { + + private final List<InnerStockResponse> stocksResponse; + + private StocksResponse(List<InnerStockResponse> stocksResponse) { + this.stocksResponse = stocksResponse; + } + + public static StocksResponse from(List<Stock> stocks) { + List<InnerStockResponse> newStocksResponse = new ArrayList<>(); + + for (Stock stock : stocks) { + newStocksResponse.add(InnerStockResponse.from(stock)); + } + return new StocksResponse(newStocksResponse); + } + + public List<InnerStockResponse> getStocksResponse() { + return stocksResponse; + } + + public static class InnerStockResponse { + + private final String name; + private final Integer price; + private final String promotionName; + private final String quantity; + + private InnerStockResponse(String name, Integer price, String promotionName, String quantity) { + this.name = name; + this.price = price; + this.promotionName = promotionName; + this.quantity = quantity; + } + + private static InnerStockResponse from(Stock stock) { + return new InnerStockResponse( + stock.getProductName(), + stock.getProductPrice(), + formatPromotionName(stock.getPromotionName()), + formatQuantity(stock.getQuantity())); + } + + private static String formatPromotionName(String promotionName) { + if (promotionName.equals(NO_PROMOTION)) { + return EMPTY_STRING; + } + return promotionName; + } + + private static String formatQuantity(Integer quantity) { + if (quantity <= 0) { + return NOT_IN_STOCK; + } + return String.format(STOCKS_COUNT.getMessage(), quantity); + } + + public String getName() { + return name; + } + + public Integer getPrice() { + return price; + } + + public String getPromotionName() { + return promotionName; + } + + public String getQuantity() { + return quantity; + } + } +} \ No newline at end of file
Java
stream을 사용할 수 있을 것 같아요!
@@ -1,7 +1,43 @@ package store; +import static store.enums.ErrorMessage.INVALID_INPUT; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import store.config.StoreConfig; +import store.controller.PurchaseController; +import store.controller.StoreController; + public class Application { + + private static final StoreController storeController = StoreConfig.getStoreController(); + private static final PurchaseController purchaseController = StoreConfig.getPurchaseController(); + public static void main(String[] args) { - // TODO: 프로그램 구현 + init(); + try { + execute(); + } finally { + Console.close(); + storeController.clearFile(); + } + } + + private static void execute() { + boolean isRetry = true; + while (isRetry) { + storeController.explain(); + purchaseController.purchase(); + storeController.clearOrder(); + isRetry = purchaseController.retry(); + } + } + + private static void init() { + try { + storeController.init(); + } catch (IOException e) { + throw new IllegalArgumentException(INVALID_INPUT.getMessage()); + } } }
Java
do-while 활용해도 좋았을 것 같습니다!
@@ -0,0 +1,145 @@ +package store.domain; + +import static store.enums.ErrorMessage.EXCEED_PURCHASE; +import static store.enums.ErrorMessage.INVALID_FILE_FORMAT; +import static store.utils.Constants.ENTER; +import static store.utils.Constants.SPACE_BAR; + +import java.util.Objects; +import java.util.StringJoiner; +import store.domain.vo.ProductName; +import store.exception.InvalidFileFormatException; +import store.utils.StringUtils; + +public class Product { + + private static final String CURRENCY_UNIT = "원"; + private static final String DIVIDER = "-"; + + private final ProductName name; + private final long price; + private final Stock stock; + private Promotion promotion; + + public Product(ProductName name, long price, Promotion promotion) { + this.name = name; + this.price = price; + this.stock = new Stock(); + updatePromotion(promotion); + } + + public Product(ProductName name, long price, Stock stock, Promotion promotion) { + this.name = name; + this.price = price; + this.stock = stock; + this.promotion = promotion; + } + + public void validStock(long requestCount) { + if (stock.total() < requestCount) { + throw new IllegalArgumentException(EXCEED_PURCHASE.getMessage()); + } + } + + public void updatePromotion(Promotion promotion) { + if (this.promotion != null && !this.promotion.equals(promotion)) { + throw new InvalidFileFormatException(INVALID_FILE_FORMAT.getMessage()); + } + + this.promotion = promotion; + } + + public void validPrice(long dtoPrice) { + if (price != dtoPrice) { + throw new InvalidFileFormatException(INVALID_FILE_FORMAT.getMessage()); + } + } + + public void addNormalQuantity(long quantity) { + stock.addNormalProduct(quantity); + } + + public void addPromotionQuantity(long quantity) { + stock.addPromotionProduct(quantity); + } + + public long calculateRequiredQuantity(long requestQuantity) { + return stock.problemQuantity(requestQuantity, promotion); + } + + public long sumOriginalPrice(long requestQuantity) { + long originalQuantity = stock.calculateOriginalPriceQuantity(requestQuantity, promotion); + + return -originalQuantity * price; + } + + public long calculateGiftQuantity(long requestQuantity) { + return stock.calculateGiftQuantity(requestQuantity, promotion); + } + + public long calculateSumPrice(long quantity) { + return quantity * price; + } + + public void applyStock(long requestQuantity) { + stock.applyQuantity(requestQuantity); + } + + @Override + public String toString() { + StringJoiner enterJoiner = new StringJoiner(ENTER); + + if (promotion != null) { + enterJoiner.add(promotionStatus()); + } + + return enterJoiner.add(normalStatus()) + .toString(); + } + + private String promotionStatus() { + StringJoiner spaceBarJoiner = new StringJoiner(SPACE_BAR); + return spaceBarJoiner.add(DIVIDER) + .add(name.value()) + .add(toFormatPrice()) + .add(stock.toPromotionCountString()) + .add(promotion.toString()) + .toString(); + } + + private String normalStatus() { + StringJoiner spaceBarJoiner = new StringJoiner(SPACE_BAR); + return spaceBarJoiner.add(DIVIDER) + .add(name.value()) + .add(toFormatPrice()) + .add(stock.toNormalCountString()) + .toString(); + } + + private String toFormatPrice() { + return StringUtils.numberFormat(price) + CURRENCY_UNIT; + } + + protected String toProductName() { + return name.value(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Product product = (Product) o; + return price == product.price && Objects.equals(name, product.name) && Objects.equals(stock, + product.stock) && Objects.equals(promotion, product.promotion); + } + + @Override + public int hashCode() { + return Objects.hash(name, price, stock, promotion); + } + +}
Java
equals가 promotion의 모든 필드를 참고하여 비교하게 되어있는데, 그러면 `!this.promotion.equals(promotion)`에 의해 현재 갖고 있는 프로모션이 동일해야 업데이트하게 되는 건가요??
@@ -0,0 +1,87 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_FILE_FORMAT; +import static store.enums.ErrorMessage.INVALID_INPUT; + +import java.time.LocalDate; +import java.util.Objects; +import store.domain.vo.PromotionDate; +import store.exception.InvalidFileFormatException; +import store.utils.StringUtils; + +public class Promotion { + + private static final String NULL_NAME = "null"; + private static final long GET_PROMOTION_QUANTITY = 1; + + private final String name; + private final PromotionDate promotionDate; + private final long buyPromotionQuantity; + + protected Promotion(String name, long buyQuantity, LocalDate startDate, LocalDate endDate) { + this.name = name; + this.promotionDate = new PromotionDate(startDate, endDate); + this.buyPromotionQuantity = buyQuantity; + } + + public static Promotion create(String name, long buyQuantity, LocalDate startDate, LocalDate endDate) { + StringUtils.validName(name); + validPromotionName(name); + validPromotionQuantity(buyQuantity); + return new Promotion(name, buyQuantity, startDate, endDate); + } + + private static void validPromotionQuantity(Long buyQuantity) { + if (buyQuantity <= 0) { + throw new InvalidFileFormatException(INVALID_FILE_FORMAT.getMessage()); + } + } + + private static void validPromotionName(String name) { + if (name.equalsIgnoreCase(NULL_NAME)) { + throw new InvalidFileFormatException(INVALID_INPUT.getMessage()); + } + } + + public boolean isValidPromotion(LocalDate currentDate) { + return promotionDate.isAvailable(currentDate); + } + + protected long bundleSize() { + return GET_PROMOTION_QUANTITY + buyPromotionQuantity; + } + + protected long totalGetQuantity(long promotionBundleCount) { + return promotionBundleCount * GET_PROMOTION_QUANTITY; + } + + protected long getPromotionGiftQuantity(long requestQuantity) { + if ((requestQuantity + GET_PROMOTION_QUANTITY) % bundleSize() == 0) { + return GET_PROMOTION_QUANTITY; + } + return 0L; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Promotion promotion = (Promotion) o; + return buyPromotionQuantity == promotion.buyPromotionQuantity && Objects.equals(name, promotion.name) + && Objects.equals(promotionDate, promotion.promotionDate); + } + + @Override + public int hashCode() { + return Objects.hash(name, promotionDate, buyPromotionQuantity); + } + + @Override + public String toString() { + return name; + } +}
Java
private이 아니라, protected인 이유가 궁금해요! 아래 정적팩터리메서드만 사용해도 될 것 같아보여서요!
@@ -0,0 +1,150 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_PURCHASE; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import store.domain.vo.ProductName; +import store.dto.OrderConfirmDto; + +public class OrderInfo { + + private static final String OPEN_BRACKET = "["; + private static final String CLOSE_BRACKET = "]"; + private static final String SEPARATOR = "-"; + + private static final int MIN_LENGTH = 5; + private static final int BRACKET_OFFSET = 1; + private static final int NAME_IDX = 0; + private static final int QUANTITY_IDX = 1; + private static final int SPLIT_LENGTH = 2; + private static final int ZERO = 0; + + private final ProductName productName; + private final long requestQuantity; + + public OrderInfo(ProductName productName, long requestQuantity) { + this.productName = productName; + this.requestQuantity = requestQuantity; + } + + public static OrderInfo of(ProductName productName, long requestQuantity) { + return new OrderInfo(productName, requestQuantity); + } + + public static OrderInfo create(String input) { + validInput(input); + String[] parsedInput = parseNameAndQuantity(input); + return new OrderInfo(ProductName.create(parsedInput[NAME_IDX]), parseQuantity(parsedInput[QUANTITY_IDX])); + } + + protected static Map<ProductName, Long> sumQuantityByProduct(List<OrderInfo> orderInfos) { + Map<ProductName, Long> purchaseCountMap = new LinkedHashMap<>(); + + orderInfos.forEach( + orderInfo -> purchaseCountMap.merge(orderInfo.productName, orderInfo.requestQuantity, + Long::sum)); + + return purchaseCountMap; + } + + private static void validInput(String input) { + if (input == null || input.isBlank() || input.length() < MIN_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + boolean startsWith = input.startsWith(OPEN_BRACKET); + boolean endsWith = input.endsWith(CLOSE_BRACKET); + if ((!startsWith || !endsWith) && input.contains(SEPARATOR)) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String[] parseNameAndQuantity(String input) { + String trimInput = trimBrackets(input); + validTrimInput(trimInput); + String[] splitInput = trimInput.split(SEPARATOR); + validSplitInput(splitInput); + + return splitInput; + } + + private static void validTrimInput(String trimInput) { + boolean startsWith = trimInput.startsWith(SEPARATOR); + boolean endsWith = trimInput.endsWith(SEPARATOR); + + if (startsWith || endsWith) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String trimBrackets(String input) { + int endIdx = input.length() - BRACKET_OFFSET; + + return input.substring(BRACKET_OFFSET, endIdx); + } + + private static long parseQuantity(String number) { + try { + long parseNumber = Long.parseLong(number); + validQuantity(parseNumber); + return parseNumber; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validQuantity(long number) { + if (number <= ZERO) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validSplitInput(String[] splitInput) { + if (splitInput.length != SPLIT_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + if (splitInput[NAME_IDX].isBlank() || splitInput[QUANTITY_IDX].isBlank()) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + public OrderConfirmDto toConfirmDto(Product product) { + long requireQuantity = product.calculateRequiredQuantity(requestQuantity); + + return OrderConfirmDto.create(productName, requestQuantity, requireQuantity); + } + + public void validQuantity(Product product) { + product.validStock(requestQuantity); + } + + public String toOriginalInput() { + return OPEN_BRACKET + productName + SEPARATOR + requestQuantity + CLOSE_BRACKET; + } + + public ProductName getProductName() { + return productName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderInfo that = (OrderInfo) o; + return Objects.equals(productName, that.productName) && Objects.equals(requestQuantity, + that.requestQuantity); + } + + @Override + public int hashCode() { + return Objects.hash(productName, requestQuantity); + } +}
Java
도메인이 view로직을 너무 포함하고 있는 것이 아닐까? 라는 고민이 있어요. 애매한 부분이라 어떻게 생각하시는지 궁금합니다!
@@ -0,0 +1,145 @@ +package store.domain; + +import static store.enums.ErrorMessage.EXCEED_PURCHASE; +import static store.enums.ErrorMessage.INVALID_FILE_FORMAT; +import static store.utils.Constants.ENTER; +import static store.utils.Constants.SPACE_BAR; + +import java.util.Objects; +import java.util.StringJoiner; +import store.domain.vo.ProductName; +import store.exception.InvalidFileFormatException; +import store.utils.StringUtils; + +public class Product { + + private static final String CURRENCY_UNIT = "원"; + private static final String DIVIDER = "-"; + + private final ProductName name; + private final long price; + private final Stock stock; + private Promotion promotion; + + public Product(ProductName name, long price, Promotion promotion) { + this.name = name; + this.price = price; + this.stock = new Stock(); + updatePromotion(promotion); + } + + public Product(ProductName name, long price, Stock stock, Promotion promotion) { + this.name = name; + this.price = price; + this.stock = stock; + this.promotion = promotion; + } + + public void validStock(long requestCount) { + if (stock.total() < requestCount) { + throw new IllegalArgumentException(EXCEED_PURCHASE.getMessage()); + } + } + + public void updatePromotion(Promotion promotion) { + if (this.promotion != null && !this.promotion.equals(promotion)) { + throw new InvalidFileFormatException(INVALID_FILE_FORMAT.getMessage()); + } + + this.promotion = promotion; + } + + public void validPrice(long dtoPrice) { + if (price != dtoPrice) { + throw new InvalidFileFormatException(INVALID_FILE_FORMAT.getMessage()); + } + } + + public void addNormalQuantity(long quantity) { + stock.addNormalProduct(quantity); + } + + public void addPromotionQuantity(long quantity) { + stock.addPromotionProduct(quantity); + } + + public long calculateRequiredQuantity(long requestQuantity) { + return stock.problemQuantity(requestQuantity, promotion); + } + + public long sumOriginalPrice(long requestQuantity) { + long originalQuantity = stock.calculateOriginalPriceQuantity(requestQuantity, promotion); + + return -originalQuantity * price; + } + + public long calculateGiftQuantity(long requestQuantity) { + return stock.calculateGiftQuantity(requestQuantity, promotion); + } + + public long calculateSumPrice(long quantity) { + return quantity * price; + } + + public void applyStock(long requestQuantity) { + stock.applyQuantity(requestQuantity); + } + + @Override + public String toString() { + StringJoiner enterJoiner = new StringJoiner(ENTER); + + if (promotion != null) { + enterJoiner.add(promotionStatus()); + } + + return enterJoiner.add(normalStatus()) + .toString(); + } + + private String promotionStatus() { + StringJoiner spaceBarJoiner = new StringJoiner(SPACE_BAR); + return spaceBarJoiner.add(DIVIDER) + .add(name.value()) + .add(toFormatPrice()) + .add(stock.toPromotionCountString()) + .add(promotion.toString()) + .toString(); + } + + private String normalStatus() { + StringJoiner spaceBarJoiner = new StringJoiner(SPACE_BAR); + return spaceBarJoiner.add(DIVIDER) + .add(name.value()) + .add(toFormatPrice()) + .add(stock.toNormalCountString()) + .toString(); + } + + private String toFormatPrice() { + return StringUtils.numberFormat(price) + CURRENCY_UNIT; + } + + protected String toProductName() { + return name.value(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Product product = (Product) o; + return price == product.price && Objects.equals(name, product.name) && Objects.equals(stock, + product.stock) && Objects.equals(promotion, product.promotion); + } + + @Override + public int hashCode() { + return Objects.hash(name, price, stock, promotion); + } + +}
Java
해당 update은 상태가 null일때만 새로운 업데이트가 가능하도록 하였습니다. 만약 제품이 두개가 이름과 가격이 중복인데 참조하는 프로모션이 다르다면 파일의 문제이므로 예외처리 하였습니다.
@@ -0,0 +1,150 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_PURCHASE; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import store.domain.vo.ProductName; +import store.dto.OrderConfirmDto; + +public class OrderInfo { + + private static final String OPEN_BRACKET = "["; + private static final String CLOSE_BRACKET = "]"; + private static final String SEPARATOR = "-"; + + private static final int MIN_LENGTH = 5; + private static final int BRACKET_OFFSET = 1; + private static final int NAME_IDX = 0; + private static final int QUANTITY_IDX = 1; + private static final int SPLIT_LENGTH = 2; + private static final int ZERO = 0; + + private final ProductName productName; + private final long requestQuantity; + + public OrderInfo(ProductName productName, long requestQuantity) { + this.productName = productName; + this.requestQuantity = requestQuantity; + } + + public static OrderInfo of(ProductName productName, long requestQuantity) { + return new OrderInfo(productName, requestQuantity); + } + + public static OrderInfo create(String input) { + validInput(input); + String[] parsedInput = parseNameAndQuantity(input); + return new OrderInfo(ProductName.create(parsedInput[NAME_IDX]), parseQuantity(parsedInput[QUANTITY_IDX])); + } + + protected static Map<ProductName, Long> sumQuantityByProduct(List<OrderInfo> orderInfos) { + Map<ProductName, Long> purchaseCountMap = new LinkedHashMap<>(); + + orderInfos.forEach( + orderInfo -> purchaseCountMap.merge(orderInfo.productName, orderInfo.requestQuantity, + Long::sum)); + + return purchaseCountMap; + } + + private static void validInput(String input) { + if (input == null || input.isBlank() || input.length() < MIN_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + boolean startsWith = input.startsWith(OPEN_BRACKET); + boolean endsWith = input.endsWith(CLOSE_BRACKET); + if ((!startsWith || !endsWith) && input.contains(SEPARATOR)) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String[] parseNameAndQuantity(String input) { + String trimInput = trimBrackets(input); + validTrimInput(trimInput); + String[] splitInput = trimInput.split(SEPARATOR); + validSplitInput(splitInput); + + return splitInput; + } + + private static void validTrimInput(String trimInput) { + boolean startsWith = trimInput.startsWith(SEPARATOR); + boolean endsWith = trimInput.endsWith(SEPARATOR); + + if (startsWith || endsWith) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String trimBrackets(String input) { + int endIdx = input.length() - BRACKET_OFFSET; + + return input.substring(BRACKET_OFFSET, endIdx); + } + + private static long parseQuantity(String number) { + try { + long parseNumber = Long.parseLong(number); + validQuantity(parseNumber); + return parseNumber; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validQuantity(long number) { + if (number <= ZERO) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validSplitInput(String[] splitInput) { + if (splitInput.length != SPLIT_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + if (splitInput[NAME_IDX].isBlank() || splitInput[QUANTITY_IDX].isBlank()) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + public OrderConfirmDto toConfirmDto(Product product) { + long requireQuantity = product.calculateRequiredQuantity(requestQuantity); + + return OrderConfirmDto.create(productName, requestQuantity, requireQuantity); + } + + public void validQuantity(Product product) { + product.validStock(requestQuantity); + } + + public String toOriginalInput() { + return OPEN_BRACKET + productName + SEPARATOR + requestQuantity + CLOSE_BRACKET; + } + + public ProductName getProductName() { + return productName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderInfo that = (OrderInfo) o; + return Objects.equals(productName, that.productName) && Objects.equals(requestQuantity, + that.requestQuantity); + } + + @Override + public int hashCode() { + return Objects.hash(productName, requestQuantity); + } +}
Java
저는 view를 단순하게 시스템의 출력으로 두고 생각하고 String의 경우 객체가 스스로 처리해야한다는 관점이기에 다음과 같이 구현하였습니다. getter를 사용하지 않는다면 이러한 방법이 최선이라고 봅니다만 다른 방법이 있을까요?
@@ -0,0 +1,87 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_FILE_FORMAT; +import static store.enums.ErrorMessage.INVALID_INPUT; + +import java.time.LocalDate; +import java.util.Objects; +import store.domain.vo.PromotionDate; +import store.exception.InvalidFileFormatException; +import store.utils.StringUtils; + +public class Promotion { + + private static final String NULL_NAME = "null"; + private static final long GET_PROMOTION_QUANTITY = 1; + + private final String name; + private final PromotionDate promotionDate; + private final long buyPromotionQuantity; + + protected Promotion(String name, long buyQuantity, LocalDate startDate, LocalDate endDate) { + this.name = name; + this.promotionDate = new PromotionDate(startDate, endDate); + this.buyPromotionQuantity = buyQuantity; + } + + public static Promotion create(String name, long buyQuantity, LocalDate startDate, LocalDate endDate) { + StringUtils.validName(name); + validPromotionName(name); + validPromotionQuantity(buyQuantity); + return new Promotion(name, buyQuantity, startDate, endDate); + } + + private static void validPromotionQuantity(Long buyQuantity) { + if (buyQuantity <= 0) { + throw new InvalidFileFormatException(INVALID_FILE_FORMAT.getMessage()); + } + } + + private static void validPromotionName(String name) { + if (name.equalsIgnoreCase(NULL_NAME)) { + throw new InvalidFileFormatException(INVALID_INPUT.getMessage()); + } + } + + public boolean isValidPromotion(LocalDate currentDate) { + return promotionDate.isAvailable(currentDate); + } + + protected long bundleSize() { + return GET_PROMOTION_QUANTITY + buyPromotionQuantity; + } + + protected long totalGetQuantity(long promotionBundleCount) { + return promotionBundleCount * GET_PROMOTION_QUANTITY; + } + + protected long getPromotionGiftQuantity(long requestQuantity) { + if ((requestQuantity + GET_PROMOTION_QUANTITY) % bundleSize() == 0) { + return GET_PROMOTION_QUANTITY; + } + return 0L; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Promotion promotion = (Promotion) o; + return buyPromotionQuantity == promotion.buyPromotionQuantity && Objects.equals(name, promotion.name) + && Objects.equals(promotionDate, promotion.promotionDate); + } + + @Override + public int hashCode() { + return Objects.hash(name, promotionDate, buyPromotionQuantity); + } + + @Override + public String toString() { + return name; + } +}
Java
제가 주로 프로텍트를 사용하는 이유는 단위 테스트나 계층 내부에서만 사용할 수 있도록 하는게 목적이긴해요. 다만, 패키지 프라이빗을 쓰는게 더 올라는게 맞다고 생각하긴하네요!
@@ -0,0 +1,150 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_PURCHASE; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import store.domain.vo.ProductName; +import store.dto.OrderConfirmDto; + +public class OrderInfo { + + private static final String OPEN_BRACKET = "["; + private static final String CLOSE_BRACKET = "]"; + private static final String SEPARATOR = "-"; + + private static final int MIN_LENGTH = 5; + private static final int BRACKET_OFFSET = 1; + private static final int NAME_IDX = 0; + private static final int QUANTITY_IDX = 1; + private static final int SPLIT_LENGTH = 2; + private static final int ZERO = 0; + + private final ProductName productName; + private final long requestQuantity; + + public OrderInfo(ProductName productName, long requestQuantity) { + this.productName = productName; + this.requestQuantity = requestQuantity; + } + + public static OrderInfo of(ProductName productName, long requestQuantity) { + return new OrderInfo(productName, requestQuantity); + } + + public static OrderInfo create(String input) { + validInput(input); + String[] parsedInput = parseNameAndQuantity(input); + return new OrderInfo(ProductName.create(parsedInput[NAME_IDX]), parseQuantity(parsedInput[QUANTITY_IDX])); + } + + protected static Map<ProductName, Long> sumQuantityByProduct(List<OrderInfo> orderInfos) { + Map<ProductName, Long> purchaseCountMap = new LinkedHashMap<>(); + + orderInfos.forEach( + orderInfo -> purchaseCountMap.merge(orderInfo.productName, orderInfo.requestQuantity, + Long::sum)); + + return purchaseCountMap; + } + + private static void validInput(String input) { + if (input == null || input.isBlank() || input.length() < MIN_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + boolean startsWith = input.startsWith(OPEN_BRACKET); + boolean endsWith = input.endsWith(CLOSE_BRACKET); + if ((!startsWith || !endsWith) && input.contains(SEPARATOR)) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String[] parseNameAndQuantity(String input) { + String trimInput = trimBrackets(input); + validTrimInput(trimInput); + String[] splitInput = trimInput.split(SEPARATOR); + validSplitInput(splitInput); + + return splitInput; + } + + private static void validTrimInput(String trimInput) { + boolean startsWith = trimInput.startsWith(SEPARATOR); + boolean endsWith = trimInput.endsWith(SEPARATOR); + + if (startsWith || endsWith) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String trimBrackets(String input) { + int endIdx = input.length() - BRACKET_OFFSET; + + return input.substring(BRACKET_OFFSET, endIdx); + } + + private static long parseQuantity(String number) { + try { + long parseNumber = Long.parseLong(number); + validQuantity(parseNumber); + return parseNumber; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validQuantity(long number) { + if (number <= ZERO) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validSplitInput(String[] splitInput) { + if (splitInput.length != SPLIT_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + if (splitInput[NAME_IDX].isBlank() || splitInput[QUANTITY_IDX].isBlank()) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + public OrderConfirmDto toConfirmDto(Product product) { + long requireQuantity = product.calculateRequiredQuantity(requestQuantity); + + return OrderConfirmDto.create(productName, requestQuantity, requireQuantity); + } + + public void validQuantity(Product product) { + product.validStock(requestQuantity); + } + + public String toOriginalInput() { + return OPEN_BRACKET + productName + SEPARATOR + requestQuantity + CLOSE_BRACKET; + } + + public ProductName getProductName() { + return productName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderInfo that = (OrderInfo) o; + return Objects.equals(productName, that.productName) && Objects.equals(requestQuantity, + that.requestQuantity); + } + + @Override + public int hashCode() { + return Objects.hash(productName, requestQuantity); + } +}
Java
저는 도메인 객체는 비즈니스로직을 담당하여야 한다고 생각하는데 포매터 클래스를 만들어서 유틸로 분리하는건 어떨까요?
@@ -0,0 +1,150 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_PURCHASE; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import store.domain.vo.ProductName; +import store.dto.OrderConfirmDto; + +public class OrderInfo { + + private static final String OPEN_BRACKET = "["; + private static final String CLOSE_BRACKET = "]"; + private static final String SEPARATOR = "-"; + + private static final int MIN_LENGTH = 5; + private static final int BRACKET_OFFSET = 1; + private static final int NAME_IDX = 0; + private static final int QUANTITY_IDX = 1; + private static final int SPLIT_LENGTH = 2; + private static final int ZERO = 0; + + private final ProductName productName; + private final long requestQuantity; + + public OrderInfo(ProductName productName, long requestQuantity) { + this.productName = productName; + this.requestQuantity = requestQuantity; + } + + public static OrderInfo of(ProductName productName, long requestQuantity) { + return new OrderInfo(productName, requestQuantity); + } + + public static OrderInfo create(String input) { + validInput(input); + String[] parsedInput = parseNameAndQuantity(input); + return new OrderInfo(ProductName.create(parsedInput[NAME_IDX]), parseQuantity(parsedInput[QUANTITY_IDX])); + } + + protected static Map<ProductName, Long> sumQuantityByProduct(List<OrderInfo> orderInfos) { + Map<ProductName, Long> purchaseCountMap = new LinkedHashMap<>(); + + orderInfos.forEach( + orderInfo -> purchaseCountMap.merge(orderInfo.productName, orderInfo.requestQuantity, + Long::sum)); + + return purchaseCountMap; + } + + private static void validInput(String input) { + if (input == null || input.isBlank() || input.length() < MIN_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + boolean startsWith = input.startsWith(OPEN_BRACKET); + boolean endsWith = input.endsWith(CLOSE_BRACKET); + if ((!startsWith || !endsWith) && input.contains(SEPARATOR)) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String[] parseNameAndQuantity(String input) { + String trimInput = trimBrackets(input); + validTrimInput(trimInput); + String[] splitInput = trimInput.split(SEPARATOR); + validSplitInput(splitInput); + + return splitInput; + } + + private static void validTrimInput(String trimInput) { + boolean startsWith = trimInput.startsWith(SEPARATOR); + boolean endsWith = trimInput.endsWith(SEPARATOR); + + if (startsWith || endsWith) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String trimBrackets(String input) { + int endIdx = input.length() - BRACKET_OFFSET; + + return input.substring(BRACKET_OFFSET, endIdx); + } + + private static long parseQuantity(String number) { + try { + long parseNumber = Long.parseLong(number); + validQuantity(parseNumber); + return parseNumber; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validQuantity(long number) { + if (number <= ZERO) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validSplitInput(String[] splitInput) { + if (splitInput.length != SPLIT_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + if (splitInput[NAME_IDX].isBlank() || splitInput[QUANTITY_IDX].isBlank()) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + public OrderConfirmDto toConfirmDto(Product product) { + long requireQuantity = product.calculateRequiredQuantity(requestQuantity); + + return OrderConfirmDto.create(productName, requestQuantity, requireQuantity); + } + + public void validQuantity(Product product) { + product.validStock(requestQuantity); + } + + public String toOriginalInput() { + return OPEN_BRACKET + productName + SEPARATOR + requestQuantity + CLOSE_BRACKET; + } + + public ProductName getProductName() { + return productName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderInfo that = (OrderInfo) o; + return Objects.equals(productName, that.productName) && Objects.equals(requestQuantity, + that.requestQuantity); + } + + @Override + public int hashCode() { + return Objects.hash(productName, requestQuantity); + } +}
Java
입력검증 부분은 따로 분리하여 하는게 좋지 않을까요? 도메인 검증과 입렵검증을 나눠서 해야한다고 생각합니다
@@ -0,0 +1,80 @@ +package store.controller; + +import static store.enums.PromptMessage.BUY; +import static store.enums.PromptMessage.MEMBERSHIP_DISCOUNT; +import static store.enums.PromptMessage.RETRY_PURCHASE; + +import store.dto.Message; +import store.dto.OrderConfirmDto; +import store.dto.OrderConfirmDtos; +import store.enums.Confirmation; +import store.service.PurchaseService; +import store.utils.RecoveryUtils; +import store.viewer.InputViewer; +import store.viewer.OutputViewer; + +public class PurchaseController { + + private final PurchaseService purchaseService; + private final InputViewer inputViewer; + private final OutputViewer outputViewer; + + public PurchaseController(PurchaseService purchaseService, InputViewer inputViewer, OutputViewer outputViewer) { + this.purchaseService = purchaseService; + this.inputViewer = inputViewer; + this.outputViewer = outputViewer; + } + + public void purchase() { + buy(); + check(); + printReceipt(); + } + + protected void buy() { + inputViewer.promptMessage(BUY); + RecoveryUtils.executeWithRetry(inputViewer::getInput, purchaseService::createOrderInfos); + } + + protected void check() { + OrderConfirmDtos confirmDtos = purchaseService.check(); + for (OrderConfirmDto confirmDto : confirmDtos.items()) { + if (confirmDto.problemQuantity() == 0) { + purchaseService.processQuantity(confirmDto); + continue; + } + confirmProblemQuantity(confirmDto); + } + } + + protected void printReceipt() { + inputViewer.promptMessage(MEMBERSHIP_DISCOUNT); + + Message receiptDto = RecoveryUtils.executeWithRetry(() -> Confirmation.from(inputViewer.getInput()), + purchaseService::getReceipt); + + outputViewer.printResult(receiptDto); + } + + public boolean retry() { + inputViewer.promptMessage(RETRY_PURCHASE); + Confirmation confirmation = RecoveryUtils.executeWithRetry(() -> Confirmation.from(inputViewer.getInput())); + return confirmation.isBool(); + } + + private void printProblemQuantity(OrderConfirmDto confirmDto) { + if (confirmDto.problemQuantity() < 0) { + inputViewer.promptNonDiscount(confirmDto.name(), -confirmDto.problemQuantity()); + } + + if (confirmDto.problemQuantity() > 0) { + inputViewer.promptFreeItem(confirmDto.name(), confirmDto.problemQuantity()); + } + } + + private void confirmProblemQuantity(OrderConfirmDto confirmDto) { + printProblemQuantity(confirmDto); + Confirmation confirmation = RecoveryUtils.executeWithRetry(() -> Confirmation.from(inputViewer.getInput())); + purchaseService.processProblemQuantity(confirmDto, confirmation); + } +}
Java
컨트롤러는 사용자 인터페이스와 서비스 계층간의 다리 역할을 담당 하고있어야 하는데 check()는 검증 부분이라 서비스로 분리 해야하지 않을까요?
@@ -0,0 +1,150 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_PURCHASE; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import store.domain.vo.ProductName; +import store.dto.OrderConfirmDto; + +public class OrderInfo { + + private static final String OPEN_BRACKET = "["; + private static final String CLOSE_BRACKET = "]"; + private static final String SEPARATOR = "-"; + + private static final int MIN_LENGTH = 5; + private static final int BRACKET_OFFSET = 1; + private static final int NAME_IDX = 0; + private static final int QUANTITY_IDX = 1; + private static final int SPLIT_LENGTH = 2; + private static final int ZERO = 0; + + private final ProductName productName; + private final long requestQuantity; + + public OrderInfo(ProductName productName, long requestQuantity) { + this.productName = productName; + this.requestQuantity = requestQuantity; + } + + public static OrderInfo of(ProductName productName, long requestQuantity) { + return new OrderInfo(productName, requestQuantity); + } + + public static OrderInfo create(String input) { + validInput(input); + String[] parsedInput = parseNameAndQuantity(input); + return new OrderInfo(ProductName.create(parsedInput[NAME_IDX]), parseQuantity(parsedInput[QUANTITY_IDX])); + } + + protected static Map<ProductName, Long> sumQuantityByProduct(List<OrderInfo> orderInfos) { + Map<ProductName, Long> purchaseCountMap = new LinkedHashMap<>(); + + orderInfos.forEach( + orderInfo -> purchaseCountMap.merge(orderInfo.productName, orderInfo.requestQuantity, + Long::sum)); + + return purchaseCountMap; + } + + private static void validInput(String input) { + if (input == null || input.isBlank() || input.length() < MIN_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + boolean startsWith = input.startsWith(OPEN_BRACKET); + boolean endsWith = input.endsWith(CLOSE_BRACKET); + if ((!startsWith || !endsWith) && input.contains(SEPARATOR)) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String[] parseNameAndQuantity(String input) { + String trimInput = trimBrackets(input); + validTrimInput(trimInput); + String[] splitInput = trimInput.split(SEPARATOR); + validSplitInput(splitInput); + + return splitInput; + } + + private static void validTrimInput(String trimInput) { + boolean startsWith = trimInput.startsWith(SEPARATOR); + boolean endsWith = trimInput.endsWith(SEPARATOR); + + if (startsWith || endsWith) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String trimBrackets(String input) { + int endIdx = input.length() - BRACKET_OFFSET; + + return input.substring(BRACKET_OFFSET, endIdx); + } + + private static long parseQuantity(String number) { + try { + long parseNumber = Long.parseLong(number); + validQuantity(parseNumber); + return parseNumber; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validQuantity(long number) { + if (number <= ZERO) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validSplitInput(String[] splitInput) { + if (splitInput.length != SPLIT_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + if (splitInput[NAME_IDX].isBlank() || splitInput[QUANTITY_IDX].isBlank()) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + public OrderConfirmDto toConfirmDto(Product product) { + long requireQuantity = product.calculateRequiredQuantity(requestQuantity); + + return OrderConfirmDto.create(productName, requestQuantity, requireQuantity); + } + + public void validQuantity(Product product) { + product.validStock(requestQuantity); + } + + public String toOriginalInput() { + return OPEN_BRACKET + productName + SEPARATOR + requestQuantity + CLOSE_BRACKET; + } + + public ProductName getProductName() { + return productName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderInfo that = (OrderInfo) o; + return Objects.equals(productName, that.productName) && Objects.equals(requestQuantity, + that.requestQuantity); + } + + @Override + public int hashCode() { + return Objects.hash(productName, requestQuantity); + } +}
Java
생성로직이 복잡해 보이는데 해당 로직을 별도의 Builder나 Factory 클래스로 옮기는 거는 어떨까요?
@@ -0,0 +1,150 @@ +package store.domain; + +import static store.enums.ErrorMessage.INVALID_PURCHASE; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import store.domain.vo.ProductName; +import store.dto.OrderConfirmDto; + +public class OrderInfo { + + private static final String OPEN_BRACKET = "["; + private static final String CLOSE_BRACKET = "]"; + private static final String SEPARATOR = "-"; + + private static final int MIN_LENGTH = 5; + private static final int BRACKET_OFFSET = 1; + private static final int NAME_IDX = 0; + private static final int QUANTITY_IDX = 1; + private static final int SPLIT_LENGTH = 2; + private static final int ZERO = 0; + + private final ProductName productName; + private final long requestQuantity; + + public OrderInfo(ProductName productName, long requestQuantity) { + this.productName = productName; + this.requestQuantity = requestQuantity; + } + + public static OrderInfo of(ProductName productName, long requestQuantity) { + return new OrderInfo(productName, requestQuantity); + } + + public static OrderInfo create(String input) { + validInput(input); + String[] parsedInput = parseNameAndQuantity(input); + return new OrderInfo(ProductName.create(parsedInput[NAME_IDX]), parseQuantity(parsedInput[QUANTITY_IDX])); + } + + protected static Map<ProductName, Long> sumQuantityByProduct(List<OrderInfo> orderInfos) { + Map<ProductName, Long> purchaseCountMap = new LinkedHashMap<>(); + + orderInfos.forEach( + orderInfo -> purchaseCountMap.merge(orderInfo.productName, orderInfo.requestQuantity, + Long::sum)); + + return purchaseCountMap; + } + + private static void validInput(String input) { + if (input == null || input.isBlank() || input.length() < MIN_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + boolean startsWith = input.startsWith(OPEN_BRACKET); + boolean endsWith = input.endsWith(CLOSE_BRACKET); + if ((!startsWith || !endsWith) && input.contains(SEPARATOR)) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String[] parseNameAndQuantity(String input) { + String trimInput = trimBrackets(input); + validTrimInput(trimInput); + String[] splitInput = trimInput.split(SEPARATOR); + validSplitInput(splitInput); + + return splitInput; + } + + private static void validTrimInput(String trimInput) { + boolean startsWith = trimInput.startsWith(SEPARATOR); + boolean endsWith = trimInput.endsWith(SEPARATOR); + + if (startsWith || endsWith) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static String trimBrackets(String input) { + int endIdx = input.length() - BRACKET_OFFSET; + + return input.substring(BRACKET_OFFSET, endIdx); + } + + private static long parseQuantity(String number) { + try { + long parseNumber = Long.parseLong(number); + validQuantity(parseNumber); + return parseNumber; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validQuantity(long number) { + if (number <= ZERO) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + private static void validSplitInput(String[] splitInput) { + if (splitInput.length != SPLIT_LENGTH) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + + if (splitInput[NAME_IDX].isBlank() || splitInput[QUANTITY_IDX].isBlank()) { + throw new IllegalArgumentException(INVALID_PURCHASE.getMessage()); + } + } + + public OrderConfirmDto toConfirmDto(Product product) { + long requireQuantity = product.calculateRequiredQuantity(requestQuantity); + + return OrderConfirmDto.create(productName, requestQuantity, requireQuantity); + } + + public void validQuantity(Product product) { + product.validStock(requestQuantity); + } + + public String toOriginalInput() { + return OPEN_BRACKET + productName + SEPARATOR + requestQuantity + CLOSE_BRACKET; + } + + public ProductName getProductName() { + return productName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderInfo that = (OrderInfo) o; + return Objects.equals(productName, that.productName) && Objects.equals(requestQuantity, + that.requestQuantity); + } + + @Override + public int hashCode() { + return Objects.hash(productName, requestQuantity); + } +}
Java
도메인에 DTO 변환 로직이 직접 포함되는거는 부적절해 보입니다
@@ -0,0 +1,129 @@ +package store.domain; + +import static store.utils.Constants.BLANK; +import static store.utils.Constants.TAB; + +import java.util.List; +import java.util.Objects; +import java.util.StringJoiner; +import store.dto.OrderConfirmDto; +import store.enums.Confirmation; +import store.utils.StringUtils; + +public class VerifiedOrder { + + private static final long ZERO = 0; + + private final Product product; + private final long requestQuantity; + + protected VerifiedOrder(Product product, long requestQuantity) { + this.product = product; + this.requestQuantity = requestQuantity; + } + + public static VerifiedOrder of(Product product, long requestQuantity) { + return new VerifiedOrder(product, requestQuantity); + } + + public static VerifiedOrder of(Product product, OrderConfirmDto orderConfirmDto, Confirmation confirmation) { + return new VerifiedOrder(product, processQuantity(orderConfirmDto, confirmation)); + } + + public static long getTotalCount(List<VerifiedOrder> verifiedOrders) { + return verifiedOrders.stream() + .mapToLong(VerifiedOrder::getRequestQuantity) + .sum(); + } + + private static long processQuantity(OrderConfirmDto confirmDto, Confirmation confirmation) { + if (confirmDto.problemQuantity() > 0 && confirmation.equals(Confirmation.YES)) { + return confirmDto.requestQuantity() + confirmDto.problemQuantity(); + } + if (confirmDto.problemQuantity() < 0 && confirmation.equals(Confirmation.NO)) { + return ZERO; + } + + return confirmDto.requestQuantity(); + } + + public void applyStock() { + product.applyStock(requestQuantity); + } + + public String toQuantityString() { + return String.valueOf(requestQuantity); + } + + public String getStatus() { + StringJoiner joiner = new StringJoiner(TAB); + return joiner.add(product.toProductName()) + .add(BLANK) + .add(toQuantityString()) + .add(BLANK) + .add(toFormatTotalPriceByProduct()) + .toString(); + } + + public String getDiscountStatus() { + StringJoiner joiner = new StringJoiner(TAB); + long giftQuantity = product.calculateGiftQuantity(requestQuantity); + + if (giftQuantity == 0) { + return null; + } + + return joiner.add(product.toProductName() + TAB) + .add(String.valueOf(giftQuantity)) + .toString(); + } + + protected String toFormatTotalPriceByProduct() { + long totalPrice = product.calculateSumPrice(requestQuantity); + + return StringUtils.numberFormat(totalPrice); + } + + protected long getTotalOriginalPriceByProduct() { + return product.sumOriginalPrice(requestQuantity); + } + + protected long getTotalPrice() { + return product.calculateSumPrice(requestQuantity); + } + + protected long getTotalDiscountByProduct() { + long giftQuantity = product.calculateGiftQuantity(requestQuantity); + + return product.calculateSumPrice(giftQuantity); + } + + private long getRequestQuantity() { + return requestQuantity; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VerifiedOrder that = (VerifiedOrder) o; + return requestQuantity == that.requestQuantity && Objects.equals(product, that.product); + } + + @Override + public int hashCode() { + return Objects.hash(product, requestQuantity); + } + + @Override + public String toString() { + return "OrderVerificationV2{" + + "product=" + product + + ", requestQuantity=" + requestQuantity + + '}'; + } +}
Java
`Object`의 기본 메서드를 오버라이딩 하여 기능을 만드신 것이 인상깊었어요
@@ -0,0 +1,156 @@ +package store.domain; + +import java.util.Objects; + +public class Stock { + private static final String COUNT_UNIT = "개"; + private static final String EMPTY_STOCK = "재고 없음"; + private static final long NOT_PROBLEM_COUNT = 0; + + private long normalQuantity; + private long promotionQuantity; + + public Stock(long normalQuantity, long promotionQuantity) { + this.normalQuantity = normalQuantity; + this.promotionQuantity = promotionQuantity; + } + + public Stock() { + this.normalQuantity = 0; + this.promotionQuantity = 0; + } + + public long calculateGiftQuantity(long requestQuantity, Promotion promotion) { + if (promotion == null) { + return 0L; + } + + long promotionBundleCnt = getPromotionBundleCnt(requestQuantity, promotion); + return promotion.totalGetQuantity(promotionBundleCnt); + } + + public void applyQuantity(long requestQuantity) { + long exceedPromotionQuantity = requestQuantity - promotionQuantity; + + if (exceedPromotionQuantity > 0) { + updatePromotionProduct(0); + updateNormalProduct(normalQuantity - exceedPromotionQuantity); + return; + } + + updatePromotionProduct(promotionQuantity - requestQuantity); + } + + public void addNormalProduct(long count) { + this.normalQuantity += count; + } + + public void addPromotionProduct(long count) { + this.promotionQuantity += count; + } + + public long total() { + return normalQuantity + promotionQuantity; + } + + public String toPromotionCountString() { + if (this.promotionQuantity == 0) { + return EMPTY_STOCK; + } + return promotionQuantity + COUNT_UNIT; + } + + public String toNormalCountString() { + if (this.normalQuantity == 0) { + return EMPTY_STOCK; + } + return normalQuantity + COUNT_UNIT; + } + + /** + * 프로모션에 따라 문제 있는 수량을 검증하는 메서드 + * + * @param requestQuantity 요청 수량 + * @param promotion 프로모션 여부 + * @return 0보다 작으면 원가, 0보다 크면 증정하는 수량을 반환한다. + */ + + public long problemQuantity(long requestQuantity, Promotion promotion) { + validRequestQuantity(requestQuantity); + if (promotion == null || promotionQuantity == 0) { + return NOT_PROBLEM_COUNT; + } + + long giftQuantity = promotion.getPromotionGiftQuantity(requestQuantity); + if (promotionQuantity < Math.max(requestQuantity + giftQuantity, promotion.bundleSize())) { + return calculateOriginalPriceQuantity(requestQuantity, promotion); + } + + return giftQuantity; + } + + + /** + * 요청한 수량 중 원가로 처리되어야 하는 수량을 계산하는 메서드 + * 프로모션이 존재하지 않는 경우 원가로 되는 요청 수량을 음수로 반환 + * + * @param requestQuantity 요청한 수량 + * @param promotion 프로모션 + * @return 원가로 처리되는 수량은 음수로 반환 + */ + + public long calculateOriginalPriceQuantity(long requestQuantity, Promotion promotion) { + validRequestQuantity(requestQuantity); + if (promotion == null) { + return -requestQuantity; + } + + long promotionBundleCnt = getPromotionBundleCnt(requestQuantity, promotion); + long totalPromotionQuantity = promotion.bundleSize() * promotionBundleCnt; + + return totalPromotionQuantity - requestQuantity; + } + + /** + * @param requestQuantity 요청한 수량 + * @param promotion 프로모션 + * @return 프로모션 묶음 수를 반환한다. + */ + + private long getPromotionBundleCnt(long requestQuantity, Promotion promotion) { + long availablePromoUnits = Math.min(requestQuantity, promotionQuantity); + + return availablePromoUnits / promotion.bundleSize(); + } + + private void validRequestQuantity(long requestQuantity) { + if (requestQuantity > total()) { + throw new IllegalStateException("처리할 수 없는 요청 수량입니다!"); + } + } + + private void updateNormalProduct(long count) { + this.normalQuantity = count; + } + + private void updatePromotionProduct(long count) { + this.promotionQuantity = count; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Stock stock = (Stock) o; + return normalQuantity == stock.normalQuantity && promotionQuantity == stock.promotionQuantity; + } + + @Override + public int hashCode() { + return Objects.hash(normalQuantity, promotionQuantity); + } +}
Java
프로모션을 검증하고 적용하는 과정을 `stock`에서 처리하셨네요. 저는 `purchaseService`에서 진행했는데 `stock` 도메인이 프로모션 적용 로직을 까지 가지고 있는건 별로라고 생각했었어요. 하지만 결국 `stock`을 까봐야 프로모션을 적용할 수 있으니 기욱님처럼 도메인에서 담당하는것도 좋아보이네요!
@@ -165,3 +165,47 @@ public enum Coin { - **Git의 커밋 단위는 앞 단계에서 README.md 파일에 정리한 기능 목록 단위**로 추가한다. - [AngularJS Commit Message Conventions](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) 참고해 commit log를 남긴다. - 과제 진행 및 제출 방법은 [프리코스 과제 제출 문서](https://github.com/woowacourse/woowacourse-docs/tree/master/precourse) 를 참고한다. + +--- + +## 기능 구현 목록 +- [x] [자판기] 사용자로부터 자판기가 보유하고 있는 금액을 입력받는 기능 + + +- [x] [자판기] 자판기가 보유하고 있는 금액만큼 동전을 무작위로 생성하는 기능 + - [x] 투입 금액으로는 동전을 생성하지 않는다. + + +- [x] [자판기] 자판기가 보유하고 있는 동전의 개수를 출력하는 기능 + + +- [x] [자판기] 사용자로부터 상품명, 가격, 수량을 입력받고, 상품을 추가하는 기능 + - [x] [예외 상황] 개별 상품이 대괄호([])로 묶이지 않는 경우 + - [x] [예외 상황] 상품명, 가격, 수량이 쉼표(,)로 구분되지 않는 경우 + - [x] [예외 상황] 상품 가격이 100원부터 시작하지 않고, 10원으로 나누어 떨어지지지 않는 경우 + - [x] [예외 상황] 상품명이 비어있는 경우 + - [x] [예외 상황] 상품 수량이 0 미만인 경우 + + +- [x] [구매] 사용자로부터 투입 금액을 입력받는 기능 + + +- [x] [구매] 사용자로부터 구매할 상품명을 입력받는 기능 + + +- [x] [구매] 입력받은 투입 금액과 상품명을 이용해 구매를 진행하는 기능 + + +- [x] [잔돈 반환] 잔돈을 돌려줄 때 현재 보유한 최소 개수의 동전으로 잔돈을 돌려주는 기능 + - [x] 지폐를 잔돈으로 반환하는 경우는 없다고 가정한다. + - [x] 잔돈을 반환할 수 없는 경우 잔돈으로 반환할 수 있는 금액만 반환한다. + - [x] 남은 금액이 상품의 최저 가격보다 적거나, 모든 상품이 소진된 경우 바로 잔돈을 돌려준다. + - [x] 반환되지 않은 금액은 자판기에 남는다. + + +과제 시작 시간: 21:30 +<br>TDD 종료 : 01:58 (4시간 28분) +<br>MVP 완성 : 02:13 (TDD + 15분) +<br>5시간 종료 : 02:30 +<br>리팩토링 종료 : 03:10 (MVP 완성 + 40분) +<br>총 5시간 40분
Unknown
설계에 시간을 따로 투자하셨는지 궁금해요
@@ -165,3 +165,47 @@ public enum Coin { - **Git의 커밋 단위는 앞 단계에서 README.md 파일에 정리한 기능 목록 단위**로 추가한다. - [AngularJS Commit Message Conventions](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) 참고해 commit log를 남긴다. - 과제 진행 및 제출 방법은 [프리코스 과제 제출 문서](https://github.com/woowacourse/woowacourse-docs/tree/master/precourse) 를 참고한다. + +--- + +## 기능 구현 목록 +- [x] [자판기] 사용자로부터 자판기가 보유하고 있는 금액을 입력받는 기능 + + +- [x] [자판기] 자판기가 보유하고 있는 금액만큼 동전을 무작위로 생성하는 기능 + - [x] 투입 금액으로는 동전을 생성하지 않는다. + + +- [x] [자판기] 자판기가 보유하고 있는 동전의 개수를 출력하는 기능 + + +- [x] [자판기] 사용자로부터 상품명, 가격, 수량을 입력받고, 상품을 추가하는 기능 + - [x] [예외 상황] 개별 상품이 대괄호([])로 묶이지 않는 경우 + - [x] [예외 상황] 상품명, 가격, 수량이 쉼표(,)로 구분되지 않는 경우 + - [x] [예외 상황] 상품 가격이 100원부터 시작하지 않고, 10원으로 나누어 떨어지지지 않는 경우 + - [x] [예외 상황] 상품명이 비어있는 경우 + - [x] [예외 상황] 상품 수량이 0 미만인 경우 + + +- [x] [구매] 사용자로부터 투입 금액을 입력받는 기능 + + +- [x] [구매] 사용자로부터 구매할 상품명을 입력받는 기능 + + +- [x] [구매] 입력받은 투입 금액과 상품명을 이용해 구매를 진행하는 기능 + + +- [x] [잔돈 반환] 잔돈을 돌려줄 때 현재 보유한 최소 개수의 동전으로 잔돈을 돌려주는 기능 + - [x] 지폐를 잔돈으로 반환하는 경우는 없다고 가정한다. + - [x] 잔돈을 반환할 수 없는 경우 잔돈으로 반환할 수 있는 금액만 반환한다. + - [x] 남은 금액이 상품의 최저 가격보다 적거나, 모든 상품이 소진된 경우 바로 잔돈을 돌려준다. + - [x] 반환되지 않은 금액은 자판기에 남는다. + + +과제 시작 시간: 21:30 +<br>TDD 종료 : 01:58 (4시간 28분) +<br>MVP 완성 : 02:13 (TDD + 15분) +<br>5시간 종료 : 02:30 +<br>리팩토링 종료 : 03:10 (MVP 완성 + 40분) +<br>총 5시간 40분
Unknown
새벽3시까지 쉬지않고 6시간 코딩은 좀.. 무섭네요 😵‍💫
@@ -0,0 +1,25 @@ +package vendingmachine.constant; + +public enum ErrorMessage { + INVALID_COIN_MONEY("[ERROR] 유효하지 않은 동전 금액입니다."), + INVALID_PRODUCT_NAME("[ERROR] 상품명은 비어 있을 수 없습니다."), + INVALID_PRODUCT_PRICE("[ERROR] 상품 가격은 100원부터 시작하며 10원으로 나누어 떨어져야 합니다."), + INVALID_PRODUCT_QUANTITY("[ERROR] 상품 수량은 0 이상이어야 합니다."), + PRODUCT_SOLD_OUT("[ERROR] 해당 상품은 품절되었습니다."), + PRODUCT_IS_NOT_EXIST("[ERROR] 해당 상품이 존재하지 않습니다."), + NOT_ENOUGH_MONEY("[ERROR] 구매 가능한 상품이 없습니다."), + MONEY_SHOULD_BE_NUMBER("[ERROR] 금액은 숫자여야 합니다."), + MONEY_SHOULD_BE_POSITIVE("[ERROR] 금액은 양수여야 합니다."), + INVALID_PRODUCT_FORMAT("[ERROR] 상품의 형식이 올바르지 않습니다."), + ; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
공통되는 문구 `[ERROR]`는 상수화해도 좋았을 것 같아요!
@@ -0,0 +1,25 @@ +package vendingmachine.constant; + +public enum ErrorMessage { + INVALID_COIN_MONEY("[ERROR] 유효하지 않은 동전 금액입니다."), + INVALID_PRODUCT_NAME("[ERROR] 상품명은 비어 있을 수 없습니다."), + INVALID_PRODUCT_PRICE("[ERROR] 상품 가격은 100원부터 시작하며 10원으로 나누어 떨어져야 합니다."), + INVALID_PRODUCT_QUANTITY("[ERROR] 상품 수량은 0 이상이어야 합니다."), + PRODUCT_SOLD_OUT("[ERROR] 해당 상품은 품절되었습니다."), + PRODUCT_IS_NOT_EXIST("[ERROR] 해당 상품이 존재하지 않습니다."), + NOT_ENOUGH_MONEY("[ERROR] 구매 가능한 상품이 없습니다."), + MONEY_SHOULD_BE_NUMBER("[ERROR] 금액은 숫자여야 합니다."), + MONEY_SHOULD_BE_POSITIVE("[ERROR] 금액은 양수여야 합니다."), + INVALID_PRODUCT_FORMAT("[ERROR] 상품의 형식이 올바르지 않습니다."), + ; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
예외 메시지 내의 숫자는 상수를 활용하면 좋을 것 같아요!
@@ -0,0 +1,21 @@ +package vendingmachine.constant; + +public enum OutputMessage { + INPUT_MACHINE_HAVE("자판기가 보유하고 있는 금액을 입력해 주세요."), + MACHINE_HAVE("\n자판기가 보유한 동전"), + INPUT_PRODUCTS("\n상품명과 가격, 수량을 입력해 주세요."), + INPUT_MONEY("\n투입 금액을 입력해 주세요."), + BUYING("\n투입 금액: %d원%n구매할 상품명을 입력해주세요."), + RETURN_CHANGE("\n잔돈 반환:"), + ; + + private final String message; + + OutputMessage(String message) { + this.message = message; + } + + public String format(Object... args) { + return String.format(this.message, args); + } +}
Java
%n을 활용하는것도 좋을 것 같아요!
@@ -0,0 +1,75 @@ +package vendingmachine.controller; + +import vendingmachine.model.domain.Coins; +import vendingmachine.model.domain.Products; +import vendingmachine.model.domain.VendingMachine; +import vendingmachine.model.service.VendingMachineService; +import vendingmachine.view.InputView; +import vendingmachine.view.OutputView; + +public class VendingMachineController { + private final VendingMachineService vendingMachineService; + + public VendingMachineController(VendingMachineService vendingMachineService) { + this.vendingMachineService = vendingMachineService; + } + + public void start() { + OutputView.promptInputMachineHave(); + int money = InputView.vendingMachineHave(); + + VendingMachine vendingMachine = vendingMachineService.getVendingMachine(money); + OutputView.promptMachineHave(vendingMachine); + + getProducts(vendingMachine); + int inputMoney = getInputMoney(); + + inputMoney = getInputMoney(vendingMachine, inputMoney); + getReturnChange(vendingMachine, inputMoney); + } + + private static void getProducts(VendingMachine vendingMachine) { + OutputView.promptInputProducts(); + Products products = InputView.buyProducts(); + vendingMachine.addProducts(products); + } + + private static int getInputMoney() { + OutputView.promptInputMoney(); + return InputView.inputMoney(); + } + + private static int getInputMoney(VendingMachine vendingMachine, int inputMoney) { + while (inputMoney > 0) { + int minPrice = vendingMachine.findMinimumProductPrice(); + if (inputMoney < minPrice) { + break; + } + if (vendingMachine.areProductsSoldOut()) { + break; + } + + OutputView.promptBuying(inputMoney); + String buyProductName = InputView.buyProduct(); + + inputMoney = calculateInputMoney(vendingMachine, inputMoney, buyProductName); + } + return inputMoney; + } + + private static void getReturnChange(VendingMachine vendingMachine, int inputMoney) { + Coins change = vendingMachine.returnChange(inputMoney); + OutputView.promptReturnChange(change); + } + + private static int calculateInputMoney(VendingMachine vendingMachine, int inputMoney, String buyProductName) { + try { + int productPrice = vendingMachine.findProductPrice(buyProductName); + inputMoney -= productPrice; + vendingMachine.purchaseProduct(buyProductName); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + return inputMoney; + } +}
Java
책임을 조금 더 서비스에 위임했어도 좋았을 것 같아요!
@@ -0,0 +1,75 @@ +package vendingmachine.controller; + +import vendingmachine.model.domain.Coins; +import vendingmachine.model.domain.Products; +import vendingmachine.model.domain.VendingMachine; +import vendingmachine.model.service.VendingMachineService; +import vendingmachine.view.InputView; +import vendingmachine.view.OutputView; + +public class VendingMachineController { + private final VendingMachineService vendingMachineService; + + public VendingMachineController(VendingMachineService vendingMachineService) { + this.vendingMachineService = vendingMachineService; + } + + public void start() { + OutputView.promptInputMachineHave(); + int money = InputView.vendingMachineHave(); + + VendingMachine vendingMachine = vendingMachineService.getVendingMachine(money); + OutputView.promptMachineHave(vendingMachine); + + getProducts(vendingMachine); + int inputMoney = getInputMoney(); + + inputMoney = getInputMoney(vendingMachine, inputMoney); + getReturnChange(vendingMachine, inputMoney); + } + + private static void getProducts(VendingMachine vendingMachine) { + OutputView.promptInputProducts(); + Products products = InputView.buyProducts(); + vendingMachine.addProducts(products); + } + + private static int getInputMoney() { + OutputView.promptInputMoney(); + return InputView.inputMoney(); + } + + private static int getInputMoney(VendingMachine vendingMachine, int inputMoney) { + while (inputMoney > 0) { + int minPrice = vendingMachine.findMinimumProductPrice(); + if (inputMoney < minPrice) { + break; + } + if (vendingMachine.areProductsSoldOut()) { + break; + } + + OutputView.promptBuying(inputMoney); + String buyProductName = InputView.buyProduct(); + + inputMoney = calculateInputMoney(vendingMachine, inputMoney, buyProductName); + } + return inputMoney; + } + + private static void getReturnChange(VendingMachine vendingMachine, int inputMoney) { + Coins change = vendingMachine.returnChange(inputMoney); + OutputView.promptReturnChange(change); + } + + private static int calculateInputMoney(VendingMachine vendingMachine, int inputMoney, String buyProductName) { + try { + int productPrice = vendingMachine.findProductPrice(buyProductName); + inputMoney -= productPrice; + vendingMachine.purchaseProduct(buyProductName); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + return inputMoney; + } +}
Java
이부분은 도메인 객체의 관심사라고 볼 수도 있을 것 같습니다!
@@ -0,0 +1,59 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_NAME; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_PRICE; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_QUANTITY; +import static vendingmachine.constant.ErrorMessage.PRODUCT_SOLD_OUT; +import static vendingmachine.constant.NumberConstant.*; + +public class Product { + private final String productName; + private final int price; + private int quantity; + + public Product(String productName, int price, int quantity) { + validateProductName(productName); + validatePrice(price); + validateQuantity(quantity); + this.productName = productName; + this.price = price; + this.quantity = quantity; + } + + private void validateProductName(String productName) { + if (productName == null || productName.isEmpty()) { + throw new IllegalArgumentException(INVALID_PRODUCT_NAME.getMessage()); + } + } + + private void validatePrice(int price) { + if (price < MINIMUM_MONEY_PRICE || price % DIVIDE_MONEY_UNIT != 0) { + throw new IllegalArgumentException(INVALID_PRODUCT_PRICE.getMessage()); + } + } + + private void validateQuantity(int quantity) { + if (quantity < 0) { + throw new IllegalArgumentException(INVALID_PRODUCT_QUANTITY.getMessage()); + } + } + + public int getPrice() { + return price; + } + + public boolean isNameSame(String inputProductName) { + return this.productName.equals(inputProductName); + } + + public boolean isQuantityZero() { + return this.quantity == 0; + } + + public void decreaseQuantity() { + if (quantity <= 0) { + throw new IllegalArgumentException(PRODUCT_SOLD_OUT.getMessage()); + } + this.quantity -= 1; + } +}
Java
수량까지 final로 선언해서 불변 객체로 활용하는 건 어떻게 생각하시나요??
@@ -0,0 +1,43 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.PRODUCT_IS_NOT_EXIST; +import static vendingmachine.constant.ErrorMessage.NOT_ENOUGH_MONEY; + +import java.util.List; + +public class Products { + private final List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public int findPriceByProductName(String productName) { + return products.stream() + .filter(product -> product.isNameSame(productName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(PRODUCT_IS_NOT_EXIST.getMessage())) + .getPrice(); + } + + public int findMinimumPrice() { + return products.stream() + .filter(product -> !product.isQuantityZero()) + .mapToInt(Product::getPrice) + .min() + .orElseThrow(() -> new IllegalArgumentException(NOT_ENOUGH_MONEY.getMessage())); + } + + public boolean areSoldOut() { + return products.stream().allMatch(Product::isQuantityZero); + } + + public void decreaseProductQuantity(String productName) { + Product product = products.stream() + .filter(name -> name.isNameSame(productName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(PRODUCT_IS_NOT_EXIST.getMessage())); + + product.decreaseQuantity(); + } +}
Java
stream을 잘 활용하시는 것 같아요 👍
@@ -0,0 +1,38 @@ +package vendingmachine.model.domain; + +public class VendingMachine { + private final Coins coins; + private Products products; + + public VendingMachine(Coins coins) { + this.coins = coins; + } + + public Coins getCoins() { + return coins; + } + + public void addProducts(Products products) { + this.products = products; + } + + public int findProductPrice(String buyProductName) { + return products.findPriceByProductName(buyProductName); + } + + public int findMinimumProductPrice() { + return products.findMinimumPrice(); + } + + public boolean areProductsSoldOut() { + return products.areSoldOut(); + } + + public void purchaseProduct(String buyProductName) { + products.decreaseProductQuantity(buyProductName); + } + + public Coins returnChange(int amount) { + return coins.calculateChange(amount); + } +}
Java
일급 컬렉션을 활용하니 확실히 관심사의 분리가 적절하게 이루어지는 것 같아요 👍
@@ -0,0 +1,73 @@ +package vendingmachine.util; + +import static vendingmachine.constant.ErrorMessage.MONEY_SHOULD_BE_NUMBER; +import static vendingmachine.constant.ErrorMessage.MONEY_SHOULD_BE_POSITIVE; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_FORMAT; +import static vendingmachine.constant.NumberConstant.*; + +import java.util.ArrayList; +import java.util.List; + +import vendingmachine.model.domain.Product; +import vendingmachine.model.domain.Products; + +public class Parser { + private static final String SEMICOLON = ";"; + private static final String LEFT_BRACKET = "["; + private static final String RIGHT_BRACKET = "]"; + private static final String COMMA = ","; + + public static int parseInteger(String input) { + try { + int money = Integer.parseInt(input); + validateNegative(money); + return money; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(MONEY_SHOULD_BE_NUMBER.getMessage()); + } + } + + private static void validateNegative(int money) { + if(money < 0) { + throw new IllegalArgumentException(MONEY_SHOULD_BE_POSITIVE.getMessage()); + } + } + + public static Products parseProducts(String inputProducts) { + List<Product> products = parseProductList(inputProducts); + return new Products(products); + } + + private static List<Product> parseProductList(String inputProducts) { + String[] splitProducts = inputProducts.split(SEMICOLON); + List<Product> products = new ArrayList<>(); + + for (String splitProduct : splitProducts) { + validateProductFormat(splitProduct); + Product product = parseProduct(splitProduct); + products.add(product); + } + return products; + } + + private static void validateProductFormat(String productInfo) { + if (!productInfo.startsWith(LEFT_BRACKET) || !productInfo.endsWith(RIGHT_BRACKET)) { + throw new IllegalArgumentException(INVALID_PRODUCT_FORMAT.getMessage()); + } + } + + private static Product parseProduct(String productInfo) { + String content = productInfo.substring(1, productInfo.length() - 1); + String[] splitProductInfo = content.split(COMMA); + + if (splitProductInfo.length != PRODUCTS_LENGTH) { + throw new IllegalArgumentException(INVALID_PRODUCT_FORMAT.getMessage()); + } + + String name = splitProductInfo[0].trim(); + int price = Integer.parseInt(splitProductInfo[1].trim()); + int quantity = Integer.parseInt(splitProductInfo[2].trim()); + + return new Product(name, price, quantity); + } +}
Java
정규표현식을 사용하지 않은 이유가 있나요?!
@@ -0,0 +1,44 @@ +package vendingmachine.view; + +import camp.nextstep.edu.missionutils.Console; +import vendingmachine.model.domain.Products; +import vendingmachine.util.Parser; + +public class InputView { + public static int vendingMachineHave() { + while (true) { + try { + String money = Console.readLine(); + return Parser.parseInteger(money); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + } + } + + public static Products buyProducts() { + while (true) { + try { + String products = Console.readLine(); + return Parser.parseProducts(products); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + } + } + + public static int inputMoney() { + while (true) { + try { + String money = Console.readLine(); + return Parser.parseInteger(money); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + } + } + + public static String buyProduct() { + return Console.readLine(); + } +}
Java
재입력을 input단에서 진행해주셨네요! 몇 가지 궁금한 점이 있습니다. 1. 재입력 시 입력 유도 문구는 재출력되지 않나요?? 2. 입력형식이 아닌 다른 잘못된 입력 시에는 어떻게 재입력이 진행되나요? (ex. 매진된 상품 구매 요청, 존재하지 않는 상품명 입력 등)
@@ -0,0 +1,36 @@ +package vendingmachine.model.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class ProductTest { + @Test + @DisplayName("상품 가격이 100원부터 시작하지 않는 경우 예외가 발생한다.") + void 상품_가격이_100원부터_시작하지_않는_경우_예외_발생() { + assertThatThrownBy(() -> new Product("콜라", 90, 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("상품 가격이 10원으로 나누어 떨어지지지 않는 경우 예외가 발생한다.") + void 상품_가격이_10원으로_나누어_떨어지지_않는_경우_예외_발생() { + assertThatThrownBy(() -> new Product("콜라", 9, 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("상품명이 비어있는 경 예외가 발생한다.") + void 상품명이_비어있는_경우_예외_발생() { + assertThatThrownBy(() -> new Product("", 1000, 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("상품 수량이 0 미만인 경우 예외가 발생한다.") + void 상품_수량이_0_미만인_경우_예외_발생() { + assertThatThrownBy(() -> new Product("콜라", 1000, -1)) + .isInstanceOf(IllegalArgumentException.class); + } +}
Java
TDD 이후로 테스트 코드는 추가로 리팩토링하지 않으신 건가요??
@@ -0,0 +1,7 @@ +package vendingmachine.constant; + +public class NumberConstant { + public static final int MINIMUM_MONEY_PRICE = 100; + public static final int DIVIDE_MONEY_UNIT = 10; + public static final int PRODUCTS_LENGTH = 3; +}
Java
이게 무슨 숫자를 의미하는 건지, 왜 3인지 잘 모르겠어요
@@ -0,0 +1,37 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.*; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public enum Coin { + COIN_500(500), + COIN_100(100), + COIN_50(50), + COIN_10(10); + + private final int amount; + + Coin(final int amount) { + this.amount = amount; + } + + public int getAmount() { + return amount; + } + + public static List<Integer> getAmounts() { + return Arrays.stream(Coin.values()) + .map(Coin::getAmount) + .collect(Collectors.toList()); + } + + public static Coin from(int amount) { + return Arrays.stream(values()) + .filter(coin -> coin.getAmount() == amount) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(INVALID_COIN_MONEY.getMessage())); + } +}
Java
오옷 ㅎㅎㅎ 패키지 안에 클래스 5개만 넣기 잘 지키셨군요!!
@@ -0,0 +1,59 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_NAME; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_PRICE; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_QUANTITY; +import static vendingmachine.constant.ErrorMessage.PRODUCT_SOLD_OUT; +import static vendingmachine.constant.NumberConstant.*; + +public class Product { + private final String productName; + private final int price; + private int quantity; + + public Product(String productName, int price, int quantity) { + validateProductName(productName); + validatePrice(price); + validateQuantity(quantity); + this.productName = productName; + this.price = price; + this.quantity = quantity; + } + + private void validateProductName(String productName) { + if (productName == null || productName.isEmpty()) { + throw new IllegalArgumentException(INVALID_PRODUCT_NAME.getMessage()); + } + } + + private void validatePrice(int price) { + if (price < MINIMUM_MONEY_PRICE || price % DIVIDE_MONEY_UNIT != 0) { + throw new IllegalArgumentException(INVALID_PRODUCT_PRICE.getMessage()); + } + } + + private void validateQuantity(int quantity) { + if (quantity < 0) { + throw new IllegalArgumentException(INVALID_PRODUCT_QUANTITY.getMessage()); + } + } + + public int getPrice() { + return price; + } + + public boolean isNameSame(String inputProductName) { + return this.productName.equals(inputProductName); + } + + public boolean isQuantityZero() { + return this.quantity == 0; + } + + public void decreaseQuantity() { + if (quantity <= 0) { + throw new IllegalArgumentException(PRODUCT_SOLD_OUT.getMessage()); + } + this.quantity -= 1; + } +}
Java
구매 후 재고 수량을 조절해야 할 텐데 불변 객체로 선언해도 될까요?
@@ -0,0 +1,75 @@ +package vendingmachine.controller; + +import vendingmachine.model.domain.Coins; +import vendingmachine.model.domain.Products; +import vendingmachine.model.domain.VendingMachine; +import vendingmachine.model.service.VendingMachineService; +import vendingmachine.view.InputView; +import vendingmachine.view.OutputView; + +public class VendingMachineController { + private final VendingMachineService vendingMachineService; + + public VendingMachineController(VendingMachineService vendingMachineService) { + this.vendingMachineService = vendingMachineService; + } + + public void start() { + OutputView.promptInputMachineHave(); + int money = InputView.vendingMachineHave(); + + VendingMachine vendingMachine = vendingMachineService.getVendingMachine(money); + OutputView.promptMachineHave(vendingMachine); + + getProducts(vendingMachine); + int inputMoney = getInputMoney(); + + inputMoney = getInputMoney(vendingMachine, inputMoney); + getReturnChange(vendingMachine, inputMoney); + } + + private static void getProducts(VendingMachine vendingMachine) { + OutputView.promptInputProducts(); + Products products = InputView.buyProducts(); + vendingMachine.addProducts(products); + } + + private static int getInputMoney() { + OutputView.promptInputMoney(); + return InputView.inputMoney(); + } + + private static int getInputMoney(VendingMachine vendingMachine, int inputMoney) { + while (inputMoney > 0) { + int minPrice = vendingMachine.findMinimumProductPrice(); + if (inputMoney < minPrice) { + break; + } + if (vendingMachine.areProductsSoldOut()) { + break; + } + + OutputView.promptBuying(inputMoney); + String buyProductName = InputView.buyProduct(); + + inputMoney = calculateInputMoney(vendingMachine, inputMoney, buyProductName); + } + return inputMoney; + } + + private static void getReturnChange(VendingMachine vendingMachine, int inputMoney) { + Coins change = vendingMachine.returnChange(inputMoney); + OutputView.promptReturnChange(change); + } + + private static int calculateInputMoney(VendingMachine vendingMachine, int inputMoney, String buyProductName) { + try { + int productPrice = vendingMachine.findProductPrice(buyProductName); + inputMoney -= productPrice; + vendingMachine.purchaseProduct(buyProductName); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + return inputMoney; + } +}
Java
이 조건들은 while문 조건으로 안 넣고 따로 빼신 이유가 궁금해요
@@ -0,0 +1,37 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.*; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public enum Coin { + COIN_500(500), + COIN_100(100), + COIN_50(50), + COIN_10(10); + + private final int amount; + + Coin(final int amount) { + this.amount = amount; + } + + public int getAmount() { + return amount; + } + + public static List<Integer> getAmounts() { + return Arrays.stream(Coin.values()) + .map(Coin::getAmount) + .collect(Collectors.toList()); + } + + public static Coin from(int amount) { + return Arrays.stream(values()) + .filter(coin -> coin.getAmount() == amount) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(INVALID_COIN_MONEY.getMessage())); + } +}
Java
이 부분이 선권님이랑 거의 동일해서 알아봤더니 Enum 관련 관용적 패턴인 거 같던데 맞나요..?!! 안 그래도 enum 클래스 사용법을 잘 몰라서 초반에 시간이 많이 지체됐는데, 이렇게 쓰는 거군용
@@ -0,0 +1,43 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.PRODUCT_IS_NOT_EXIST; +import static vendingmachine.constant.ErrorMessage.NOT_ENOUGH_MONEY; + +import java.util.List; + +public class Products { + private final List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public int findPriceByProductName(String productName) { + return products.stream() + .filter(product -> product.isNameSame(productName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(PRODUCT_IS_NOT_EXIST.getMessage())) + .getPrice(); + } + + public int findMinimumPrice() { + return products.stream() + .filter(product -> !product.isQuantityZero()) + .mapToInt(Product::getPrice) + .min() + .orElseThrow(() -> new IllegalArgumentException(NOT_ENOUGH_MONEY.getMessage())); + } + + public boolean areSoldOut() { + return products.stream().allMatch(Product::isQuantityZero); + } + + public void decreaseProductQuantity(String productName) { + Product product = products.stream() + .filter(name -> name.isNameSame(productName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(PRODUCT_IS_NOT_EXIST.getMessage())); + + product.decreaseQuantity(); + } +}
Java
isQuantityZero 부분은 Product에 두고 순회하는 부분만 products가 가지고 있으니까 좋네요!!
@@ -165,3 +165,47 @@ public enum Coin { - **Git의 커밋 단위는 앞 단계에서 README.md 파일에 정리한 기능 목록 단위**로 추가한다. - [AngularJS Commit Message Conventions](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) 참고해 commit log를 남긴다. - 과제 진행 및 제출 방법은 [프리코스 과제 제출 문서](https://github.com/woowacourse/woowacourse-docs/tree/master/precourse) 를 참고한다. + +--- + +## 기능 구현 목록 +- [x] [자판기] 사용자로부터 자판기가 보유하고 있는 금액을 입력받는 기능 + + +- [x] [자판기] 자판기가 보유하고 있는 금액만큼 동전을 무작위로 생성하는 기능 + - [x] 투입 금액으로는 동전을 생성하지 않는다. + + +- [x] [자판기] 자판기가 보유하고 있는 동전의 개수를 출력하는 기능 + + +- [x] [자판기] 사용자로부터 상품명, 가격, 수량을 입력받고, 상품을 추가하는 기능 + - [x] [예외 상황] 개별 상품이 대괄호([])로 묶이지 않는 경우 + - [x] [예외 상황] 상품명, 가격, 수량이 쉼표(,)로 구분되지 않는 경우 + - [x] [예외 상황] 상품 가격이 100원부터 시작하지 않고, 10원으로 나누어 떨어지지지 않는 경우 + - [x] [예외 상황] 상품명이 비어있는 경우 + - [x] [예외 상황] 상품 수량이 0 미만인 경우 + + +- [x] [구매] 사용자로부터 투입 금액을 입력받는 기능 + + +- [x] [구매] 사용자로부터 구매할 상품명을 입력받는 기능 + + +- [x] [구매] 입력받은 투입 금액과 상품명을 이용해 구매를 진행하는 기능 + + +- [x] [잔돈 반환] 잔돈을 돌려줄 때 현재 보유한 최소 개수의 동전으로 잔돈을 돌려주는 기능 + - [x] 지폐를 잔돈으로 반환하는 경우는 없다고 가정한다. + - [x] 잔돈을 반환할 수 없는 경우 잔돈으로 반환할 수 있는 금액만 반환한다. + - [x] 남은 금액이 상품의 최저 가격보다 적거나, 모든 상품이 소진된 경우 바로 잔돈을 돌려준다. + - [x] 반환되지 않은 금액은 자판기에 남는다. + + +과제 시작 시간: 21:30 +<br>TDD 종료 : 01:58 (4시간 28분) +<br>MVP 완성 : 02:13 (TDD + 15분) +<br>5시간 종료 : 02:30 +<br>리팩토링 종료 : 03:10 (MVP 완성 + 40분) +<br>총 5시간 40분
Unknown
넵 무작정 구현에 돌입하는게 어려워서, 머릿속으로 계속 생각하면서 구현했습니다!
@@ -165,3 +165,47 @@ public enum Coin { - **Git의 커밋 단위는 앞 단계에서 README.md 파일에 정리한 기능 목록 단위**로 추가한다. - [AngularJS Commit Message Conventions](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) 참고해 commit log를 남긴다. - 과제 진행 및 제출 방법은 [프리코스 과제 제출 문서](https://github.com/woowacourse/woowacourse-docs/tree/master/precourse) 를 참고한다. + +--- + +## 기능 구현 목록 +- [x] [자판기] 사용자로부터 자판기가 보유하고 있는 금액을 입력받는 기능 + + +- [x] [자판기] 자판기가 보유하고 있는 금액만큼 동전을 무작위로 생성하는 기능 + - [x] 투입 금액으로는 동전을 생성하지 않는다. + + +- [x] [자판기] 자판기가 보유하고 있는 동전의 개수를 출력하는 기능 + + +- [x] [자판기] 사용자로부터 상품명, 가격, 수량을 입력받고, 상품을 추가하는 기능 + - [x] [예외 상황] 개별 상품이 대괄호([])로 묶이지 않는 경우 + - [x] [예외 상황] 상품명, 가격, 수량이 쉼표(,)로 구분되지 않는 경우 + - [x] [예외 상황] 상품 가격이 100원부터 시작하지 않고, 10원으로 나누어 떨어지지지 않는 경우 + - [x] [예외 상황] 상품명이 비어있는 경우 + - [x] [예외 상황] 상품 수량이 0 미만인 경우 + + +- [x] [구매] 사용자로부터 투입 금액을 입력받는 기능 + + +- [x] [구매] 사용자로부터 구매할 상품명을 입력받는 기능 + + +- [x] [구매] 입력받은 투입 금액과 상품명을 이용해 구매를 진행하는 기능 + + +- [x] [잔돈 반환] 잔돈을 돌려줄 때 현재 보유한 최소 개수의 동전으로 잔돈을 돌려주는 기능 + - [x] 지폐를 잔돈으로 반환하는 경우는 없다고 가정한다. + - [x] 잔돈을 반환할 수 없는 경우 잔돈으로 반환할 수 있는 금액만 반환한다. + - [x] 남은 금액이 상품의 최저 가격보다 적거나, 모든 상품이 소진된 경우 바로 잔돈을 돌려준다. + - [x] 반환되지 않은 금액은 자판기에 남는다. + + +과제 시작 시간: 21:30 +<br>TDD 종료 : 01:58 (4시간 28분) +<br>MVP 완성 : 02:13 (TDD + 15분) +<br>5시간 종료 : 02:30 +<br>리팩토링 종료 : 03:10 (MVP 완성 + 40분) +<br>총 5시간 40분
Unknown
새벽 코딩 쉽진 않지만, 집중 하나는 잘 되네요🙂
@@ -0,0 +1,25 @@ +package vendingmachine.constant; + +public enum ErrorMessage { + INVALID_COIN_MONEY("[ERROR] 유효하지 않은 동전 금액입니다."), + INVALID_PRODUCT_NAME("[ERROR] 상품명은 비어 있을 수 없습니다."), + INVALID_PRODUCT_PRICE("[ERROR] 상품 가격은 100원부터 시작하며 10원으로 나누어 떨어져야 합니다."), + INVALID_PRODUCT_QUANTITY("[ERROR] 상품 수량은 0 이상이어야 합니다."), + PRODUCT_SOLD_OUT("[ERROR] 해당 상품은 품절되었습니다."), + PRODUCT_IS_NOT_EXIST("[ERROR] 해당 상품이 존재하지 않습니다."), + NOT_ENOUGH_MONEY("[ERROR] 구매 가능한 상품이 없습니다."), + MONEY_SHOULD_BE_NUMBER("[ERROR] 금액은 숫자여야 합니다."), + MONEY_SHOULD_BE_POSITIVE("[ERROR] 금액은 양수여야 합니다."), + INVALID_PRODUCT_FORMAT("[ERROR] 상품의 형식이 올바르지 않습니다."), + ; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
좋은 것 같아요! 피드백 감사합니다:)
@@ -0,0 +1,25 @@ +package vendingmachine.constant; + +public enum ErrorMessage { + INVALID_COIN_MONEY("[ERROR] 유효하지 않은 동전 금액입니다."), + INVALID_PRODUCT_NAME("[ERROR] 상품명은 비어 있을 수 없습니다."), + INVALID_PRODUCT_PRICE("[ERROR] 상품 가격은 100원부터 시작하며 10원으로 나누어 떨어져야 합니다."), + INVALID_PRODUCT_QUANTITY("[ERROR] 상품 수량은 0 이상이어야 합니다."), + PRODUCT_SOLD_OUT("[ERROR] 해당 상품은 품절되었습니다."), + PRODUCT_IS_NOT_EXIST("[ERROR] 해당 상품이 존재하지 않습니다."), + NOT_ENOUGH_MONEY("[ERROR] 구매 가능한 상품이 없습니다."), + MONEY_SHOULD_BE_NUMBER("[ERROR] 금액은 숫자여야 합니다."), + MONEY_SHOULD_BE_POSITIVE("[ERROR] 금액은 양수여야 합니다."), + INVALID_PRODUCT_FORMAT("[ERROR] 상품의 형식이 올바르지 않습니다."), + ; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
조금 더 꼼꼼히 샬펴봐야겠네요 피드백 감사합니다!
@@ -0,0 +1,21 @@ +package vendingmachine.constant; + +public enum OutputMessage { + INPUT_MACHINE_HAVE("자판기가 보유하고 있는 금액을 입력해 주세요."), + MACHINE_HAVE("\n자판기가 보유한 동전"), + INPUT_PRODUCTS("\n상품명과 가격, 수량을 입력해 주세요."), + INPUT_MONEY("\n투입 금액을 입력해 주세요."), + BUYING("\n투입 금액: %d원%n구매할 상품명을 입력해주세요."), + RETURN_CHANGE("\n잔돈 반환:"), + ; + + private final String message; + + OutputMessage(String message) { + this.message = message; + } + + public String format(Object... args) { + return String.format(this.message, args); + } +}
Java
엇 마음이 급했는지 \n과 %n을 혼용했네요! %n 활용해볼게요!!
@@ -0,0 +1,75 @@ +package vendingmachine.controller; + +import vendingmachine.model.domain.Coins; +import vendingmachine.model.domain.Products; +import vendingmachine.model.domain.VendingMachine; +import vendingmachine.model.service.VendingMachineService; +import vendingmachine.view.InputView; +import vendingmachine.view.OutputView; + +public class VendingMachineController { + private final VendingMachineService vendingMachineService; + + public VendingMachineController(VendingMachineService vendingMachineService) { + this.vendingMachineService = vendingMachineService; + } + + public void start() { + OutputView.promptInputMachineHave(); + int money = InputView.vendingMachineHave(); + + VendingMachine vendingMachine = vendingMachineService.getVendingMachine(money); + OutputView.promptMachineHave(vendingMachine); + + getProducts(vendingMachine); + int inputMoney = getInputMoney(); + + inputMoney = getInputMoney(vendingMachine, inputMoney); + getReturnChange(vendingMachine, inputMoney); + } + + private static void getProducts(VendingMachine vendingMachine) { + OutputView.promptInputProducts(); + Products products = InputView.buyProducts(); + vendingMachine.addProducts(products); + } + + private static int getInputMoney() { + OutputView.promptInputMoney(); + return InputView.inputMoney(); + } + + private static int getInputMoney(VendingMachine vendingMachine, int inputMoney) { + while (inputMoney > 0) { + int minPrice = vendingMachine.findMinimumProductPrice(); + if (inputMoney < minPrice) { + break; + } + if (vendingMachine.areProductsSoldOut()) { + break; + } + + OutputView.promptBuying(inputMoney); + String buyProductName = InputView.buyProduct(); + + inputMoney = calculateInputMoney(vendingMachine, inputMoney, buyProductName); + } + return inputMoney; + } + + private static void getReturnChange(VendingMachine vendingMachine, int inputMoney) { + Coins change = vendingMachine.returnChange(inputMoney); + OutputView.promptReturnChange(change); + } + + private static int calculateInputMoney(VendingMachine vendingMachine, int inputMoney, String buyProductName) { + try { + int productPrice = vendingMachine.findProductPrice(buyProductName); + inputMoney -= productPrice; + vendingMachine.purchaseProduct(buyProductName); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + return inputMoney; + } +}
Java
구현하면서 Controller 로직이 복잡하다는 점이 아쉬웠는데, 이 점은 계속해서 개선해봐야겠어요!
@@ -0,0 +1,75 @@ +package vendingmachine.controller; + +import vendingmachine.model.domain.Coins; +import vendingmachine.model.domain.Products; +import vendingmachine.model.domain.VendingMachine; +import vendingmachine.model.service.VendingMachineService; +import vendingmachine.view.InputView; +import vendingmachine.view.OutputView; + +public class VendingMachineController { + private final VendingMachineService vendingMachineService; + + public VendingMachineController(VendingMachineService vendingMachineService) { + this.vendingMachineService = vendingMachineService; + } + + public void start() { + OutputView.promptInputMachineHave(); + int money = InputView.vendingMachineHave(); + + VendingMachine vendingMachine = vendingMachineService.getVendingMachine(money); + OutputView.promptMachineHave(vendingMachine); + + getProducts(vendingMachine); + int inputMoney = getInputMoney(); + + inputMoney = getInputMoney(vendingMachine, inputMoney); + getReturnChange(vendingMachine, inputMoney); + } + + private static void getProducts(VendingMachine vendingMachine) { + OutputView.promptInputProducts(); + Products products = InputView.buyProducts(); + vendingMachine.addProducts(products); + } + + private static int getInputMoney() { + OutputView.promptInputMoney(); + return InputView.inputMoney(); + } + + private static int getInputMoney(VendingMachine vendingMachine, int inputMoney) { + while (inputMoney > 0) { + int minPrice = vendingMachine.findMinimumProductPrice(); + if (inputMoney < minPrice) { + break; + } + if (vendingMachine.areProductsSoldOut()) { + break; + } + + OutputView.promptBuying(inputMoney); + String buyProductName = InputView.buyProduct(); + + inputMoney = calculateInputMoney(vendingMachine, inputMoney, buyProductName); + } + return inputMoney; + } + + private static void getReturnChange(VendingMachine vendingMachine, int inputMoney) { + Coins change = vendingMachine.returnChange(inputMoney); + OutputView.promptReturnChange(change); + } + + private static int calculateInputMoney(VendingMachine vendingMachine, int inputMoney, String buyProductName) { + try { + int productPrice = vendingMachine.findProductPrice(buyProductName); + inputMoney -= productPrice; + vendingMachine.purchaseProduct(buyProductName); + } catch (IllegalArgumentException e) { + OutputView.promptErrorMessage(e.getMessage()); + } + return inputMoney; + } +}
Java
말씀하신 부분 다시 살펴보니 도메인에 위임하는게 더 좋겠네요!
@@ -0,0 +1,59 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_NAME; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_PRICE; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_QUANTITY; +import static vendingmachine.constant.ErrorMessage.PRODUCT_SOLD_OUT; +import static vendingmachine.constant.NumberConstant.*; + +public class Product { + private final String productName; + private final int price; + private int quantity; + + public Product(String productName, int price, int quantity) { + validateProductName(productName); + validatePrice(price); + validateQuantity(quantity); + this.productName = productName; + this.price = price; + this.quantity = quantity; + } + + private void validateProductName(String productName) { + if (productName == null || productName.isEmpty()) { + throw new IllegalArgumentException(INVALID_PRODUCT_NAME.getMessage()); + } + } + + private void validatePrice(int price) { + if (price < MINIMUM_MONEY_PRICE || price % DIVIDE_MONEY_UNIT != 0) { + throw new IllegalArgumentException(INVALID_PRODUCT_PRICE.getMessage()); + } + } + + private void validateQuantity(int quantity) { + if (quantity < 0) { + throw new IllegalArgumentException(INVALID_PRODUCT_QUANTITY.getMessage()); + } + } + + public int getPrice() { + return price; + } + + public boolean isNameSame(String inputProductName) { + return this.productName.equals(inputProductName); + } + + public boolean isQuantityZero() { + return this.quantity == 0; + } + + public void decreaseQuantity() { + if (quantity <= 0) { + throw new IllegalArgumentException(PRODUCT_SOLD_OUT.getMessage()); + } + this.quantity -= 1; + } +}
Java
말씀해주신 부분처럼 재고 수량 조절을 위해서 final 키워드를 생략했습니다!
@@ -0,0 +1,43 @@ +package vendingmachine.model.domain; + +import static vendingmachine.constant.ErrorMessage.PRODUCT_IS_NOT_EXIST; +import static vendingmachine.constant.ErrorMessage.NOT_ENOUGH_MONEY; + +import java.util.List; + +public class Products { + private final List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public int findPriceByProductName(String productName) { + return products.stream() + .filter(product -> product.isNameSame(productName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(PRODUCT_IS_NOT_EXIST.getMessage())) + .getPrice(); + } + + public int findMinimumPrice() { + return products.stream() + .filter(product -> !product.isQuantityZero()) + .mapToInt(Product::getPrice) + .min() + .orElseThrow(() -> new IllegalArgumentException(NOT_ENOUGH_MONEY.getMessage())); + } + + public boolean areSoldOut() { + return products.stream().allMatch(Product::isQuantityZero); + } + + public void decreaseProductQuantity(String productName) { + Product product = products.stream() + .filter(name -> name.isNameSame(productName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(PRODUCT_IS_NOT_EXIST.getMessage())); + + product.decreaseQuantity(); + } +}
Java
감사합니다!!:)
@@ -0,0 +1,73 @@ +package vendingmachine.util; + +import static vendingmachine.constant.ErrorMessage.MONEY_SHOULD_BE_NUMBER; +import static vendingmachine.constant.ErrorMessage.MONEY_SHOULD_BE_POSITIVE; +import static vendingmachine.constant.ErrorMessage.INVALID_PRODUCT_FORMAT; +import static vendingmachine.constant.NumberConstant.*; + +import java.util.ArrayList; +import java.util.List; + +import vendingmachine.model.domain.Product; +import vendingmachine.model.domain.Products; + +public class Parser { + private static final String SEMICOLON = ";"; + private static final String LEFT_BRACKET = "["; + private static final String RIGHT_BRACKET = "]"; + private static final String COMMA = ","; + + public static int parseInteger(String input) { + try { + int money = Integer.parseInt(input); + validateNegative(money); + return money; + } catch (NumberFormatException e) { + throw new IllegalArgumentException(MONEY_SHOULD_BE_NUMBER.getMessage()); + } + } + + private static void validateNegative(int money) { + if(money < 0) { + throw new IllegalArgumentException(MONEY_SHOULD_BE_POSITIVE.getMessage()); + } + } + + public static Products parseProducts(String inputProducts) { + List<Product> products = parseProductList(inputProducts); + return new Products(products); + } + + private static List<Product> parseProductList(String inputProducts) { + String[] splitProducts = inputProducts.split(SEMICOLON); + List<Product> products = new ArrayList<>(); + + for (String splitProduct : splitProducts) { + validateProductFormat(splitProduct); + Product product = parseProduct(splitProduct); + products.add(product); + } + return products; + } + + private static void validateProductFormat(String productInfo) { + if (!productInfo.startsWith(LEFT_BRACKET) || !productInfo.endsWith(RIGHT_BRACKET)) { + throw new IllegalArgumentException(INVALID_PRODUCT_FORMAT.getMessage()); + } + } + + private static Product parseProduct(String productInfo) { + String content = productInfo.substring(1, productInfo.length() - 1); + String[] splitProductInfo = content.split(COMMA); + + if (splitProductInfo.length != PRODUCTS_LENGTH) { + throw new IllegalArgumentException(INVALID_PRODUCT_FORMAT.getMessage()); + } + + String name = splitProductInfo[0].trim(); + int price = Integer.parseInt(splitProductInfo[1].trim()); + int quantity = Integer.parseInt(splitProductInfo[2].trim()); + + return new Product(name, price, quantity); + } +}
Java
마음이 급하다보니 더 쉬운 방법을 택했던 것 같아요! 정규표현식을 사용해도 좋을 것 같네요:)
@@ -0,0 +1,36 @@ +package vendingmachine.model.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class ProductTest { + @Test + @DisplayName("상품 가격이 100원부터 시작하지 않는 경우 예외가 발생한다.") + void 상품_가격이_100원부터_시작하지_않는_경우_예외_발생() { + assertThatThrownBy(() -> new Product("콜라", 90, 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("상품 가격이 10원으로 나누어 떨어지지지 않는 경우 예외가 발생한다.") + void 상품_가격이_10원으로_나누어_떨어지지_않는_경우_예외_발생() { + assertThatThrownBy(() -> new Product("콜라", 9, 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("상품명이 비어있는 경 예외가 발생한다.") + void 상품명이_비어있는_경우_예외_발생() { + assertThatThrownBy(() -> new Product("", 1000, 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("상품 수량이 0 미만인 경우 예외가 발생한다.") + void 상품_수량이_0_미만인_경우_예외_발생() { + assertThatThrownBy(() -> new Product("콜라", 1000, -1)) + .isInstanceOf(IllegalArgumentException.class); + } +}
Java
넵 추가로 테스트 코드 리팩토링까지는 생각 못했네요,,😅
@@ -0,0 +1,25 @@ +package store.constants; + +public enum ErrorMessage { + + PRODUCT_BUY_FORM_ERROR("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요."), + NO_EXSIST_PRODUCT_ERROR("존재하지 않는 상품 입니다. 다시 입력해 주세요"), + NOT_ENOUGH_QUANTITY_ERROR("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."), + NOT_POSITIVE_INPUT_ERROR("구입할 수량은 1 이상이어야 합니다. 다시 입력해 주세요."), + ETC_INPUT_ERROR("잘못된 입력입니다. 다시 입력해주세요."), + DUPLICATE_PRODUCT_INPUT_ERROR("같은 상품은 한 번에 여러개 구입합니다. 다시 입력해 주세요."), + PRODUCT_ERROR("잘못된 재고입니다."), + SYSTEM_ERROR("실행 오류 입니다."); + + private final String prefix = "[ERROR] "; + private final String postfix = "\n"; + private final String message; + + ErrorMessage(String message) { + this.message = prefix + message + postfix; + } + + public String getMessage() { + return message; + } +}
Java
prefix와 postfix는 공통된 부분이어서 static으로 만드셔도 좋을 거 같아요!
@@ -0,0 +1,19 @@ +package store.constants; + +public enum StringConstants { + + ZERO_STRING("0"), + NO_PROMOTION("null"), + YES("Y"), + NO("N"); + + private final String string; + + StringConstants(String string) { + this.string = string; + } + + public String getString() { + return string; + } +}
Java
enum으로 잘 묶으셨네요! YES와 NO를 제외한 다른 상수는 관련성이 없어 보이는데, 따로 enum으로 묶으신 이유가 궁금합니다!
@@ -0,0 +1,82 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import store.constants.ErrorMessage; +import store.constants.StringConstants; + +public class Products { + + private List<String> productNames = new ArrayList<>(); + private final Map<String, Product> promotionProducts = new LinkedHashMap<>(); + private final Map<String, Product> regularProducts = new LinkedHashMap<>(); + + public Products(List<Product> allProducts) { + for (Product product : allProducts) { + addProduct(product); + } + } + + public List<String> getProductNames() { + return productNames; + } + + public Map<String, Product> getPromotionProducts() { + return promotionProducts; + } + + public Map<String, Product> getRegularProducts() { + return regularProducts; + } + + public void setProductNames(List<String> productNames) { + this.productNames = productNames; + } + + private void addProduct(Product product) { + if (product.hasPromotion()) { + promotionProducts.put(product.getName(), product); + } + if (!product.hasPromotion()) { + regularProducts.put(product.getName(), product); + } + } + + public void addNoRegularProducts() { + for (String productName : productNames) { + if (!regularProducts.containsKey(productName)) { + Product product = promotionProducts.get(productName); + regularProducts.put(productName, new Product(productName, String.valueOf(product.getPrice()), + StringConstants.ZERO_STRING.getString(), StringConstants.NO_PROMOTION.getString())); + } + } + } + + public boolean hasProduct(String productName) { + if (!promotionProducts.containsKey(productName) && !regularProducts.containsKey(productName)) { + throw new IllegalArgumentException(ErrorMessage.NO_EXSIST_PRODUCT_ERROR.getMessage()); + } + return promotionProducts.containsKey(productName) || regularProducts.containsKey(productName); + } + + public void updatePromotionProductQuantity(String name, int quantity) { + Product product = promotionProducts.get(name); + product.updateQuantity(quantity); + } + + public void updateRegularProductQuantity(String name, int quantity) { + Product product = regularProducts.get(name); + product.updateQuantity(quantity); + } + + public boolean hasSufficientStock(String productName, int quantity) { + int totalQuantity = regularProducts.get(productName).getQuantity(); + if (promotionProducts.containsKey(productName)) { + totalQuantity += promotionProducts.get(productName).getQuantity(); + } + + return totalQuantity >= quantity; + } +}
Java
프로모션 상품과 일반 상품을 잘 나누셨네요! `hasPromotion`이 중복되어서 아래와 같이 하는 건 어떨까요? ```java if (product.hasPromotion()) { promotionProducts.put(product.getName(), product); return; } regularProducts.put(product.getName(), product); ```
@@ -0,0 +1,83 @@ +package store.domain; + +import java.util.List; +import store.constants.StringConstants; + +public class TotalPrice { + + private static final int MAX_MEMBERSHIP_SALE = 8000; + private int totalCount = 0; + private int totalPrice = 0; + private int promotionPrice = 0; + private double memberShipPrice = 0; + + public TotalPrice(List<Purchase> purchases, Products products) { + getTotalPrice(purchases, products); + } + + public int getTotalCount() { + return totalCount; + } + + public int getPromotionPrice() { + return promotionPrice; + } + + public int getTotalPrice() { + return totalPrice; + } + + public void setPromotionPrice(int promotionPrice) { + this.promotionPrice = promotionPrice; + } + + public double getMemberShipPrice() { + return memberShipPrice; + } + + public void setMemberShipPrice(double memberShipPrice) { + this.memberShipPrice = memberShipPrice; + } + + private void getTotalPrice(List<Purchase> purchases, Products products) { + for (Purchase purchase : purchases) { + int price = products.getRegularProducts().get(purchase.getName()).getPrice(); + this.totalPrice += purchase.getQuantity() * price; + this.totalCount += purchase.getQuantity(); + } + } + + public int getPromotionSalePrice(List<Purchase> purchases, Promotions promotions, Products products) { + int promotionPrice = 0; + for (Purchase purchase : purchases) { + if (purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + continue; + } + Promotion promotion = promotions.getPromotions().get(purchase.getPromotion()); + int price = products.getRegularProducts().get(purchase.getName()).getPrice(); + promotionPrice += price * promotion.freeCount(purchase.getQuantity()); + } + return promotionPrice; + } + + public double getMembershipSalePrice(List<Purchase> purchases, Products products) { + int afterPromotionSalePrice = totalPrice - getPurchasePromotionPrice(purchases, products); + double membershipPrice = afterPromotionSalePrice * 0.3; + + if (membershipPrice > MAX_MEMBERSHIP_SALE) { + return MAX_MEMBERSHIP_SALE; + } + return membershipPrice; + } + + private static int getPurchasePromotionPrice(List<Purchase> purchases, Products products) { + int promotionPrice = 0; + for (Purchase purchase : purchases) { + if (!purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + Product product = products.getRegularProducts().get(purchase.getName()); + promotionPrice += purchase.getQuantity() * product.getPrice(); + } + } + return promotionPrice; + } +}
Java
`0.3`도 상수화하시면, 의미가 더 명확해질 거 같아요!
@@ -0,0 +1,21 @@ +package store.service; + +import store.constants.StringConstants; +import store.domain.Cart; +import store.domain.Products; +import store.domain.Purchase; + +public class CartService { + + public Products productsReduce(Products products, Cart cart) { + for (Purchase purchase : cart.getItems()) { + if (purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + products.getRegularProducts().get(purchase.getName()).updateQuantity(purchase.getQuantity()); + } + if (!purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + products.getPromotionProducts().get(purchase.getName()).updateQuantity(purchase.getQuantity()); + } + } + return products; + } +}
Java
이 부분이 계속 반복되어서, `purchase.hasPromotion`으로 만드시면 더 가독성이 좋아질 거 같아요!
@@ -0,0 +1,30 @@ +package store.utils; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class FileRead { + + public static List<String> readFile(String fileName) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(fileName)); + List<String> contents = readFileContents(br); + + br.close(); + contents.removeFirst(); + return contents; + } + + private static List<String> readFileContents(BufferedReader br) throws IOException { + List<String> contents = new ArrayList<>(); + while (true) { + String line = br.readLine(); + if (line == null) break; + contents.add(line); + } + return contents; + } +}
Java
파일 읽어오는 부분을 잘 작성하셨네요! BufferedReader의 `lines()`메서드도 활용해보시면 좋을 거 같아요!
@@ -0,0 +1,62 @@ +package store.domain; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import store.constants.ErrorMessage; + +class CartTest { + + private Cart cart; + private List<Purchase> purchases; + + @BeforeEach + void setUp() { + purchases = new ArrayList<>(); + purchases.add(new Purchase("콜라", 3, "탄산2+1")); + purchases.add(new Purchase("사이다", 5, "null")); + cart = new Cart(purchases); + } + + @Test + void 장바구니_생성_테스트() { + // given + List<Purchase> expectedItems = purchases; + + // then + assertThat(cart.getItems().size()).isEqualTo(expectedItems.size()); + assertThat(cart.getItems()).containsAll(expectedItems); + } + + @Test + void 중복_아이템_추가_예외_테스트() { + // given + purchases.add(new Purchase("콜라", 2, "탄산2+1")); + + // when & then + assertThatThrownBy(() -> new Cart(purchases)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.DUPLICATE_PRODUCT_INPUT_ERROR.getMessage()); + } + + @Test + void 아이템_병합_테스트() { + // given + List<Purchase> additionalPurchases = new ArrayList<>(cart.getItems());; + additionalPurchases.add(new Purchase("콜라", 2, "탄산2+1")); + additionalPurchases.add(new Purchase("물", 4, "null")); + + // when + Map<String, Purchase> mergedItems = cart.mergeItems(additionalPurchases); + + // then + assertThat(mergedItems.get("콜라").getQuantity()).isEqualTo(5); // 기존 3 + 추가 2 + assertThat(mergedItems.containsKey("물")).isTrue(); + assertThat(mergedItems.get("물").getQuantity()).isEqualTo(4); + } +} \ No newline at end of file
Java
꼼꼼한 테스트가 인상적이네요!
@@ -0,0 +1,29 @@ +package store.constants; + +public enum OutputPrompts { + WELCOME_MESSAGE("\n안녕하세요. W편의점입니다.\n" + + "현재 보유하고 있는 상품입니다.\n"), + + PRODUCTS_HAVE_PROMOTION("- %s %s원 %s %s"), + PRODUCTS_NO_PROMOTION("- %s %s원 %s"), + RECEIPT_HEADER("\n==============W 편의점================\n" + + "상품명\t\t수량\t금액"), + RECEIPT_PRODUCTS("%s\t\t%d\t%s\n"), + RECEIPT_PROMOTION_HEADER("=============증\t정==============="), + RECEIPT_PROMOTION_PRODUCTS("%s\t\t%d\n"), + RECEIPT_TOTAL_PRICE_HEADER("===================================="), + RECEIPT_TOTAL_PRICE("총구매액\t\t%d\t%s\n"), + RECEIPT_PROMOTION_DISCOUNT("행사할인\t\t\t-%s\n"), + RECEIPT_MEMBERSHIP_DISCOUNT("멤버십할인\t\t\t-%s\n"), + RECEIPT_FINAL_PRICE("내실돈\t\t\t %s\n\n"); + + private final String prompts; + + OutputPrompts(String prompts) { + this.prompts = prompts; + } + + public String getPrompts() { + return prompts; + } +}
Java
어떤 상수에서 enum 타입을 사용하시는지 기준이 궁금합니다!
@@ -0,0 +1,84 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import java.util.Map; +import store.constants.ErrorMessage; +import store.constants.StringConstants; +import store.domain.Cart; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.Purchase; +import store.domain.TotalPrice; +import store.service.CartService; +import store.service.InitService; +import store.service.PromotionService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private Products products; + private Promotions promotions; + private Cart cart; + + private final InitService initService = new InitService(); + private final PromotionService promotionService = new PromotionService(); + private final CartService cartService = new CartService(); + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + String next = StringConstants.YES.getString(); + initStock(); + while(next.equals(StringConstants.YES.getString())) { + start(); + checkProducts(); + result(); + products = cartService.productsReduce(products, cart); + next = inputView.checkMorePurchase(); + } + Console.close(); + } + + private void initStock() { + try { + products = initService.saveInitProducts(); + promotions = initService.saveInitPromotions(); + } catch (IOException e) { + System.out.println(ErrorMessage.SYSTEM_ERROR.getMessage()); + } + } + + private void start() { + outputView.productsOutput(this.products); + cart = inputView.readItem(products); + } + + private void checkProducts() { + for (Purchase purchase : cart.getItems()) { + promotionService.setPromotion(purchase, products); + if (!purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + promotionService.promotionsAll(purchase, promotions, products, cart); + } + } + addCart(); + } + + private void addCart() { + promotionService.applyAddPurchaseToCart(cart); + } + + private void result() { + Map<String, Purchase> items = cart.mergeItems(cart.getItems()); + TotalPrice totalPrice = new TotalPrice(cart.getItems(), products); + + totalPrice.setPromotionPrice(totalPrice.getPromotionSalePrice(cart.getItems(), promotions, products)); + String answer = inputView.checkMemberShipSale(); + + if (answer.equals(StringConstants.YES.getString())) { + totalPrice.setMemberShipPrice(totalPrice.getMembershipSalePrice(cart.getItems(), products)); + } + outputView.printReceipt(cart, products, promotions, items, totalPrice); + } +}
Java
내부에서 생성하는것보다 확장성을 위해서 생성자 주입 방식을 활용해보는건 어떨까요?
@@ -0,0 +1,56 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import store.constants.ErrorMessage; + +public class Cart { + + private List<Purchase> items; + + public Cart(List<Purchase> items) { + this.items = new ArrayList<>(); + addPurchase(new ArrayList<>(items)); + } + + public List<Purchase> getItems() { + return items; + } + + private void addPurchase(List<Purchase> purchases) { + for (Purchase purchase : purchases) { + if(validateItem(purchase)) { + this.items.add(purchase); + } + } + } + + private boolean validateItem(Purchase purchase) { + if (items.stream().anyMatch(item -> item.getName().equals(purchase.getName()))) { + throw new IllegalArgumentException(ErrorMessage.DUPLICATE_PRODUCT_INPUT_ERROR.getMessage()); + } + return true; + } + + public Map<String, Purchase> mergeItems(List<Purchase> purchases) { + Map<String, Purchase> itemsMap = new HashMap<>(); + for (Purchase purchase : purchases) { + addItems(purchase, itemsMap); + } + return itemsMap; + } + + private static void addItems(Purchase purchase, Map<String, Purchase> itemsMap) { + Purchase existingItem = itemsMap.get(purchase.getName()); + + if (existingItem != null) { + existingItem.setQuantity(existingItem.getQuantity() + purchase.getQuantity()); + } + if (existingItem == null) { + Purchase item = new Purchase(purchase.getName(), purchase.getQuantity(), purchase.getPromotion()); + itemsMap.put(item.getName(), item); + } + } +}
Java
현재 itemsMap 파라미터에 put으로 내부에서 변경을 가하고 있습니다. 저는 이런 로직을 되도록 피하려고 합니다! 그 이유는 현재는 혼자 개발을 해서 로직을 이해하고 있지만 다른 분들과 협업을 해서 처음 이 클래스를 보고 사용하신다면 itemsMap이 수정이 되는지를 모르기 때문에 사용자는 의도치 않은 변경이 일어나 오류를 받을 수 있을거라고 생각합니다! 그래서 만약 이렇게 파라미터의 값을 변경하는 일이 있는 경우 주석이나 메서드 명으로 알려주는 것이 좋다고 생각합니다! 저의 개인적인 생각이니 참고만 부탁드릴게요 ㅎㅎ 😊
@@ -0,0 +1,49 @@ +package store.service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.utils.FileRead; +import store.utils.Split; + +public class InitService { + + private static final String PRODUCTS_FILE_NAME = "src/main/resources/products.md"; + private static final String PROMOTIONS_FILE_NAME = "src/main/resources/promotions.md"; + + public Products saveInitProducts() throws IOException { + List<String> fileContent = FileRead.readFile(PRODUCTS_FILE_NAME); + List<Product> productList = new ArrayList<>(); + Set<String> productNames = new LinkedHashSet<>(); + + saveProducts(fileContent, productNames, productList); + Products products = new Products(productList); + products.setProductNames(new ArrayList<>(productNames)); + products.addNoRegularProducts(); + return products; + } + + private static void saveProducts(List<String> fileContent, Set<String> productNames, List<Product> productList) { + for (String content : fileContent) { + List<String> split = Split.commaSpliter(content); + productNames.add(split.get(0)); + productList.add(new Product(split.get(0), split.get(1), split.get(2), split.get(3))); + } + } + + public Promotions saveInitPromotions() throws IOException { + List<String> fileContent = FileRead.readFile(PROMOTIONS_FILE_NAME); + List<Promotion> promotions = new ArrayList<>(); + for (String content : fileContent) { + List<String> split = Split.commaSpliter(content); + promotions.add(new Promotion(split.get(0), split.get(1), split.get(2), split.get(3), split.get(4))); + } + return new Promotions(promotions); + } +}
Java
split의 인덱스 값을 상수화하면 좋을거같습니다! 저도 이번에는 상수화를 안했습니다..ㅎ 하지만 다른 분들의 코드를 보고 이 부분을 상수화하면 split의 각 인덱스가 뭘 의미하는지 한눈에 파악하기 쉬워서 앞으로 인덱스 값도 상수화를 하려고 합니다! 민경님 생각은 어떠신가요?
@@ -0,0 +1,88 @@ +package store.service; + +import java.util.ArrayList; +import java.util.List; +import store.constants.StringConstants; +import store.domain.Cart; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.domain.Purchase; +import store.view.InputView; + +public class PromotionService { + + private final InputView inputView = new InputView(); + private static final List<Purchase> addRegularPurchase = new ArrayList<>(); + + public void setPromotion(Purchase purchase, Products products) { + Product product = products.getPromotionProducts().get(purchase.getName()); + if (product != null) { + purchase.setPromotion(product.getPromotion()); + } + } + + public void promotionsAll(Purchase purchase, Promotions promotions, Products products, Cart cart) { + Promotion promotion = promotions.getPromotions().get(purchase.getPromotion()); + if (promotion == null || !promotion.isActive()) { + purchase.setPromotion(StringConstants.NO_PROMOTION.getString()); + return; + } + + adjustPromotionCount(purchase, promotion, cart); + handleInsufficientStock(purchase, cart, products, promotion); + } + + private void adjustPromotionCount(Purchase purchase, Promotion promotion, Cart cart) { + if (!promotion.correctCount(purchase.getQuantity())) { + String answer = inputView.checkPromotionCountAdd(purchase); + adjustPurchaseByAnswer(purchase, promotion, answer); + } + } + + private static void adjustPurchaseByAnswer(Purchase purchase, Promotion promotion, String answer) { + if (answer.equals(StringConstants.YES.getString())) { + int more = promotion.addCount(purchase.getQuantity()); + purchase.setQuantity(more); + } + if (answer.equals(StringConstants.NO.getString())) { + int extraCount = purchase.getQuantity() - promotion.extraCount(purchase.getQuantity()); + addRegularPurchase.add(new Purchase(purchase.getName(), promotion.extraCount(purchase.getQuantity()), StringConstants.NO_PROMOTION.getString())); + purchase.setQuantity(extraCount); + } + } + + private void handleInsufficientStock(Purchase purchase, Cart cart, Products products, Promotion promotion) { + Product product = products.getPromotionProducts().get(purchase.getName()); + if (product.getQuantity() < purchase.getQuantity()) { + int extraCount = purchase.getQuantity() - (product.getQuantity() - promotion.extraCount(product.getQuantity())); + String answer = inputView.checkPromotionSaleNotAccept(purchase, extraCount); + handleByAnswerInsufficientStock(purchase, cart, promotion, product, answer, extraCount); + } + } + + private static void handleByAnswerInsufficientStock(Purchase purchase, Cart cart, Promotion promotion, Product product, String answer, + int extraCount) { + int promotionQuantity = purchase.getQuantity() - extraCount; + + if (answer.equals(StringConstants.YES.getString())) { + purchase.setQuantity(promotionQuantity); + addRegularPurchase.add(new Purchase(purchase.getName(), extraCount, StringConstants.NO_PROMOTION.getString())); + } + if (answer.equals(StringConstants.NO.getString())) { + purchase.setQuantity(promotionQuantity); + } + } + + public void applyAddPurchaseToCart(Cart cart) { + if (!addRegularPurchase.isEmpty()) { + cart.getItems().addAll(addRegularPurchase); + addRegularPurchase.clear(); + } + } + + public static void clearAddCart() { + addRegularPurchase.clear(); + } +}
Java
MVC패턴에서 컨트롤러의 역할은 서비스와 view를 연결해주는 역할을 합니다. 하지만 지금처럼 서비스가 view를 직접적으로 의존하게 된다면 컨트롤러의 역할이 모호해진다고 생각됩니다!
@@ -0,0 +1,19 @@ +package store.constants; + +public enum StringConstants { + + ZERO_STRING("0"), + NO_PROMOTION("null"), + YES("Y"), + NO("N"); + + private final String string; + + StringConstants(String string) { + this.string = string; + } + + public String getString() { + return string; + } +}
Java
zero_string은 어떤 상황에 쓰이는지 정확히 이름을 보고 파악하기 힘든거 같습니다! 아래 처럼 no_promotion 같은 경우는 프로모션이 없을 때 사용하는지 알아서 편했습니다! 아래 상수화 하신거처럼 의미있는 네이밍하시면 좋을거같습니다 ㅎㅎ
@@ -0,0 +1,82 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import store.constants.ErrorMessage; +import store.constants.StringConstants; + +public class Products { + + private List<String> productNames = new ArrayList<>(); + private final Map<String, Product> promotionProducts = new LinkedHashMap<>(); + private final Map<String, Product> regularProducts = new LinkedHashMap<>(); + + public Products(List<Product> allProducts) { + for (Product product : allProducts) { + addProduct(product); + } + } + + public List<String> getProductNames() { + return productNames; + } + + public Map<String, Product> getPromotionProducts() { + return promotionProducts; + } + + public Map<String, Product> getRegularProducts() { + return regularProducts; + } + + public void setProductNames(List<String> productNames) { + this.productNames = productNames; + } + + private void addProduct(Product product) { + if (product.hasPromotion()) { + promotionProducts.put(product.getName(), product); + } + if (!product.hasPromotion()) { + regularProducts.put(product.getName(), product); + } + } + + public void addNoRegularProducts() { + for (String productName : productNames) { + if (!regularProducts.containsKey(productName)) { + Product product = promotionProducts.get(productName); + regularProducts.put(productName, new Product(productName, String.valueOf(product.getPrice()), + StringConstants.ZERO_STRING.getString(), StringConstants.NO_PROMOTION.getString())); + } + } + } + + public boolean hasProduct(String productName) { + if (!promotionProducts.containsKey(productName) && !regularProducts.containsKey(productName)) { + throw new IllegalArgumentException(ErrorMessage.NO_EXSIST_PRODUCT_ERROR.getMessage()); + } + return promotionProducts.containsKey(productName) || regularProducts.containsKey(productName); + } + + public void updatePromotionProductQuantity(String name, int quantity) { + Product product = promotionProducts.get(name); + product.updateQuantity(quantity); + } + + public void updateRegularProductQuantity(String name, int quantity) { + Product product = regularProducts.get(name); + product.updateQuantity(quantity); + } + + public boolean hasSufficientStock(String productName, int quantity) { + int totalQuantity = regularProducts.get(productName).getQuantity(); + if (promotionProducts.containsKey(productName)) { + totalQuantity += promotionProducts.get(productName).getQuantity(); + } + + return totalQuantity >= quantity; + } +}
Java
외부로 리스트, 맵처럼 컬렉션을 반환하면 final로 설정한다해도 add, remove 메서드들로 수정을 가할 수가 있습니다. 만약 수정할 의도가 없으시다면 복사를 하여 외부로 넘기는 방법이 좋을거 같습니다! 저는 주로 Collections.unmodifiableMap(promotionProducts); 이렇게 수정을 가하면 예외가 던져지도록 설정합니다!
@@ -0,0 +1,61 @@ +package store.validator; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.constants.ErrorMessage; +import store.constants.StringConstants; +import store.domain.Cart; +import store.domain.Products; +import store.domain.Purchase; +import store.utils.Split; + +public class InputValidator { + + private static final String PATTERN = "^[a-zA-Z가-힣0-9\\-\\[\\]]+$"; + private static final String VALID_PATTERN = "\\[[a-zA-Z가-힣0-9]+-[0-9]+\\]"; + + public static void validateInput(String input) { + List<String> items = Split.commaSpliter(input); + + for (String item : items) { + if (!item.matches(VALID_PATTERN)) { + throw new IllegalArgumentException(ErrorMessage.PRODUCT_BUY_FORM_ERROR.getMessage()); + } + } + } + + public static void validatePurchaseForm(List<String> inputs) { + for (String input : inputs) { + Pattern compiledPattern = Pattern.compile(PATTERN); + Matcher matcher = compiledPattern.matcher(input); + + if (!matcher.matches()) { + throw new IllegalArgumentException(ErrorMessage.PRODUCT_BUY_FORM_ERROR.getMessage()); + } + } + } + + public static void validateHasProduct(Cart cart, Products products) { + for (Purchase purchase : cart.getItems()) { + if (!products.hasProduct(purchase.getName())) { + throw new IllegalArgumentException(ErrorMessage.NO_EXSIST_PRODUCT_ERROR.getMessage()); + } + } + } + + public static void validateSufficientStock(Cart cart, Products products) { + for (Purchase purchase : cart.getItems()) { + if (!products.hasSufficientStock(purchase.getName(), purchase.getQuantity())) { + throw new IllegalArgumentException(ErrorMessage.NOT_ENOUGH_QUANTITY_ERROR.getMessage()); + } + } + } + + public static void validateAnswer(String answer) { + answer = answer.toUpperCase(); + if (!answer.equals(StringConstants.YES.getString()) && !answer.equals(StringConstants.NO.getString())) { + throw new IllegalArgumentException(ErrorMessage.ETC_INPUT_ERROR.getMessage()); + } + } +}
Java
검증을 한 곳에 모아두는 이유가 있나요??
@@ -0,0 +1,62 @@ +package store.domain; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import store.constants.ErrorMessage; + +class CartTest { + + private Cart cart; + private List<Purchase> purchases; + + @BeforeEach + void setUp() { + purchases = new ArrayList<>(); + purchases.add(new Purchase("콜라", 3, "탄산2+1")); + purchases.add(new Purchase("사이다", 5, "null")); + cart = new Cart(purchases); + } + + @Test + void 장바구니_생성_테스트() { + // given + List<Purchase> expectedItems = purchases; + + // then + assertThat(cart.getItems().size()).isEqualTo(expectedItems.size()); + assertThat(cart.getItems()).containsAll(expectedItems); + } + + @Test + void 중복_아이템_추가_예외_테스트() { + // given + purchases.add(new Purchase("콜라", 2, "탄산2+1")); + + // when & then + assertThatThrownBy(() -> new Cart(purchases)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.DUPLICATE_PRODUCT_INPUT_ERROR.getMessage()); + } + + @Test + void 아이템_병합_테스트() { + // given + List<Purchase> additionalPurchases = new ArrayList<>(cart.getItems());; + additionalPurchases.add(new Purchase("콜라", 2, "탄산2+1")); + additionalPurchases.add(new Purchase("물", 4, "null")); + + // when + Map<String, Purchase> mergedItems = cart.mergeItems(additionalPurchases); + + // then + assertThat(mergedItems.get("콜라").getQuantity()).isEqualTo(5); // 기존 3 + 추가 2 + assertThat(mergedItems.containsKey("물")).isTrue(); + assertThat(mergedItems.get("물").getQuantity()).isEqualTo(4); + } +} \ No newline at end of file
Java
given when then 덕분에 테스트 코드 읽기가 쉽네요!👍
@@ -1,19 +1,33 @@ package store; +import camp.nextstep.edu.missionutils.Console; import camp.nextstep.edu.missionutils.test.NsTest; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import store.constants.ErrorMessage; +import store.constants.StringConstants; import static camp.nextstep.edu.missionutils.test.Assertions.assertNowTest; import static camp.nextstep.edu.missionutils.test.Assertions.assertSimpleTest; import static org.assertj.core.api.Assertions.assertThat; +import static store.constants.StringConstants.NO; +import static store.constants.StringConstants.YES; class ApplicationTest extends NsTest { + + @AfterEach + void consoleClose() { + Console.close(); + } + @Test void 파일에_있는_상품_목록_출력() { assertSimpleTest(() -> { - run("[물-1]", "N", "N"); + run("[물-1]", NO.getString(), NO.getString()); assertThat(output()).contains( "- 콜라 1,000원 10개 탄산2+1", "- 콜라 1,000원 10개", @@ -40,24 +54,133 @@ class ApplicationTest extends NsTest { @Test void 여러_개의_일반_상품_구매() { assertSimpleTest(() -> { - run("[비타민워터-3],[물-2],[정식도시락-2]", "N", "N"); + run("[비타민워터-3],[물-2],[정식도시락-2]", NO.getString(), NO.getString()); assertThat(output().replaceAll("\\s", "")).contains("내실돈18,300"); }); } @Test void 기간에_해당하지_않는_프로모션_적용() { assertNowTest(() -> { - run("[감자칩-2]", "N", "N"); + run("[감자칩-2]", NO.getString(), NO.getString()); assertThat(output().replaceAll("\\s", "")).contains("내실돈3,000"); }, LocalDate.of(2024, 2, 1).atStartOfDay()); } @Test void 예외_테스트() { assertSimpleTest(() -> { - runException("[컵라면-12]", "N", "N"); - assertThat(output()).contains("[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."); + runException("[컵라면-12]", NO.getString(), NO.getString()); + assertThat(output()).contains(ErrorMessage.NOT_ENOUGH_QUANTITY_ERROR.getMessage()); + }); + } + + //구매항목 관련 테스트 + @ParameterizedTest + @ValueSource(strings = {"콜라-5", "[콜라-5],[콜라-5]", "[콜라,5]", "[한우-2]", "[콜라-100]"}) + void 구매항목_입력_예외_테스트(String input) { + //when, then + assertSimpleTest(() -> { + try { + runException(input, NO.getString(), NO.getString()); + assertThat(output()).contains(ErrorMessage.PRODUCT_BUY_FORM_ERROR.getMessage()); + } finally { + Console.close(); + } + }); + } + + //여부 확인 관련 테스트 + @Test + void 여부_확인_예외_테스트() { + assertSimpleTest(() -> { + runException("[콜라-5]", "ㅇ", NO.getString()); + assertThat(output()).contains(ErrorMessage.ETC_INPUT_ERROR.getMessage()); + }); + } + + //프로모션 관리 관련 테스트 + @Test + void 프로모션_조건_충족_혜택_적용_테스트() { + assertSimpleTest(() -> { + runException("[콜라-3]", NO.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")).contains("내실돈2,000"); + }); + } + + @Test + void 프로모션_조건_미충족_혜택_미적용_테스트() { + assertSimpleTest(() -> { + runException("[콜라-1]", NO.getString(), NO.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")).contains("내실돈1,000"); + }); + } + + @Test + void 프로모션_기간_만료_혜택_미적용_테스트() { + assertNowTest(() -> { + run("[감자칩-2]", NO.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")).contains("내실돈3,000"); + }, LocalDate.of(2024, 12, 31).atStartOfDay()); + } + + @Test + void 프로모션_재고_부족시_일부_일반_재고_처리_테스트() { + assertSimpleTest(() -> { + run("[콜라-15]", YES.getString(), NO.getString(), NO.getString()); // 프로모션 10개, 일반 10개 + assertThat(output().replaceAll("\\s", "")) + .contains("내실돈12,000"); // 프로모션 9개, 6개 일반 가격 + }); + } + + @Test + void 프로모션_조건_미충족시_개수_추가_허용_테스트() { + assertSimpleTest(() -> { + run("[사이다-2]", YES.getString(), NO.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")) + .contains("내실돈2,000"); // 프로모션 적용됨 + }); + } + + @Test + void 프로모션_조건_미충족시_추가_거부_테스트() { + assertSimpleTest(() -> { + run("[사이다-2]", NO.getString(), NO.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")) + .contains("내실돈2,000"); // 정상가로 2개 구매 + }); + } + + //가격 및 할인 관련 테스트 + @Test + void 멤버십_할인_적용_테스트() { + assertSimpleTest(() -> { + run("[비타민워터-2]", YES.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")) + .contains("내실돈2,100"); + }); + } + + @Test + void 프로모션_멤버십_할인_겹침_테스트() { + assertSimpleTest(() -> { + run("[감자칩-2]", YES.getString(), NO.getString()); + assertThat(output().replaceAll("\\s", "")) + .contains("내실돈1,500"); // 반짝할인과 멤버십 할인을 모두 적용한 가격 확인 + }); + } + + //추가 주문시 재고 관련 테스트 + @Test + void 추가_주문시_재고_감소_출력() { + assertSimpleTest(() -> { + run("[콜라-3],[사이다-3],[오렌지주스-2]", NO.getString(), YES.getString(), + "[콜라-3]", NO.getString(), NO.getString()); + assertThat(output()).contains( + "- 콜라 1,000원 7개 탄산2+1", + "- 사이다 1,000원 5개 탄산2+1", + "- 오렌지주스 1,800원 7개 MD추천상품" + ); }); }
Java
테스트 명을 어떤걸 테스트하는지 정확히 적으셔서 보기 편했습니다! 다음에는 display 애노테이션을 활용해보는건 어떨까요?ㅎㅎ
@@ -0,0 +1,25 @@ +package store.constants; + +public enum ErrorMessage { + + PRODUCT_BUY_FORM_ERROR("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요."), + NO_EXSIST_PRODUCT_ERROR("존재하지 않는 상품 입니다. 다시 입력해 주세요"), + NOT_ENOUGH_QUANTITY_ERROR("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."), + NOT_POSITIVE_INPUT_ERROR("구입할 수량은 1 이상이어야 합니다. 다시 입력해 주세요."), + ETC_INPUT_ERROR("잘못된 입력입니다. 다시 입력해주세요."), + DUPLICATE_PRODUCT_INPUT_ERROR("같은 상품은 한 번에 여러개 구입합니다. 다시 입력해 주세요."), + PRODUCT_ERROR("잘못된 재고입니다."), + SYSTEM_ERROR("실행 오류 입니다."); + + private final String prefix = "[ERROR] "; + private final String postfix = "\n"; + private final String message; + + ErrorMessage(String message) { + this.message = prefix + message + postfix; + } + + public String getMessage() { + return message; + } +}
Java
최소 구매 수량이 바뀌면 예외메시지도 바뀌어야 할 것 같아요. 상수를 외부에서 가져오도록 바꾸는 건 어떨까요?!
@@ -0,0 +1,21 @@ +package store.constants; + +public enum InputPrompts { + + START_PROMPTS("안녕하세요. W편의점입니다. \n현재 보유하고 있는 상품입니다. \n"), + ENTER_PURCHASE_PRODUCTS("구매하실 상품명과 수량을 입력해주세요. (예: [사이다-2],[감자칩-1])"), + PROMOTION_QUANTITY_ADD("현재 %s은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)\n"), + NOT_ENOUGH_PROMOTION_QUANTITY("현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)\n"), + MEMBERSHIP_DISCOUNT("\n멤버십 할인을 받으시겠습니까? (Y/N)"), + MORE_PURCHASE("감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)"); + + private final String prompt; + + InputPrompts(String prompt) { + this.prompt = prompt; + } + + public String getPrompt() { + return prompt; + } +}
Java
2+2 이벤트같은게 열리면 이 메시지는 잘못될 수도 있을 것 같아요!
@@ -0,0 +1,29 @@ +package store.constants; + +public enum OutputPrompts { + WELCOME_MESSAGE("\n안녕하세요. W편의점입니다.\n" + + "현재 보유하고 있는 상품입니다.\n"), + + PRODUCTS_HAVE_PROMOTION("- %s %s원 %s %s"), + PRODUCTS_NO_PROMOTION("- %s %s원 %s"), + RECEIPT_HEADER("\n==============W 편의점================\n" + + "상품명\t\t수량\t금액"), + RECEIPT_PRODUCTS("%s\t\t%d\t%s\n"), + RECEIPT_PROMOTION_HEADER("=============증\t정==============="), + RECEIPT_PROMOTION_PRODUCTS("%s\t\t%d\n"), + RECEIPT_TOTAL_PRICE_HEADER("===================================="), + RECEIPT_TOTAL_PRICE("총구매액\t\t%d\t%s\n"), + RECEIPT_PROMOTION_DISCOUNT("행사할인\t\t\t-%s\n"), + RECEIPT_MEMBERSHIP_DISCOUNT("멤버십할인\t\t\t-%s\n"), + RECEIPT_FINAL_PRICE("내실돈\t\t\t %s\n\n"); + + private final String prompts; + + OutputPrompts(String prompts) { + this.prompts = prompts; + } + + public String getPrompts() { + return prompts; + } +}
Java
\n은 운영체제에 종속적인 줄바꿈인 것 같아요! 다른 방법이 없을까요!?
@@ -0,0 +1,84 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import java.util.Map; +import store.constants.ErrorMessage; +import store.constants.StringConstants; +import store.domain.Cart; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.Purchase; +import store.domain.TotalPrice; +import store.service.CartService; +import store.service.InitService; +import store.service.PromotionService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private Products products; + private Promotions promotions; + private Cart cart; + + private final InitService initService = new InitService(); + private final PromotionService promotionService = new PromotionService(); + private final CartService cartService = new CartService(); + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + String next = StringConstants.YES.getString(); + initStock(); + while(next.equals(StringConstants.YES.getString())) { + start(); + checkProducts(); + result(); + products = cartService.productsReduce(products, cart); + next = inputView.checkMorePurchase(); + } + Console.close(); + } + + private void initStock() { + try { + products = initService.saveInitProducts(); + promotions = initService.saveInitPromotions(); + } catch (IOException e) { + System.out.println(ErrorMessage.SYSTEM_ERROR.getMessage()); + } + } + + private void start() { + outputView.productsOutput(this.products); + cart = inputView.readItem(products); + } + + private void checkProducts() { + for (Purchase purchase : cart.getItems()) { + promotionService.setPromotion(purchase, products); + if (!purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + promotionService.promotionsAll(purchase, promotions, products, cart); + } + } + addCart(); + } + + private void addCart() { + promotionService.applyAddPurchaseToCart(cart); + } + + private void result() { + Map<String, Purchase> items = cart.mergeItems(cart.getItems()); + TotalPrice totalPrice = new TotalPrice(cart.getItems(), products); + + totalPrice.setPromotionPrice(totalPrice.getPromotionSalePrice(cart.getItems(), promotions, products)); + String answer = inputView.checkMemberShipSale(); + + if (answer.equals(StringConstants.YES.getString())) { + totalPrice.setMemberShipPrice(totalPrice.getMembershipSalePrice(cart.getItems(), products)); + } + outputView.printReceipt(cart, products, promotions, items, totalPrice); + } +}
Java
문구 출력은 outputView에게 책임을 넘겨줘도 좋을 것 같아요!
@@ -0,0 +1,84 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import java.util.Map; +import store.constants.ErrorMessage; +import store.constants.StringConstants; +import store.domain.Cart; +import store.domain.Products; +import store.domain.Promotions; +import store.domain.Purchase; +import store.domain.TotalPrice; +import store.service.CartService; +import store.service.InitService; +import store.service.PromotionService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private Products products; + private Promotions promotions; + private Cart cart; + + private final InitService initService = new InitService(); + private final PromotionService promotionService = new PromotionService(); + private final CartService cartService = new CartService(); + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + String next = StringConstants.YES.getString(); + initStock(); + while(next.equals(StringConstants.YES.getString())) { + start(); + checkProducts(); + result(); + products = cartService.productsReduce(products, cart); + next = inputView.checkMorePurchase(); + } + Console.close(); + } + + private void initStock() { + try { + products = initService.saveInitProducts(); + promotions = initService.saveInitPromotions(); + } catch (IOException e) { + System.out.println(ErrorMessage.SYSTEM_ERROR.getMessage()); + } + } + + private void start() { + outputView.productsOutput(this.products); + cart = inputView.readItem(products); + } + + private void checkProducts() { + for (Purchase purchase : cart.getItems()) { + promotionService.setPromotion(purchase, products); + if (!purchase.getPromotion().equals(StringConstants.NO_PROMOTION.getString())) { + promotionService.promotionsAll(purchase, promotions, products, cart); + } + } + addCart(); + } + + private void addCart() { + promotionService.applyAddPurchaseToCart(cart); + } + + private void result() { + Map<String, Purchase> items = cart.mergeItems(cart.getItems()); + TotalPrice totalPrice = new TotalPrice(cart.getItems(), products); + + totalPrice.setPromotionPrice(totalPrice.getPromotionSalePrice(cart.getItems(), promotions, products)); + String answer = inputView.checkMemberShipSale(); + + if (answer.equals(StringConstants.YES.getString())) { + totalPrice.setMemberShipPrice(totalPrice.getMembershipSalePrice(cart.getItems(), products)); + } + outputView.printReceipt(cart, products, promotions, items, totalPrice); + } +}
Java
service 계층을 분리했다면 비즈니스 로직은 service에게 위임하는 것도 좋을 것 같아요!
@@ -0,0 +1,56 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import store.constants.ErrorMessage; + +public class Cart { + + private List<Purchase> items; + + public Cart(List<Purchase> items) { + this.items = new ArrayList<>(); + addPurchase(new ArrayList<>(items)); + } + + public List<Purchase> getItems() { + return items; + } + + private void addPurchase(List<Purchase> purchases) { + for (Purchase purchase : purchases) { + if(validateItem(purchase)) { + this.items.add(purchase); + } + } + } + + private boolean validateItem(Purchase purchase) { + if (items.stream().anyMatch(item -> item.getName().equals(purchase.getName()))) { + throw new IllegalArgumentException(ErrorMessage.DUPLICATE_PRODUCT_INPUT_ERROR.getMessage()); + } + return true; + } + + public Map<String, Purchase> mergeItems(List<Purchase> purchases) { + Map<String, Purchase> itemsMap = new HashMap<>(); + for (Purchase purchase : purchases) { + addItems(purchase, itemsMap); + } + return itemsMap; + } + + private static void addItems(Purchase purchase, Map<String, Purchase> itemsMap) { + Purchase existingItem = itemsMap.get(purchase.getName()); + + if (existingItem != null) { + existingItem.setQuantity(existingItem.getQuantity() + purchase.getQuantity()); + } + if (existingItem == null) { + Purchase item = new Purchase(purchase.getName(), purchase.getQuantity(), purchase.getPromotion()); + itemsMap.put(item.getName(), item); + } + } +}
Java
stream을 활용해볼 수 있지 않을까요..? 🤔
@@ -0,0 +1,56 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import store.constants.ErrorMessage; + +public class Cart { + + private List<Purchase> items; + + public Cart(List<Purchase> items) { + this.items = new ArrayList<>(); + addPurchase(new ArrayList<>(items)); + } + + public List<Purchase> getItems() { + return items; + } + + private void addPurchase(List<Purchase> purchases) { + for (Purchase purchase : purchases) { + if(validateItem(purchase)) { + this.items.add(purchase); + } + } + } + + private boolean validateItem(Purchase purchase) { + if (items.stream().anyMatch(item -> item.getName().equals(purchase.getName()))) { + throw new IllegalArgumentException(ErrorMessage.DUPLICATE_PRODUCT_INPUT_ERROR.getMessage()); + } + return true; + } + + public Map<String, Purchase> mergeItems(List<Purchase> purchases) { + Map<String, Purchase> itemsMap = new HashMap<>(); + for (Purchase purchase : purchases) { + addItems(purchase, itemsMap); + } + return itemsMap; + } + + private static void addItems(Purchase purchase, Map<String, Purchase> itemsMap) { + Purchase existingItem = itemsMap.get(purchase.getName()); + + if (existingItem != null) { + existingItem.setQuantity(existingItem.getQuantity() + purchase.getQuantity()); + } + if (existingItem == null) { + Purchase item = new Purchase(purchase.getName(), purchase.getQuantity(), purchase.getPromotion()); + itemsMap.put(item.getName(), item); + } + } +}
Java
사이드이펙트를 지양해야 한다는 의견이시군요!! 저도 동의합니다!
@@ -0,0 +1,49 @@ +package store.service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.utils.FileRead; +import store.utils.Split; + +public class InitService { + + private static final String PRODUCTS_FILE_NAME = "src/main/resources/products.md"; + private static final String PROMOTIONS_FILE_NAME = "src/main/resources/promotions.md"; + + public Products saveInitProducts() throws IOException { + List<String> fileContent = FileRead.readFile(PRODUCTS_FILE_NAME); + List<Product> productList = new ArrayList<>(); + Set<String> productNames = new LinkedHashSet<>(); + + saveProducts(fileContent, productNames, productList); + Products products = new Products(productList); + products.setProductNames(new ArrayList<>(productNames)); + products.addNoRegularProducts(); + return products; + } + + private static void saveProducts(List<String> fileContent, Set<String> productNames, List<Product> productList) { + for (String content : fileContent) { + List<String> split = Split.commaSpliter(content); + productNames.add(split.get(0)); + productList.add(new Product(split.get(0), split.get(1), split.get(2), split.get(3))); + } + } + + public Promotions saveInitPromotions() throws IOException { + List<String> fileContent = FileRead.readFile(PROMOTIONS_FILE_NAME); + List<Promotion> promotions = new ArrayList<>(); + for (String content : fileContent) { + List<String> split = Split.commaSpliter(content); + promotions.add(new Promotion(split.get(0), split.get(1), split.get(2), split.get(3), split.get(4))); + } + return new Promotions(promotions); + } +}
Java
방어적 복사를 하셨네요! 여기서 방어적 복사를 진행하지 않으면 발생할 수 있는 문제는 뭐가 있을까요!?
@@ -0,0 +1,49 @@ +package store.service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.utils.FileRead; +import store.utils.Split; + +public class InitService { + + private static final String PRODUCTS_FILE_NAME = "src/main/resources/products.md"; + private static final String PROMOTIONS_FILE_NAME = "src/main/resources/promotions.md"; + + public Products saveInitProducts() throws IOException { + List<String> fileContent = FileRead.readFile(PRODUCTS_FILE_NAME); + List<Product> productList = new ArrayList<>(); + Set<String> productNames = new LinkedHashSet<>(); + + saveProducts(fileContent, productNames, productList); + Products products = new Products(productList); + products.setProductNames(new ArrayList<>(productNames)); + products.addNoRegularProducts(); + return products; + } + + private static void saveProducts(List<String> fileContent, Set<String> productNames, List<Product> productList) { + for (String content : fileContent) { + List<String> split = Split.commaSpliter(content); + productNames.add(split.get(0)); + productList.add(new Product(split.get(0), split.get(1), split.get(2), split.get(3))); + } + } + + public Promotions saveInitPromotions() throws IOException { + List<String> fileContent = FileRead.readFile(PROMOTIONS_FILE_NAME); + List<Promotion> promotions = new ArrayList<>(); + for (String content : fileContent) { + List<String> split = Split.commaSpliter(content); + promotions.add(new Promotion(split.get(0), split.get(1), split.get(2), split.get(3), split.get(4))); + } + return new Promotions(promotions); + } +}
Java
split의 각 요소가 무엇을 의미하는지 명확하지 않은 것 같아요. 내부 클래스 매핑 등을 통해 각 자리에 어떤 의미의 필드가 들어있는지 명시하는 것도 좋을 것 같습니다!
@@ -0,0 +1,21 @@ +package store.utils; + +import java.text.DecimalFormat; + +public class ConvertFormater { + + private static final String COUNT_UNIT = "개"; + private static final String ZERO_QUANTITY = "재고 없음"; + + public static String moneyFormat(int money) { + DecimalFormat df = new DecimalFormat("###,###"); + return df.format(money); + } + + public static String quantityFormat(int quantity) { + if (quantity == 0) { + return ZERO_QUANTITY; + } + return quantity + COUNT_UNIT; + } +}
Java
이 포맷은 상수화하지 않은 이유가 있으신가요!?
@@ -0,0 +1,21 @@ +package store.utils; + +import java.text.DecimalFormat; + +public class ConvertFormater { + + private static final String COUNT_UNIT = "개"; + private static final String ZERO_QUANTITY = "재고 없음"; + + public static String moneyFormat(int money) { + DecimalFormat df = new DecimalFormat("###,###"); + return df.format(money); + } + + public static String quantityFormat(int quantity) { + if (quantity == 0) { + return ZERO_QUANTITY; + } + return quantity + COUNT_UNIT; + } +}
Java
개인적으로 상수 네이밍 단어를 통일하는 것도 좋을 것 같아요! ex) `COUNT_UNIT` -> `QUANTITY_UNIT`
@@ -0,0 +1,14 @@ +package store.utils; + +import store.constants.ErrorMessage; + +public class Parser { + + public static int parseNumberToInt(String number) { + try { + return Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ErrorMessage.ETC_INPUT_ERROR.getMessage()); + } + } +}
Java
예외를 재포장하는 로직이 좋은 것 같아요! 👍
@@ -0,0 +1,106 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; +import java.util.ArrayList; +import java.util.List; +import store.constants.InputPrompts; +import store.domain.Cart; +import store.domain.Products; +import store.domain.Purchase; +import store.utils.Split; +import store.validator.InputValidator; + +public class InputView { + + public Cart readItem(Products products) { + while(true) { + try { + String input = getPurchaseInput(); + InputValidator.validateInput(input); + List<String> purchase = Split.squareBracketsSpliter(Split.commaSpliter(input)); + return validateReadItem(purchase, products); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Cart validateReadItem(List<String> purchase, Products products) { + validatePurchase(purchase); + Cart cart = getCart(purchase); + InputValidator.validateHasProduct(cart, products); + InputValidator.validateSufficientStock(cart, products); + return cart; + } + + public String checkPromotionCountAdd(Purchase purchase) { + while(true) { + try { + System.out.printf(InputPrompts.PROMOTION_QUANTITY_ADD.getPrompt(), purchase.getName()); + String answer = Console.readLine(); + InputValidator.validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public String checkPromotionSaleNotAccept(Purchase purchase, int count) { + while(true) { + try { + System.out.printf(InputPrompts.NOT_ENOUGH_PROMOTION_QUANTITY.getPrompt(), purchase.getName(), count); + String answer = Console.readLine(); + InputValidator.validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public String checkMemberShipSale() { + while(true) { + try { + System.out.println(InputPrompts.MEMBERSHIP_DISCOUNT.getPrompt()); + String answer = Console.readLine(); + InputValidator.validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public String checkMorePurchase() { + while(true) { + try { + System.out.println(InputPrompts.MORE_PURCHASE.getPrompt()); + String answer = Console.readLine(); + InputValidator.validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private String getPurchaseInput() { + System.out.println(InputPrompts.ENTER_PURCHASE_PRODUCTS.getPrompt()); + String input = Console.readLine(); + return input.replaceAll(" ", ""); + } + + private Cart getCart(List<String> purchase) { + List<Purchase> products = new ArrayList<>(); + for (String productInput : purchase) { + List<String> buyInfo = Split.hyphenSpliter(productInput); + products.add(new Purchase(buyInfo.get(0), buyInfo.get(1))); + } + return new Cart(products); + } + + private static void validatePurchase(List<String> purchase) { + InputValidator.validatePurchaseForm(purchase); + } +}
Java
while, try-catch 코드가 동일한 구조로 여러 곳에서 중복되어 쓰이고 있는 것 같아요! 함수형 인터페이스를 활용하면 코드 중복을 최소화할 수 있을 것 같은데, 제가 학습한 내용을 아래 블로그에 게시해두었으니 관심있다면 한 번 읽어보세요! 😄 [함수형 인터페이스와 표준 API](https://velog.io/@songsunkook/%ED%95%A8%EC%88%98%ED%98%95-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4%EC%99%80-%ED%91%9C%EC%A4%80-API)
@@ -1 +1,206 @@ -# java-convenience-store-precourse + +노션 링크를 통해 더 편하게 볼 수 있습니다. + +https://tangy-napkin-64d.notion.site/4-_-_-14e5dc39aa55800480aecff3d88bce24?pvs=4 + +## 👉 로직 + +✅ **요구사항 해석한 내용** (주관적일 수 있다고 생각하여 적어봤습니다 🙌) + +- **프로모션 할인** + - **오늘 날짜가 프로모션 기간 내에 포함된 경우에만 할인을 적용한다.** + - **프로모션 혜택은 프로모션 재고 내에서만 적용할 수 있다.** + - 프로모션 적용이 가능한 상품에 대해, 고객이 해당 수량보다 적게 가져와 추가하는 경우, + 추가하는 상품 1개는 프로모션 재고가 감소된다. 이때 프로모셔 재고가 추가적으로 1개가 더 있는지 확인해야 한다고 생각함. + - **프로모션 기간 중이라면 프로모션 재고를 우선적으로 차감하며, 프로모션 재고가 부족할 경우에는 일반 재고를 사용한다.** + - **프로모션 기간이 아니라면, 이 경우에도 프로모션 재고를 우선적으로 차감할 것인가?** + + 1번) 프로모션 기간 유무에 상관없이 무조건 프로모션 재고를 우선적으로 차감한다. + + 2번) 프로모션 기간이 아니라면 우선 일반 재고를 우선적으로 차감한다. + + 3번) 프로모션 기간이 아니라면 일반 재고만 차감 가능하다. + + 4번) 프로모션 기간이 아니라면 구매 불가이다. + + → **2번**으로 해석함. 이유는 나중에 미래에 프로모션 기간이 되었을 때를 생각하면 우선 일반재고를 차감해야 한다고 생각함. + +- **멤버십 할인** + - **멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다.** + - **프로모션 미적용이란?** + + 1번) 프로모션 기간이 아닌 프로모션 상품은 프로모션 미적용 상품에 포함된다. + + 2번) (1번과 반대)프로모션 기간이 아니더라도 프로모션 혜택이 가능했던 상품이기 때문에 프로모션 미적용 상품이 아니다. + + 3번) 프로모션 상품이 줄어들어 0이 된 상황이면(일반 재고만으로 결제해야 하는 상황) 이 상품은 프로모션 미적용 상품이다. + + → **1번&3번으로 해석함. (표로 정리한 내용은 노션 참고)** + + - **프로모션 적용 후 남은 금액에 대해 멤버십 할인을 적용한다.** + - **멤버십 할인의 최대 한도는 8,000원이다.** + - **최대 한도 8000원은 플레이를 할 때마다 초기화 되는가?** + + 1번) 멤버십 할인은 누적된다. 즉 한번 플레이할 때 멤버십 할인의 최대한도인 8000원이 전부 적용되면, 다음 플레이에서는 멤버십할인이 되지 않는다. + + 2번) 멤버십 할인은 누적되지 않는다. 즉 한 번 플레이할 때 멤버십 할인이 8000원이 되더라도 다음 플레이에서 최대 8000원의 멤버십 할인을 받을 수 있다. + + → **2번**으로 해석함. + + +✅ **전제** + +- **사용자가 입력한 상품 종류 1개에 대한 구매 수량 = n** +- **영수중에 출력되는 상품 수량은 “결제한다”고 표현했습니다.** + - **따라서 결재하는 상품의 수량과 n은 다를 수 있습니다.** +- 프로모션 혜택이 가능한 상품, 프로모션 적용이 가능한 상품은 다릅니다. (위 표 참고) + +✅ **로직** + +1. **프로모션 기간 아님(**3️⃣,4️⃣) ****→ 일반 재고 우선 감소 + 나머지는 프로모션 재고 감소, + +- 프로모션 기간이 아닌 경우란? + - 프로모션 혜택이 가능한 상품이지만 기간이 아니라 ‘프로모션 미적용’ 상품인 경우 또는 + 프로모션 혜택이 애초에 없어 ‘프로모션 미적용’ 상품인 경우(처음부터 일반재고만 있는 경우) +- 일반재고 ≥ n, 일반재고 < n 나눠서 일반재고/프로모션 재고 “결제”함 +- 멤버십 할인 있음 + +2. **프로모션 기간(**1️⃣,2️⃣) → 프로모션 재고 우선 감소 + +- **case1) 프로모션 재고 > n** + - 프로모션 재고만으로 제품을 충분히 구매할 수 있는 경우 + - 이때 “결제”하는 프로모션 재고의 수는 n개 + - 고객이 해당 수량보다 적게 가져온 경우 추가 여부를 입력받음 + - 추가 가능할 정도로 프로모션 재고가 충분한지 검사 후, 추가 여부 묻기 + - 추가함 → “결제”하는 프로모션 재고의 수/증정품 수/결제한 상품의 수량을 **1개** 늘림, 멤버십 할인 받지 않음 + - 추가하지 않음 → 멤버십 할인 받지 않음(프로모션 상품이기 때문에, ‘실행 결과 예시’ 참고하기) + +- **case2) 프로모션 재고 == n** + - “결제”해야 하는 프로모션 재고의 수는 n개 + - 프로모션 적용이 가능한 상품에 대해, + - 프로모션 혜택 없이 결제해야 하는 상품의 개수라면 + - 일부 수량(k개)에 대해 정가로 결제할지 여부를 입력받음 + - 정가 결제하지 않음 → “결제” 해야하는 프로모션 재고의 수 == n-k, 일반재고 “결제” 아무것도 안함, **결제할 상품의 수량을 k개 줄임**, 멤버십 할인 받지 않음 + - 정가로 결제함 →프로모션 재고 모두 “결제”, 멤버십 할인 받지 않음 + +- **case3) 프로모션 재고 < n** + - 프로모션 재고가 부족한 경우 + - 프로모션 적용이 가능한 상품에 대해, + - 프로모션 혜택 없이 결제해야 하는 상품의 개수만큼 남았다면 + - 일부 수량(k개)에 대해 정가로 결제할지 여부를 입력받음 + - 정가 결제하지 않음 → “결제” 해야하는 프로모션 재고의 수 == n-k, 일반재고 “결제” 아무것도 안함, **결제할 상품의 수량을 k개 줄임**, 멤버십 할인 받지 않음 + - 정가로 결제함 → 프로모션 재고 모두 “결제”, 나머지는 일반재고에서 “결제”, 멤버십 할인 받지 않음 + - **단 k==n인 경우(프로모션 재고가 0개여서 구매 수량을 전부 일반재고에서 “결제”해야 하는 경우)는 멤버십 할인을 받음** + +- **case4) 추가적으로 물어볼거 없을 때** + - 정가로 결제할 상품의 수량, 추가할 수량이 없을 때 + - “결제” 해야하는 프로모션 재고의 수 == n + - 멤버십 할인 받지 않음 + +## 👉 입력 + +- 입력값 전체 공통 예외처리 + - [x] 빈값 또는 null값 입력시 + +- **구매할 상품과 수량** + - 상품명,수량은 하이픈(-)으로 + - 개별 상품은 대괄호([])로 묶어 쉼표(,)로 구분 + - `구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])` + - 예외처리 + - `,`으로 split한 후 각각에 대해서… + - [x] []이 ‘양쪽 끝에’ 각각 없으면 + - [x] -이 없으면 + + → 빈문자열인지도 함께 확인이 가능 + + - -으로 split한 후 각각에 대해서… + - [x] (스스로 판단한 내용) 상품 이름 중복 입력시 + - [x] 판매 상품이 아니면 + - [x] 재고 수량을 초과했으면 + - 프로모션 재고가 부족할 경우에는 일반 재고를 사용함 + - [x] 수량을 숫자 아닌 자료형으로 입력하면 + - [x] 수량을 0이하 입력하면 + +- Y/N 공통 예외처리 + - [x] `Y` 또는 `N` 이 아닌 값을 입력했을 때 +- **증정 받을 수 있는 상품 추가 여부** + - 프로모션이 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, + - 그 수량만큼 추가 여부를 입력받기 + - `현재 {상품명}은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)` +- **정가로 결제할지에 대한 여부** + - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, + - 일부 수량에 대해 정가로 결제할지 여부를 입력받기 + - `현재 {상품명} {수량}개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)` + - 스스로 판단한 내용 + - `N`를 입력시 : 구매를 아예 하지 않음 +- **멤버십 할인 적용 여부** + - `멤버십 할인을 받으시겠습니까? (Y/N)` + - 멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다. + - 프로모션 적용 후 남은 금액에 대해 멤버십 할인을 적용한다. + - 멤버십 할인의 최대 한도는 8,000원이다. +- **추가 구매 여부** + - `감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)` + +## 👉 출력 + +- 환영 인사와 함께 상품명, 가격, 프로모션 이름, 재고를 안내한다. 만약 재고가 0개라면 `재고 없음`을 출력 + - **천단위 쉼표 찍기** + + ```java + 안녕하세요. W편의점입니다. + 현재 보유하고 있는 상품입니다. + + - 콜라 1,000원 10개 탄산2+1 + - 콜라 1,000원 10개 + - 사이다 1,000원 8개 탄산2+1 + - 사이다 1,000원 7개 + - 오렌지주스 1,800원 9개 MD추천상품 + - 오렌지주스 1,800원 재고 없음 + - 탄산수 1,200원 5개 탄산2+1 + - 탄산수 1,200원 재고 없음 + - 물 500원 10개 + - 비타민워터 1,500원 6개 + - 감자칩 1,500원 5개 반짝할인 + - 감자칩 1,500원 5개 + - 초코바 1,200원 5개 MD추천상품 + - 초코바 1,200원 5개 + - 에너지바 2,000원 5개 + - 정식도시락 6,400원 8개 + - 컵라면 1,700원 1개 MD추천상품 + - 컵라면 1,700원 10개 + ``` + + +- 구매 상품 내역, 증정 상품 내역, 금액 정보를 출력 + - **천단위 쉼표 찍기** + + ```java + ==============W 편의점================ + 상품명 수량 금액 + 콜라 3 3,000 + 에너지바 5 10,000 + =============증 정=============== + 콜라 1 + ==================================== + 총구매액 8 13,000 + 행사할인 -1,000 + 멤버십할인 -3,000 + 내실돈 9,000 + ``` + + +- 에러 메시지 + - 사용자가 잘못된 값을 입력했을 때, **"[ERROR]"로 시작**하는 오류 메시지와 함께 상황에 맞는 안내를 출력한다. + - 구매할 상품과 수량 형식이 올바르지 않은 경우: `[ERROR] 올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.` + - 존재하지 않는 상품을 입력한 경우: `[ERROR] 존재하지 않는 상품입니다. 다시 입력해 주세요.` + - 구매 수량이 재고 수량을 초과한 경우: `[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.` + - 기타 잘못된 입력의 경우: `[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.` + +- 사용자가 잘못된 값을 입력할 경우 `IllegalArgumentException`를 발생시키고, "[ERROR]"로 시작하는 에러 메시지를 출력 후 그 부분부터 입력을 다시 받는다. + - `Exception`이 아닌 `IllegalArgumentException`, `IllegalStateException` 등과 같은 명확한 유형을 처리한다. + +## 👉 추가 라이브러리 + +- `camp.nextstep.edu.missionutils`에서 제공하는 `DateTimes` 및 `Console` API를 사용하여 구현해야 한다. + - 현재 날짜와 시간을 가져오려면 `camp.nextstep.edu.missionutils.DateTimes`의 `now()`를 활용한다. + - 사용자가 입력하는 값은 `camp.nextstep.edu.missionutils.Console`의 `readLine()`을 활용한다.
Unknown
프로모션 재고가 없는 경우 어차피 추가가 불가능하기 때문에 추가하는 경우에 들어가기 전에 확인 해야한다고 생각합니다.
@@ -1 +1,206 @@ -# java-convenience-store-precourse + +노션 링크를 통해 더 편하게 볼 수 있습니다. + +https://tangy-napkin-64d.notion.site/4-_-_-14e5dc39aa55800480aecff3d88bce24?pvs=4 + +## 👉 로직 + +✅ **요구사항 해석한 내용** (주관적일 수 있다고 생각하여 적어봤습니다 🙌) + +- **프로모션 할인** + - **오늘 날짜가 프로모션 기간 내에 포함된 경우에만 할인을 적용한다.** + - **프로모션 혜택은 프로모션 재고 내에서만 적용할 수 있다.** + - 프로모션 적용이 가능한 상품에 대해, 고객이 해당 수량보다 적게 가져와 추가하는 경우, + 추가하는 상품 1개는 프로모션 재고가 감소된다. 이때 프로모셔 재고가 추가적으로 1개가 더 있는지 확인해야 한다고 생각함. + - **프로모션 기간 중이라면 프로모션 재고를 우선적으로 차감하며, 프로모션 재고가 부족할 경우에는 일반 재고를 사용한다.** + - **프로모션 기간이 아니라면, 이 경우에도 프로모션 재고를 우선적으로 차감할 것인가?** + + 1번) 프로모션 기간 유무에 상관없이 무조건 프로모션 재고를 우선적으로 차감한다. + + 2번) 프로모션 기간이 아니라면 우선 일반 재고를 우선적으로 차감한다. + + 3번) 프로모션 기간이 아니라면 일반 재고만 차감 가능하다. + + 4번) 프로모션 기간이 아니라면 구매 불가이다. + + → **2번**으로 해석함. 이유는 나중에 미래에 프로모션 기간이 되었을 때를 생각하면 우선 일반재고를 차감해야 한다고 생각함. + +- **멤버십 할인** + - **멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다.** + - **프로모션 미적용이란?** + + 1번) 프로모션 기간이 아닌 프로모션 상품은 프로모션 미적용 상품에 포함된다. + + 2번) (1번과 반대)프로모션 기간이 아니더라도 프로모션 혜택이 가능했던 상품이기 때문에 프로모션 미적용 상품이 아니다. + + 3번) 프로모션 상품이 줄어들어 0이 된 상황이면(일반 재고만으로 결제해야 하는 상황) 이 상품은 프로모션 미적용 상품이다. + + → **1번&3번으로 해석함. (표로 정리한 내용은 노션 참고)** + + - **프로모션 적용 후 남은 금액에 대해 멤버십 할인을 적용한다.** + - **멤버십 할인의 최대 한도는 8,000원이다.** + - **최대 한도 8000원은 플레이를 할 때마다 초기화 되는가?** + + 1번) 멤버십 할인은 누적된다. 즉 한번 플레이할 때 멤버십 할인의 최대한도인 8000원이 전부 적용되면, 다음 플레이에서는 멤버십할인이 되지 않는다. + + 2번) 멤버십 할인은 누적되지 않는다. 즉 한 번 플레이할 때 멤버십 할인이 8000원이 되더라도 다음 플레이에서 최대 8000원의 멤버십 할인을 받을 수 있다. + + → **2번**으로 해석함. + + +✅ **전제** + +- **사용자가 입력한 상품 종류 1개에 대한 구매 수량 = n** +- **영수중에 출력되는 상품 수량은 “결제한다”고 표현했습니다.** + - **따라서 결재하는 상품의 수량과 n은 다를 수 있습니다.** +- 프로모션 혜택이 가능한 상품, 프로모션 적용이 가능한 상품은 다릅니다. (위 표 참고) + +✅ **로직** + +1. **프로모션 기간 아님(**3️⃣,4️⃣) ****→ 일반 재고 우선 감소 + 나머지는 프로모션 재고 감소, + +- 프로모션 기간이 아닌 경우란? + - 프로모션 혜택이 가능한 상품이지만 기간이 아니라 ‘프로모션 미적용’ 상품인 경우 또는 + 프로모션 혜택이 애초에 없어 ‘프로모션 미적용’ 상품인 경우(처음부터 일반재고만 있는 경우) +- 일반재고 ≥ n, 일반재고 < n 나눠서 일반재고/프로모션 재고 “결제”함 +- 멤버십 할인 있음 + +2. **프로모션 기간(**1️⃣,2️⃣) → 프로모션 재고 우선 감소 + +- **case1) 프로모션 재고 > n** + - 프로모션 재고만으로 제품을 충분히 구매할 수 있는 경우 + - 이때 “결제”하는 프로모션 재고의 수는 n개 + - 고객이 해당 수량보다 적게 가져온 경우 추가 여부를 입력받음 + - 추가 가능할 정도로 프로모션 재고가 충분한지 검사 후, 추가 여부 묻기 + - 추가함 → “결제”하는 프로모션 재고의 수/증정품 수/결제한 상품의 수량을 **1개** 늘림, 멤버십 할인 받지 않음 + - 추가하지 않음 → 멤버십 할인 받지 않음(프로모션 상품이기 때문에, ‘실행 결과 예시’ 참고하기) + +- **case2) 프로모션 재고 == n** + - “결제”해야 하는 프로모션 재고의 수는 n개 + - 프로모션 적용이 가능한 상품에 대해, + - 프로모션 혜택 없이 결제해야 하는 상품의 개수라면 + - 일부 수량(k개)에 대해 정가로 결제할지 여부를 입력받음 + - 정가 결제하지 않음 → “결제” 해야하는 프로모션 재고의 수 == n-k, 일반재고 “결제” 아무것도 안함, **결제할 상품의 수량을 k개 줄임**, 멤버십 할인 받지 않음 + - 정가로 결제함 →프로모션 재고 모두 “결제”, 멤버십 할인 받지 않음 + +- **case3) 프로모션 재고 < n** + - 프로모션 재고가 부족한 경우 + - 프로모션 적용이 가능한 상품에 대해, + - 프로모션 혜택 없이 결제해야 하는 상품의 개수만큼 남았다면 + - 일부 수량(k개)에 대해 정가로 결제할지 여부를 입력받음 + - 정가 결제하지 않음 → “결제” 해야하는 프로모션 재고의 수 == n-k, 일반재고 “결제” 아무것도 안함, **결제할 상품의 수량을 k개 줄임**, 멤버십 할인 받지 않음 + - 정가로 결제함 → 프로모션 재고 모두 “결제”, 나머지는 일반재고에서 “결제”, 멤버십 할인 받지 않음 + - **단 k==n인 경우(프로모션 재고가 0개여서 구매 수량을 전부 일반재고에서 “결제”해야 하는 경우)는 멤버십 할인을 받음** + +- **case4) 추가적으로 물어볼거 없을 때** + - 정가로 결제할 상품의 수량, 추가할 수량이 없을 때 + - “결제” 해야하는 프로모션 재고의 수 == n + - 멤버십 할인 받지 않음 + +## 👉 입력 + +- 입력값 전체 공통 예외처리 + - [x] 빈값 또는 null값 입력시 + +- **구매할 상품과 수량** + - 상품명,수량은 하이픈(-)으로 + - 개별 상품은 대괄호([])로 묶어 쉼표(,)로 구분 + - `구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])` + - 예외처리 + - `,`으로 split한 후 각각에 대해서… + - [x] []이 ‘양쪽 끝에’ 각각 없으면 + - [x] -이 없으면 + + → 빈문자열인지도 함께 확인이 가능 + + - -으로 split한 후 각각에 대해서… + - [x] (스스로 판단한 내용) 상품 이름 중복 입력시 + - [x] 판매 상품이 아니면 + - [x] 재고 수량을 초과했으면 + - 프로모션 재고가 부족할 경우에는 일반 재고를 사용함 + - [x] 수량을 숫자 아닌 자료형으로 입력하면 + - [x] 수량을 0이하 입력하면 + +- Y/N 공통 예외처리 + - [x] `Y` 또는 `N` 이 아닌 값을 입력했을 때 +- **증정 받을 수 있는 상품 추가 여부** + - 프로모션이 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, + - 그 수량만큼 추가 여부를 입력받기 + - `현재 {상품명}은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)` +- **정가로 결제할지에 대한 여부** + - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, + - 일부 수량에 대해 정가로 결제할지 여부를 입력받기 + - `현재 {상품명} {수량}개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)` + - 스스로 판단한 내용 + - `N`를 입력시 : 구매를 아예 하지 않음 +- **멤버십 할인 적용 여부** + - `멤버십 할인을 받으시겠습니까? (Y/N)` + - 멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다. + - 프로모션 적용 후 남은 금액에 대해 멤버십 할인을 적용한다. + - 멤버십 할인의 최대 한도는 8,000원이다. +- **추가 구매 여부** + - `감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)` + +## 👉 출력 + +- 환영 인사와 함께 상품명, 가격, 프로모션 이름, 재고를 안내한다. 만약 재고가 0개라면 `재고 없음`을 출력 + - **천단위 쉼표 찍기** + + ```java + 안녕하세요. W편의점입니다. + 현재 보유하고 있는 상품입니다. + + - 콜라 1,000원 10개 탄산2+1 + - 콜라 1,000원 10개 + - 사이다 1,000원 8개 탄산2+1 + - 사이다 1,000원 7개 + - 오렌지주스 1,800원 9개 MD추천상품 + - 오렌지주스 1,800원 재고 없음 + - 탄산수 1,200원 5개 탄산2+1 + - 탄산수 1,200원 재고 없음 + - 물 500원 10개 + - 비타민워터 1,500원 6개 + - 감자칩 1,500원 5개 반짝할인 + - 감자칩 1,500원 5개 + - 초코바 1,200원 5개 MD추천상품 + - 초코바 1,200원 5개 + - 에너지바 2,000원 5개 + - 정식도시락 6,400원 8개 + - 컵라면 1,700원 1개 MD추천상품 + - 컵라면 1,700원 10개 + ``` + + +- 구매 상품 내역, 증정 상품 내역, 금액 정보를 출력 + - **천단위 쉼표 찍기** + + ```java + ==============W 편의점================ + 상품명 수량 금액 + 콜라 3 3,000 + 에너지바 5 10,000 + =============증 정=============== + 콜라 1 + ==================================== + 총구매액 8 13,000 + 행사할인 -1,000 + 멤버십할인 -3,000 + 내실돈 9,000 + ``` + + +- 에러 메시지 + - 사용자가 잘못된 값을 입력했을 때, **"[ERROR]"로 시작**하는 오류 메시지와 함께 상황에 맞는 안내를 출력한다. + - 구매할 상품과 수량 형식이 올바르지 않은 경우: `[ERROR] 올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.` + - 존재하지 않는 상품을 입력한 경우: `[ERROR] 존재하지 않는 상품입니다. 다시 입력해 주세요.` + - 구매 수량이 재고 수량을 초과한 경우: `[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.` + - 기타 잘못된 입력의 경우: `[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.` + +- 사용자가 잘못된 값을 입력할 경우 `IllegalArgumentException`를 발생시키고, "[ERROR]"로 시작하는 에러 메시지를 출력 후 그 부분부터 입력을 다시 받는다. + - `Exception`이 아닌 `IllegalArgumentException`, `IllegalStateException` 등과 같은 명확한 유형을 처리한다. + +## 👉 추가 라이브러리 + +- `camp.nextstep.edu.missionutils`에서 제공하는 `DateTimes` 및 `Console` API를 사용하여 구현해야 한다. + - 현재 날짜와 시간을 가져오려면 `camp.nextstep.edu.missionutils.DateTimes`의 `now()`를 활용한다. + - 사용자가 입력하는 값은 `camp.nextstep.edu.missionutils.Console`의 `readLine()`을 활용한다.
Unknown
이런 의문은 안가졌었는데 꼼꼼히 하셨네요... 처음보는 시점입니다
@@ -1 +1,206 @@ -# java-convenience-store-precourse + +노션 링크를 통해 더 편하게 볼 수 있습니다. + +https://tangy-napkin-64d.notion.site/4-_-_-14e5dc39aa55800480aecff3d88bce24?pvs=4 + +## 👉 로직 + +✅ **요구사항 해석한 내용** (주관적일 수 있다고 생각하여 적어봤습니다 🙌) + +- **프로모션 할인** + - **오늘 날짜가 프로모션 기간 내에 포함된 경우에만 할인을 적용한다.** + - **프로모션 혜택은 프로모션 재고 내에서만 적용할 수 있다.** + - 프로모션 적용이 가능한 상품에 대해, 고객이 해당 수량보다 적게 가져와 추가하는 경우, + 추가하는 상품 1개는 프로모션 재고가 감소된다. 이때 프로모셔 재고가 추가적으로 1개가 더 있는지 확인해야 한다고 생각함. + - **프로모션 기간 중이라면 프로모션 재고를 우선적으로 차감하며, 프로모션 재고가 부족할 경우에는 일반 재고를 사용한다.** + - **프로모션 기간이 아니라면, 이 경우에도 프로모션 재고를 우선적으로 차감할 것인가?** + + 1번) 프로모션 기간 유무에 상관없이 무조건 프로모션 재고를 우선적으로 차감한다. + + 2번) 프로모션 기간이 아니라면 우선 일반 재고를 우선적으로 차감한다. + + 3번) 프로모션 기간이 아니라면 일반 재고만 차감 가능하다. + + 4번) 프로모션 기간이 아니라면 구매 불가이다. + + → **2번**으로 해석함. 이유는 나중에 미래에 프로모션 기간이 되었을 때를 생각하면 우선 일반재고를 차감해야 한다고 생각함. + +- **멤버십 할인** + - **멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다.** + - **프로모션 미적용이란?** + + 1번) 프로모션 기간이 아닌 프로모션 상품은 프로모션 미적용 상품에 포함된다. + + 2번) (1번과 반대)프로모션 기간이 아니더라도 프로모션 혜택이 가능했던 상품이기 때문에 프로모션 미적용 상품이 아니다. + + 3번) 프로모션 상품이 줄어들어 0이 된 상황이면(일반 재고만으로 결제해야 하는 상황) 이 상품은 프로모션 미적용 상품이다. + + → **1번&3번으로 해석함. (표로 정리한 내용은 노션 참고)** + + - **프로모션 적용 후 남은 금액에 대해 멤버십 할인을 적용한다.** + - **멤버십 할인의 최대 한도는 8,000원이다.** + - **최대 한도 8000원은 플레이를 할 때마다 초기화 되는가?** + + 1번) 멤버십 할인은 누적된다. 즉 한번 플레이할 때 멤버십 할인의 최대한도인 8000원이 전부 적용되면, 다음 플레이에서는 멤버십할인이 되지 않는다. + + 2번) 멤버십 할인은 누적되지 않는다. 즉 한 번 플레이할 때 멤버십 할인이 8000원이 되더라도 다음 플레이에서 최대 8000원의 멤버십 할인을 받을 수 있다. + + → **2번**으로 해석함. + + +✅ **전제** + +- **사용자가 입력한 상품 종류 1개에 대한 구매 수량 = n** +- **영수중에 출력되는 상품 수량은 “결제한다”고 표현했습니다.** + - **따라서 결재하는 상품의 수량과 n은 다를 수 있습니다.** +- 프로모션 혜택이 가능한 상품, 프로모션 적용이 가능한 상품은 다릅니다. (위 표 참고) + +✅ **로직** + +1. **프로모션 기간 아님(**3️⃣,4️⃣) ****→ 일반 재고 우선 감소 + 나머지는 프로모션 재고 감소, + +- 프로모션 기간이 아닌 경우란? + - 프로모션 혜택이 가능한 상품이지만 기간이 아니라 ‘프로모션 미적용’ 상품인 경우 또는 + 프로모션 혜택이 애초에 없어 ‘프로모션 미적용’ 상품인 경우(처음부터 일반재고만 있는 경우) +- 일반재고 ≥ n, 일반재고 < n 나눠서 일반재고/프로모션 재고 “결제”함 +- 멤버십 할인 있음 + +2. **프로모션 기간(**1️⃣,2️⃣) → 프로모션 재고 우선 감소 + +- **case1) 프로모션 재고 > n** + - 프로모션 재고만으로 제품을 충분히 구매할 수 있는 경우 + - 이때 “결제”하는 프로모션 재고의 수는 n개 + - 고객이 해당 수량보다 적게 가져온 경우 추가 여부를 입력받음 + - 추가 가능할 정도로 프로모션 재고가 충분한지 검사 후, 추가 여부 묻기 + - 추가함 → “결제”하는 프로모션 재고의 수/증정품 수/결제한 상품의 수량을 **1개** 늘림, 멤버십 할인 받지 않음 + - 추가하지 않음 → 멤버십 할인 받지 않음(프로모션 상품이기 때문에, ‘실행 결과 예시’ 참고하기) + +- **case2) 프로모션 재고 == n** + - “결제”해야 하는 프로모션 재고의 수는 n개 + - 프로모션 적용이 가능한 상품에 대해, + - 프로모션 혜택 없이 결제해야 하는 상품의 개수라면 + - 일부 수량(k개)에 대해 정가로 결제할지 여부를 입력받음 + - 정가 결제하지 않음 → “결제” 해야하는 프로모션 재고의 수 == n-k, 일반재고 “결제” 아무것도 안함, **결제할 상품의 수량을 k개 줄임**, 멤버십 할인 받지 않음 + - 정가로 결제함 →프로모션 재고 모두 “결제”, 멤버십 할인 받지 않음 + +- **case3) 프로모션 재고 < n** + - 프로모션 재고가 부족한 경우 + - 프로모션 적용이 가능한 상품에 대해, + - 프로모션 혜택 없이 결제해야 하는 상품의 개수만큼 남았다면 + - 일부 수량(k개)에 대해 정가로 결제할지 여부를 입력받음 + - 정가 결제하지 않음 → “결제” 해야하는 프로모션 재고의 수 == n-k, 일반재고 “결제” 아무것도 안함, **결제할 상품의 수량을 k개 줄임**, 멤버십 할인 받지 않음 + - 정가로 결제함 → 프로모션 재고 모두 “결제”, 나머지는 일반재고에서 “결제”, 멤버십 할인 받지 않음 + - **단 k==n인 경우(프로모션 재고가 0개여서 구매 수량을 전부 일반재고에서 “결제”해야 하는 경우)는 멤버십 할인을 받음** + +- **case4) 추가적으로 물어볼거 없을 때** + - 정가로 결제할 상품의 수량, 추가할 수량이 없을 때 + - “결제” 해야하는 프로모션 재고의 수 == n + - 멤버십 할인 받지 않음 + +## 👉 입력 + +- 입력값 전체 공통 예외처리 + - [x] 빈값 또는 null값 입력시 + +- **구매할 상품과 수량** + - 상품명,수량은 하이픈(-)으로 + - 개별 상품은 대괄호([])로 묶어 쉼표(,)로 구분 + - `구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])` + - 예외처리 + - `,`으로 split한 후 각각에 대해서… + - [x] []이 ‘양쪽 끝에’ 각각 없으면 + - [x] -이 없으면 + + → 빈문자열인지도 함께 확인이 가능 + + - -으로 split한 후 각각에 대해서… + - [x] (스스로 판단한 내용) 상품 이름 중복 입력시 + - [x] 판매 상품이 아니면 + - [x] 재고 수량을 초과했으면 + - 프로모션 재고가 부족할 경우에는 일반 재고를 사용함 + - [x] 수량을 숫자 아닌 자료형으로 입력하면 + - [x] 수량을 0이하 입력하면 + +- Y/N 공통 예외처리 + - [x] `Y` 또는 `N` 이 아닌 값을 입력했을 때 +- **증정 받을 수 있는 상품 추가 여부** + - 프로모션이 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, + - 그 수량만큼 추가 여부를 입력받기 + - `현재 {상품명}은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)` +- **정가로 결제할지에 대한 여부** + - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, + - 일부 수량에 대해 정가로 결제할지 여부를 입력받기 + - `현재 {상품명} {수량}개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)` + - 스스로 판단한 내용 + - `N`를 입력시 : 구매를 아예 하지 않음 +- **멤버십 할인 적용 여부** + - `멤버십 할인을 받으시겠습니까? (Y/N)` + - 멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다. + - 프로모션 적용 후 남은 금액에 대해 멤버십 할인을 적용한다. + - 멤버십 할인의 최대 한도는 8,000원이다. +- **추가 구매 여부** + - `감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)` + +## 👉 출력 + +- 환영 인사와 함께 상품명, 가격, 프로모션 이름, 재고를 안내한다. 만약 재고가 0개라면 `재고 없음`을 출력 + - **천단위 쉼표 찍기** + + ```java + 안녕하세요. W편의점입니다. + 현재 보유하고 있는 상품입니다. + + - 콜라 1,000원 10개 탄산2+1 + - 콜라 1,000원 10개 + - 사이다 1,000원 8개 탄산2+1 + - 사이다 1,000원 7개 + - 오렌지주스 1,800원 9개 MD추천상품 + - 오렌지주스 1,800원 재고 없음 + - 탄산수 1,200원 5개 탄산2+1 + - 탄산수 1,200원 재고 없음 + - 물 500원 10개 + - 비타민워터 1,500원 6개 + - 감자칩 1,500원 5개 반짝할인 + - 감자칩 1,500원 5개 + - 초코바 1,200원 5개 MD추천상품 + - 초코바 1,200원 5개 + - 에너지바 2,000원 5개 + - 정식도시락 6,400원 8개 + - 컵라면 1,700원 1개 MD추천상품 + - 컵라면 1,700원 10개 + ``` + + +- 구매 상품 내역, 증정 상품 내역, 금액 정보를 출력 + - **천단위 쉼표 찍기** + + ```java + ==============W 편의점================ + 상품명 수량 금액 + 콜라 3 3,000 + 에너지바 5 10,000 + =============증 정=============== + 콜라 1 + ==================================== + 총구매액 8 13,000 + 행사할인 -1,000 + 멤버십할인 -3,000 + 내실돈 9,000 + ``` + + +- 에러 메시지 + - 사용자가 잘못된 값을 입력했을 때, **"[ERROR]"로 시작**하는 오류 메시지와 함께 상황에 맞는 안내를 출력한다. + - 구매할 상품과 수량 형식이 올바르지 않은 경우: `[ERROR] 올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.` + - 존재하지 않는 상품을 입력한 경우: `[ERROR] 존재하지 않는 상품입니다. 다시 입력해 주세요.` + - 구매 수량이 재고 수량을 초과한 경우: `[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.` + - 기타 잘못된 입력의 경우: `[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.` + +- 사용자가 잘못된 값을 입력할 경우 `IllegalArgumentException`를 발생시키고, "[ERROR]"로 시작하는 에러 메시지를 출력 후 그 부분부터 입력을 다시 받는다. + - `Exception`이 아닌 `IllegalArgumentException`, `IllegalStateException` 등과 같은 명확한 유형을 처리한다. + +## 👉 추가 라이브러리 + +- `camp.nextstep.edu.missionutils`에서 제공하는 `DateTimes` 및 `Console` API를 사용하여 구현해야 한다. + - 현재 날짜와 시간을 가져오려면 `camp.nextstep.edu.missionutils.DateTimes`의 `now()`를 활용한다. + - 사용자가 입력하는 값은 `camp.nextstep.edu.missionutils.Console`의 `readLine()`을 활용한다.
Unknown
java가 아닌 text나 아예 제거하는게 좋을 것 같습니다. 크게 차이는 없겠지만 혹시나해서 남겨둬요