code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,4 @@ +package store.dto; + +public record BuyRequest(String itemName, int amount) { +}
Java
record 사용하신 점 인상 깊습니다! 저도 IntelliJ가 record로 변환할 수 있어서 하려다가 부작용이 생길까봐 안 했는데, record 를 사용하면 좋은 점이 무엇이라고 생각하시나요?
@@ -0,0 +1,55 @@ +package store.facade; + +import java.io.IOException; +import store.config.StoreInitializer; +import store.discount.promotion.domain.Promotions; +import store.discount.promotion.domain.PromotionsImpl; +import store.item.inventory.Inventory; +import store.order.domain.Order; +import store.order.exception.OrderCanceledException; +import store.presentation.view.input.BuyMoreInputView; +import store.presentation.view.output.OrderOutputView; +import store.presentation.view.output.ProductsOutputView; +import store.presentation.view.output.WelcomeOutputView; + +public class ConvenienceStore { + + private final OrderFacade orderFacade; + private final Inventory inventory; + + private final WelcomeOutputView welcomeOutputView = new WelcomeOutputView(); + private final ProductsOutputView productsOutputView = new ProductsOutputView(); + private final OrderOutputView orderOutputView = new OrderOutputView(); + private final BuyMoreInputView buyMoreInputView = new BuyMoreInputView(); + + public ConvenienceStore(OrderFacade orderFacade, Inventory inventory) { + this.orderFacade = orderFacade; + this.inventory = inventory; + } + + public void setUp() { + Promotions PROMOTIONS = new PromotionsImpl(); + try { + StoreInitializer.initialize(PROMOTIONS, inventory); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void enter() { + do { + welcomeOutputView.print(); + productsOutputView.print(inventory); + orderHandlingCancelException(); + } + while (ExceptionFacade.process(buyMoreInputView::read)); + } + + private void orderHandlingCancelException() { + try { + Order order = orderFacade.process(); + orderOutputView.print(order); + } catch (OrderCanceledException exception) { + } + } +}
Java
Facade 패턴은 듣기만 했지 처음 보네요 👀
@@ -0,0 +1,41 @@ +package store.common.collector; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.constant.FilePath; + +public abstract class FileContentCollector<T> { + + private final FilePath filePath; + private long sequence = 0L; + + public FileContentCollector(FilePath filePath) { + this.filePath = filePath; + } + + public final List<T> collect() throws IOException { + BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath.get())); + bufferedReader.readLine(); + List<T> result = executeCollect(bufferedReader); + + bufferedReader.close(); + return result; + } + + private List<T> executeCollect(BufferedReader bufferedReader) throws IOException { + List<T> instances = new ArrayList<>(); + while (true) { + String line = bufferedReader.readLine(); + if (line == null) { + break; + } + instances.add(toInstance(line, sequence++)); + } + return instances; + } + + protected abstract T toInstance(String line, long sequence); +}
Java
음.. 별 생각없이 관성적으로 long타입을 사용한 것 같습니다. 말씀하신 대로 long타입까지 쓸 필요가 없어보이네요!
@@ -0,0 +1,39 @@ +package store.common.collector; + +import store.constant.FilePath; +import store.discount.promotion.domain.Promotion; +import store.discount.promotion.domain.Promotions; +import store.item.domain.Item; +import store.item.domain.NormalItem; +import store.item.domain.PromotionItem; + +public class ItemCollector extends FileContentCollector<Item> { + + private final Promotions promotions; + public static final String PROMOTION_NOTHING = "null"; + + public ItemCollector(FilePath filePath, Promotions promotions) { + super(filePath); + this.promotions = promotions; + } + + @Override + protected Item toInstance(String line, long sequence) { + String[] split = line.trim().split(","); + String name = split[0]; + int price = Integer.parseInt(split[1]); + int quantity = Integer.parseInt(split[2]); + String promotionName = split[3].trim(); + + return generateItem(name, price, quantity, promotionName); + } + + private Item generateItem(String name, int price, int quantity, String promotionName) { + if (promotionName.equals(PROMOTION_NOTHING)) { + return new NormalItem(name, price, quantity); + } + + Promotion promotion = promotions.getByName(promotionName); + return new PromotionItem(name, price, quantity, promotion); + } +}
Java
프로모션과 상품 md파일을 읽는 두 곳에서 파일 입력의 중복을 없애고자 함이었습니다. 또 여러가지 파일 입력이 생길 수 있다는 확장성을 생각해 상속을 이용하여 파일입력은 공통된 메서드로 처리하고 변환에만 신경쓰기를 의도했습니다!
@@ -0,0 +1,32 @@ +package store.config; + +import store.discount.membership.Membership; +import store.discount.membership.MembershipImpl; +import store.facade.ConvenienceStore; +import store.facade.OrderFacade; +import store.item.inventory.Inventory; +import store.item.inventory.InventoryImpl; +import store.order.service.ConfirmListener; +import store.order.service.OrderService; +import store.order.service.OrderServiceImpl; +import store.presentation.view.input.PromotionAppendInputView; +import store.presentation.view.input.PromotionFailedInputView; + +public class AppConfig { + + public static final Inventory INVENTORY = new InventoryImpl(); + + private static final ConfirmListener<String, Integer> promotionAppendListener = new PromotionAppendInputView(); + private static final ConfirmListener<String, Integer> promotionFailedListener = new PromotionFailedInputView(); + public static final OrderService ORDER_SERVICE = new OrderServiceImpl(INVENTORY, + promotionAppendListener, promotionFailedListener); + + public static final OrderFacade ORDER_FACADE = new OrderFacade(ORDER_SERVICE); + public static final ConvenienceStore CONVENIENCE_STORE = new ConvenienceStore(ORDER_FACADE, + INVENTORY); + + public static final Membership MEMBERSHIP = new MembershipImpl(); + + private AppConfig() { + } +}
Java
애플리케이션을 실행했을 때 상수로 선언된 객체 중 사용되지 않는 객체가 없기도 하고, 모든 구현체들에 똑같은 싱글톤 구현 코드를 넣고싶지 않아서 상수로 선언하였습니다! 사실 메모리에 대해서는 생각해보지 않았는데, 말씀하신 덕분에 생각해보게 되었습니다 ㅎㅎ 감사합니다
@@ -0,0 +1,25 @@ +package store.constant; + +public enum ConstantNumbers { + MIN_STOCK_PRICE(100), + MAX_STOCK_PRICE(100_000), + MIN_LENGTH_ITEM_NAME(2), + MAX_LENGTH_ITEM_NAME(10), + MIN_LENGTH_PROMOTION_NAME(4), + MAX_LENGTH_PROMOTION_NAME(12), + MIN_BUY_PROMOTION(1), + MAX_BUY_PROMOTION(4), + EXACT_GET_PROMOTION(1), + PERCENT_MEMBERSHIP(30), + MAX_MEMBERSHIP(8000); + + private final int value; + + ConstantNumbers(int value) { + this.value = value; + } + + public int get() { + return value; + } +}
Java
get()이라는 이름을 사용한 이유는 이 Enum에 필드가 1개밖에 없고, ConstantNumbers.MIN_STOCK_PRICE.get() 처럼 호출할 때 어떤 값이 나올 지 예측 가능하다고 생각했습니다. 만약 value 말고도 다른 필드가 있거나 정수로 한정되지 않는 등의 경우에는 getValue()를 사용했을 것 같습니다! 이 생각은 제 주관이라.. 저도 알아봐야겠습니다 👍
@@ -0,0 +1,39 @@ +package store.constant; + +import static store.constant.ConstantNumbers.EXACT_GET_PROMOTION; +import static store.constant.ConstantNumbers.MAX_BUY_PROMOTION; +import static store.constant.ConstantNumbers.MAX_LENGTH_ITEM_NAME; +import static store.constant.ConstantNumbers.MAX_LENGTH_PROMOTION_NAME; +import static store.constant.ConstantNumbers.MAX_STOCK_PRICE; +import static store.constant.ConstantNumbers.MIN_BUY_PROMOTION; +import static store.constant.ConstantNumbers.MIN_LENGTH_ITEM_NAME; +import static store.constant.ConstantNumbers.MIN_LENGTH_PROMOTION_NAME; +import static store.constant.ConstantNumbers.MIN_STOCK_PRICE; + +public enum Errors { + + NOT_NEGATIVE_QUANTITY("수량은 음수일 수 없습니다."), + LENGTH_STOCK_NAME("상품 이름은 %d자에서 %d자 사이여야 합니다.", + MIN_LENGTH_ITEM_NAME.get(), MAX_LENGTH_ITEM_NAME.get()), + LENGTH_STOCK_PRICE("상품 가격은 최소 %d원에서 %d원 사이여야 합니다.", + MIN_STOCK_PRICE.get(), MAX_STOCK_PRICE.get()), + LENGTH_PROMOTION_NAME("프로모션 이름은 %d자에서 %d자 사이여야 합니다.", + MIN_LENGTH_PROMOTION_NAME.get(), MAX_LENGTH_PROMOTION_NAME.get()), + LENGTH_PROMOTION_BUY("프로모션 혜택은 최소 %d개에서 최대 %d까지 구매해야 합니다.", + MIN_BUY_PROMOTION.get(), MAX_BUY_PROMOTION.get()), + EXACT_PROMOTION_GET("프로모션 혜택 당 증정상품은 반드시 %d개입니다.", EXACT_GET_PROMOTION.get()), + NOT_ENOUGH_STOCK("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."), + NOT_FOUND_PROMOTION("존재하지 않는 프로모션입니다."), + NOT_FOUND_ITEM("존재하지 않는 상품입니다. 다시 입력해 주세요."); + + private static final String PREFIX = "[ERROR] "; + private final String message; + + Errors(String messageFormat, Object... args) { + this.message = PREFIX + String.format(messageFormat, args); + } + + public String message() { + return message; + } +}
Java
에러메세지와 ConstantNumbers의 상수들처럼 대부분이 사용될 수 밖에 없는 관계에서는 와일드 카드를 사용해도 큰 문제 없을것 같다고 생각합니다!
@@ -0,0 +1,19 @@ +package store.discount.membership; + +import static store.constant.ConstantNumbers.MAX_MEMBERSHIP; +import static store.constant.ConstantNumbers.PERCENT_MEMBERSHIP; + +public class MembershipImpl implements Membership { + + @Override + public int discount(int amount) { + double discountAmount = Math.min( + amount * percentToRate(PERCENT_MEMBERSHIP.get()), MAX_MEMBERSHIP.get() + ); + return (int) Math.round(discountAmount); + } + + private double percentToRate(double percent) { + return percent * 0.01; + } +}
Java
네! 멤버십 할인에대한 테스트, 멤버십을 의존하는 테스트를 쉽게하기 위해서도 있고, 할인 정책을 전략으로써 주입할 수 있게 하기 위해 인터페이스와 구현을 분리했습니다!
@@ -0,0 +1,4 @@ +package store.dto; + +public record BuyRequest(String itemName, int amount) { +}
Java
행위(메서드)를 가지지 않고 단순한 데이터로서 활용할 수 있는 점이 좋았습니다! DTO 클래스로 만들어서 getter를 이용하는 것과 차이가 없다고 느껴서, 코드량도 줄고 DTO라는 것을 명확하게 보여줄 수 있는 것 같습니다.
@@ -0,0 +1,50 @@ +package store.model.domain; + +import store.util.CommonValidator; + +public class Stock { + + private final Product product; + private Integer quantity; + + private Stock(Product product, Integer quantity) { + this.product = product; + this.quantity = quantity; + } + + public static Stock of(String name, Integer price, Integer quantity, String promotionName) { + Product product = Product.of(name, price, promotionName); + return new Stock(product, quantity); + } + + public void addQuantity(Integer addQuantity) { + CommonValidator.validateNonNegative(addQuantity); + this.quantity += addQuantity; + } + + public void reduceQuantity(Integer reducedQuantity) { + CommonValidator.validateNonNegative(reducedQuantity); + this.quantity -= reducedQuantity; + CommonValidator.validateNonNegative(this.quantity); + } + + public Product getProduct() { + return product; + } + + public String getProductName() { + return product.getName(); + } + + public Integer getProductPrice() { + return product.getPrice(); + } + + public String getPromotionName() { + return product.getPromotionName(); + } + + public Integer getQuantity() { + return quantity; + } +}
Java
this.quantity - recuedQuantity가 음수가 되는지 먼저 검증 후에 수량을 감소 시키는 방법은 어떻게 생각하시나요? 수량을 감소한 뒤에 음수 검증을 한다면 이미 수량은 음수가 된 상태로 예외가 발생할 것이고 이후에 다시 해당 메서드를 호출하여도 동일한 예외가 발생할 것 같습니다.
@@ -1,7 +1,29 @@ package store; +import store.controller.ConvenienceController; +import store.controller.InventoryController; +import store.model.PromotionManager; +import store.model.StockManager; +import store.model.ReceiptManager; +import store.service.convenience.ConvenienceService; +import store.service.inventory.InventoryService; + public class Application { public static void main(String[] args) { - // TODO: 프로그램 구현 + PromotionManager promotionManager = PromotionManager.getInstance(); + StockManager stockManager = StockManager.getInstance(); + ReceiptManager receiptManager = new ReceiptManager(); + stockManager.clearStocks(); + + InventoryService inventoryService = new InventoryService(promotionManager, stockManager); + ConvenienceService convenienceService = new ConvenienceService(promotionManager, stockManager, receiptManager); + InventoryController inventoryController = new InventoryController(inventoryService); + ConvenienceController convenienceController = new ConvenienceController(convenienceService); + start(inventoryController, convenienceController); + } + + private static void start(InventoryController inventoryController, ConvenienceController convenienceController) { + inventoryController.setup(); + convenienceController.run(); } }
Java
static으로 생성하신 이유가 궁금해요! 또 대부분의 클래스들은 정적팩토리 메서드를 사용하신 것 같은데 소은님의 기준이 궁금합니다ㅎㅎ
@@ -0,0 +1,14 @@ +package store.constant; + +public class ConvenienceConstant { + + public static final int MAX_RETRIES = 3; + public static final int MAX_MEMBERSHIP_DISCOUNT = 8000; + public static final double MEMBERSHIP_DISCOUNT_RATE = 0.3; + public static final String NO_PROMOTION = "null"; + public static final String EMPTY_STRING = ""; + public static final String NOT_IN_STOCK = "재고 없음"; + + public ConvenienceConstant() { + } +}
Java
자주 사용되는 상수들을 별도 클래스로 묶어주셨네요! 👍
@@ -0,0 +1,14 @@ +package store.constant; + +public class ConvenienceConstant { + + public static final int MAX_RETRIES = 3; + public static final int MAX_MEMBERSHIP_DISCOUNT = 8000; + public static final double MEMBERSHIP_DISCOUNT_RATE = 0.3; + public static final String NO_PROMOTION = "null"; + public static final String EMPTY_STRING = ""; + public static final String NOT_IN_STOCK = "재고 없음"; + + public ConvenienceConstant() { + } +}
Java
상수만 유지하는 클래스에 public 생성자를 명시한 이유가 있을까요!?
@@ -0,0 +1,24 @@ +package store.constant; + +public enum InputConstant { + + SQUARE_BRACKETS_PATTERN("[\\[\\]]"), + NUMERIC_PATTERN("\\d+"), + YES_NO_PATTERN("[YyNn]"), + DATE_PATTERN("^\\d{4}-\\d{2}-\\d{2}$"), + PRODUCT_SEPARATOR(","), + DATE_SEPARATOR("-"), + TRUE_STRING("Y"), + EMPTY_STRING(""), + ; + + private final String content; + + InputConstant(String content) { + this.content = content; + } + + public String getContent() { + return content; + } +}
Java
Yes No 입력을 정규표현식을 통해 검증하셨네요! 좋은 방법인 것 같아요 👍
@@ -0,0 +1,18 @@ +package store.constant; + +public enum PathConstant { + + PROMOTION_FILE_PATH("/promotions.md"), + PRODUCT_FILE_PATH("/products.md"), + ; + + private final String path; + + PathConstant(String path) { + this.path = path; + } + + public String getPath() { + return path; + } +}
Java
resources 경로는 루트 경로로 쳐주는군요..! 몰랐네요 👍
@@ -0,0 +1,18 @@ +package store.constant; + +public enum PathConstant { + + PROMOTION_FILE_PATH("/promotions.md"), + PRODUCT_FILE_PATH("/products.md"), + ; + + private final String path; + + PathConstant(String path) { + this.path = path; + } + + public String getPath() { + return path; + } +}
Java
클래스명과 get메서드명에서 Path임을 명시하고 있으니 상수명에서는 `_PATH`를 제외하는 건 어떨까요!?
@@ -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 애노테이션을 활용해보는건 어떨까요?ㅎㅎ