code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,52 @@
+package store.view;
+
+import store.domain.Product;
+import store.domain.Products;
+import store.dto.ReceiptDto;
+
+public class View {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public View(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public String requestProductSelect() {
+ return inputView.requestProductSelect();
+ }
+
+ public String askAdditionalPurchase(Product product) {
+ return inputView.askAdditionalPurchase(product);
+ }
+
+ public String askNoPromotion(Product product, int shortageQuantity) {
+ return inputView.askNoPromotion(product, shortageQuantity);
+ }
+
+ public String askMembership() {
+ return inputView.askMembership();
+ }
+
+ public String askPurchaseAgain() {
+ return inputView.askPurchaseAgain();
+ }
+
+ public void printHello() {
+ outputView.printHello();
+ }
+
+ public void printCurrentProducts(Products products) {
+ outputView.printCurrentProducts(products);
+ }
+
+ public void printReceipt(ReceiptDto receiptDto) {
+ outputView.printReceipt(receiptDto);
+ }
+
+ public void printBlank() {
+ outputView.printBlank();
+ }
+} | Java | controller가 많은 것을 의존하고 있다는 피드백을 받았어서, 최대한 줄여보려 View를 만들었습니다. 중간부터 View의 역할이 없다는 생각이 들었지만 수정할 시간이 없어 그대로 제출했습니다 ㅎㅎ... 좋은 점까지 적어주셔서 감사합니다! |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | name, price는 변경되지 않을 것으로 생각되고,
Stock도 한 번 생성된 객체를 가지고 계속 활용할 것으로 생각했습니다.
그치만 Promotion은 final이 아니면 더 좋을 것 같네요 ㅎㅎ... |
@@ -0,0 +1,64 @@
+package store.domain;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDate;
+import store.dto.PromotionDetailDto;
+
+public class Promotion {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final LocalDate startDate,
+ final LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public boolean isWithinPromotionPeriod() {
+ LocalDate today = DateTimes.now().toLocalDate();
+ return (today.isEqual(startDate) || today.isAfter(startDate))
+ && (today.isEqual(endDate) || today.isBefore(endDate));
+ }
+
+ public int calculateAdditionalPurchase(int purchaseQuantity) {
+ int remain = purchaseQuantity % sumOfBuyAndGet();
+
+ if (remain != 0) {
+ return sumOfBuyAndGet() - remain;
+ }
+
+ return remain;
+ }
+
+ public PromotionDetailDto calculatePromotionAndFree(int requestedQuantity, int promotionStock) {
+ int availablePromotion = (promotionStock / sumOfBuyAndGet()) * sumOfBuyAndGet();
+ return new PromotionDetailDto(availablePromotion, requestedQuantity - availablePromotion);
+ }
+
+ public int calculateFreeQuantity(int requestedQuantity, int promotionStock) {
+ if (requestedQuantity > promotionStock) {
+ return promotionStock / sumOfBuyAndGet();
+ }
+
+ return requestedQuantity / sumOfBuyAndGet();
+ }
+
+ private int sumOfBuyAndGet() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getGet() {
+ return get;
+ }
+} | Java | 좋은 의견인 것 같습니다! 확실히 필드가 간결해질 것 같네요 ㅎ.ㅎ |
@@ -0,0 +1,34 @@
+package store.view;
+
+public enum Sentence {
+
+ PRODUCT_SELECT_STATEMENT("구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])"),
+ HELLO_STATEMENT("안녕하세요. W편의점입니다."),
+ CURRENT_PRODUCTS_STATEMENT("현재 보유하고 있는 상품입니다."),
+ NUMBER_FORMAT("#,###"),
+ PRODUCT_FORMAT("- %s %s원 "),
+ QUANTITY_FORMAT("%s개 "),
+ OUT_OF_STOCK("재고 없음 "),
+ ADDITIONAL_PURCHASE_FORMAT("현재 %s은(는) %d개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)"),
+ NO_PROMOTION_STATEMENT("현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)"),
+ MEMBERSHIP_STATEMENT("멤버십 할인을 받으시겠습니까? (Y/N)"),
+ START_OF_RECEIPT("==============W 편의점================"),
+ HEADER_OF_PURCHASE("상품명\t\t수량\t금액"),
+ PURCHASE_FORMAT("%s\t\t%s \t%s"),
+ HEADER_OF_GIVEN("=============증\t정==============="),
+ GIVEN_FORMAT("%s\t\t%s"),
+ DIVIDE_LINE("===================================="),
+ TOTAL_PRICE_FORMAT("총구매액\t\t%s\t%s"),
+ PROMOTION_DISCOUNT_FORMAT("행사할인\t\t\t-%s"),
+ MEMBERSHIP_DISCOUNT_FORMAT("멤버십할인\t\t\t-%s"),
+ PAY_PRICE_FORMAT("내실돈\t\t\t %s"),
+ PURCHASE_AGAIN_STATEMENT("감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)"),
+ BLANK(""),
+ NEW_LINE(System.lineSeparator());
+
+ final String message;
+
+ Sentence(final String message) {
+ this.message = message;
+ }
+} | Java | 저도 @SeongUk52 님과 마찬가지로 출력 문구들을 상수화 해야하는지 의문이 듭니다.
`OutputView`를 보았을 때 함수명으로 유추가 가능하나, 만약 출력부분을 수정한다고 가능하면, 결코 유지보수가 쉬울 것 같지 않습니다.
#### 역으로 질문 드리고 싶은 것이 있습니다. 테스트 할 때 용이하다고 말씀하셨는데, 출력되는 내용들에 대해 테스트가 필요할까요?
저의 의견을 먼저 말씀드리자면, OutputView는 결국엔 데이터를 시각적으로 표현하는것 외에는 담당하는 것이 없습니다.
OutputView의 본질적인 역할은 데이터를 단순히 표현하는 것에 있으므로, 출력되는 문구 자체가 테스트의 주요 대상이 되기보다는, View에 전달되는 데이터가 올바른지에 중점을 두는 것이 타당하다고 생각합니다.
특히, 출력 문구를 상수화했을 때의 장점이 명확하지 않다면, 오히려 코드가 복잡해지고 유지보수 비용이 늘어날 수 있습니다.
이와 관련하여, 코드 수정 시 규리님이 OutputView의 메서드명 잘 작성하였기 때문에, 메서드 명을 통해 기능을 유추할 수 있는 점은 충분히 장점으로 작용할 수 있을 거라고 생각합니다~!
따라서, OutputView가 단순히 데이터 전달의 최종 단계에 있다고 보고, 이 데이터가 올바르게 전달되는지를 검증하는 데 더 초점을 맞추는 편이 OutputView의 본질적인 역할에 더 부합하는 방식이라 생각합니다. |
@@ -0,0 +1,13 @@
+package store.dto;
+
+import java.util.List;
+
+public record ReceiptDto(
+ List<PurchasedDto> purchasedItems,
+ List<GivenItemDto> givenItems,
+ int totalQuantity,
+ int totalPrice,
+ int promotionDiscountPrice,
+ int membershipDiscountPrice,
+ int payPrice) {
+} | Java | 해당 DTO에 파라미터가 많은 상황인데, Builder패턴을 사용하는건 어떨까요??? |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | record는 기본적으로 데이터 컨테이너 역할에 집중하기 때문에 다소 어울리지 않을 수 있지 않을까 생각합니다.
또한 만약 Product가 상태값을 가져야 하는 상황이 생긴다면 비용이 크게 발생할 수 있을 것 같습니다. |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | 혹시 일반상품과 프로모션 상품의 가격이 다르다면 어떻게 처리가 되나요?? |
@@ -0,0 +1,50 @@
+package store.config;
+
+import store.controller.StoreController;
+import store.service.StoreService;
+import store.util.ProductLoader;
+import store.util.PromotionLoader;
+import store.util.PurchaseItemProcessor;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.View;
+
+public enum AppConfig {
+
+ INSTANCE;
+
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ public StoreController storeController() {
+ return new StoreController(view(), storeService());
+ }
+
+ private StoreService storeService() {
+ return new StoreService(productLoader(), purchaseItemParser());
+ }
+
+ private ProductLoader productLoader() {
+ return new ProductLoader(promotionLoader()
+ .loadPromotions(PROMOTION_FILE_PATH));
+ }
+
+ private PromotionLoader promotionLoader() {
+ return new PromotionLoader();
+ }
+
+ private PurchaseItemProcessor purchaseItemParser() {
+ return new PurchaseItemProcessor();
+ }
+
+ private View view() {
+ return new View(inputView(), outputView());
+ }
+
+ private InputView inputView() {
+ return new InputView();
+ }
+
+ private OutputView outputView() {
+ return new OutputView();
+ }
+} | Java | IOC를 적용한 부분이 좋습니다!
다만, 메서드로 나누지 않아도 충분히 가독성 있는 코드가 될 수 있었을 것 같습니다! |
@@ -0,0 +1,34 @@
+package store.view;
+
+public enum Sentence {
+
+ PRODUCT_SELECT_STATEMENT("구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])"),
+ HELLO_STATEMENT("안녕하세요. W편의점입니다."),
+ CURRENT_PRODUCTS_STATEMENT("현재 보유하고 있는 상품입니다."),
+ NUMBER_FORMAT("#,###"),
+ PRODUCT_FORMAT("- %s %s원 "),
+ QUANTITY_FORMAT("%s개 "),
+ OUT_OF_STOCK("재고 없음 "),
+ ADDITIONAL_PURCHASE_FORMAT("현재 %s은(는) %d개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)"),
+ NO_PROMOTION_STATEMENT("현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)"),
+ MEMBERSHIP_STATEMENT("멤버십 할인을 받으시겠습니까? (Y/N)"),
+ START_OF_RECEIPT("==============W 편의점================"),
+ HEADER_OF_PURCHASE("상품명\t\t수량\t금액"),
+ PURCHASE_FORMAT("%s\t\t%s \t%s"),
+ HEADER_OF_GIVEN("=============증\t정==============="),
+ GIVEN_FORMAT("%s\t\t%s"),
+ DIVIDE_LINE("===================================="),
+ TOTAL_PRICE_FORMAT("총구매액\t\t%s\t%s"),
+ PROMOTION_DISCOUNT_FORMAT("행사할인\t\t\t-%s"),
+ MEMBERSHIP_DISCOUNT_FORMAT("멤버십할인\t\t\t-%s"),
+ PAY_PRICE_FORMAT("내실돈\t\t\t %s"),
+ PURCHASE_AGAIN_STATEMENT("감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)"),
+ BLANK(""),
+ NEW_LINE(System.lineSeparator());
+
+ final String message;
+
+ Sentence(final String message) {
+ this.message = message;
+ }
+} | Java | 좋은 의견 감사합니다!
출력 문구를 테스트해야 하는지에 대해 깊게 고민해 본 적이 없는 것 같습니다...
남겨주신 글을 읽고 나니 생각이 많아지네요.
다만 저에게 있어 OutputView는 단순히 데이터를 전달 받아 출력하는 역할을 담당한다고 생각됩니다. 데이터가 올바르게 전달되는지 검증한다는 것이 어떤 점에서의 검증을 의미하는지 여쭤보고 싶습니다! |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | 그렇다면 dto에서는 record를 사용하는 것이 이점이 될 수 있을까요?
필드들을 final로 가진다면 record로 구현하였는데, 상태가 변할 수 있는 domain들은 class로 구현하는 것이 좋을지 궁금합니다! |
@@ -0,0 +1,13 @@
+package store.dto;
+
+import java.util.List;
+
+public record ReceiptDto(
+ List<PurchasedDto> purchasedItems,
+ List<GivenItemDto> givenItems,
+ int totalQuantity,
+ int totalPrice,
+ int promotionDiscountPrice,
+ int membershipDiscountPrice,
+ int payPrice) {
+} | Java | Builder를 따로 만들기에 시간이 부족했습니다 ㅎ.ㅎ... 리팩토링하며 구현해보겠습니다! |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | 주어진 예시도 그렇고, 같은 상품인데 가격이 다른 상황이 있지 않을 거라 가정했습니다.
실제로 편의점에서 물건을 구입할 때 N + 1 행사를 하는 경우 서로 가격이 다른 경우는 없기 때문입니다. |
@@ -0,0 +1,22 @@
+package store.exception;
+
+import java.util.function.Supplier;
+import store.view.OutputView;
+
+public class ExceptionHandler {
+
+ private static final int MAX_ATTEMPTS = 5;
+
+ public static <T> T getValidInput(final Supplier<T> supplier) {
+ int attempts = 0;
+ while (attempts < MAX_ATTEMPTS) {
+ try {
+ return supplier.get();
+ } catch (IllegalArgumentException e) {
+ attempts++;
+ OutputView.printErrorMessage(e.getMessage());
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.TOO_MANY_INVALID_INPUT.message);
+ }
+}
\ No newline at end of file | Java | posix new line에 대해서 알아보시면 좋을 것 같아요 ! |
@@ -0,0 +1,90 @@
+package store.service;
+
+import java.util.List;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.PurchaseItem;
+import store.dto.GivenItemDto;
+import store.dto.PromotionDetailDto;
+import store.dto.PurchasedDto;
+import store.dto.ReceiptDto;
+import store.util.MembershipCalculator;
+import store.util.ProductLoader;
+import store.util.PurchaseItemProcessor;
+
+public class StoreService {
+
+ private final ProductLoader productLoader;
+ private final PurchaseItemProcessor purchaseItemProcessor;
+
+ public StoreService(ProductLoader productLoader, PurchaseItemProcessor purchaseItemProcessor) {
+ this.productLoader = productLoader;
+ this.purchaseItemProcessor = purchaseItemProcessor;
+ }
+
+ public Products loadProductsFromFile(String productFilePath) {
+ return productLoader.loadProducts(productFilePath);
+ }
+
+ public List<PurchaseItem> parsePurchaseItems(String inputStatement, Products products) {
+ return purchaseItemProcessor.parsePurchaseItems(inputStatement, products);
+ }
+
+ public int calculateMembershipDiscount(int currentPrice, boolean isMember) {
+ if (isMember) {
+ return MembershipCalculator.calculateMembershipDiscount(currentPrice);
+ }
+
+ return 0;
+ }
+
+ public int calculateTotalPrice(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .mapToInt(item -> item.getProduct().calculateTotalPrice(item.getQuantity()))
+ .sum();
+ }
+
+ public int calculatePromotionDiscount(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .mapToInt(purchaseItem -> purchaseItem.getProduct()
+ .calculatePromotionDiscount(purchaseItem.getQuantity()))
+ .sum();
+ }
+
+ public List<PurchasedDto> createPurchasedResults(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .map(PurchasedDto::from)
+ .toList();
+ }
+
+ public List<GivenItemDto> createGivenItems(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .map(GivenItemDto::from)
+ .toList();
+ }
+
+ public synchronized void updateProductStock(List<PurchaseItem> purchaseItems) {
+ purchaseItems.forEach(purchaseItem -> {
+ Product product = purchaseItem.getProduct();
+ int purchasedQuantity = purchaseItem.getQuantity();
+ product.updateStock(purchasedQuantity);
+ });
+ }
+
+ public PromotionDetailDto getPromotionDetail(PurchaseItem purchaseItem) {
+ return PromotionDetailDto.from(purchaseItem);
+ }
+
+ public ReceiptDto generateReceipt(List<PurchaseItem> purchaseItems, boolean isMember) {
+ int totalQuantity = purchaseItems.stream()
+ .mapToInt(PurchaseItem::getQuantity)
+ .sum();
+ int totalPrice = calculateTotalPrice(purchaseItems);
+ int promotionDiscount = calculatePromotionDiscount(purchaseItems);
+ int membershipDiscount = calculateMembershipDiscount(totalPrice - promotionDiscount, isMember);
+
+ return new ReceiptDto(createPurchasedResults(purchaseItems)
+ , createGivenItems(purchaseItems), totalQuantity, totalPrice, promotionDiscount,
+ membershipDiscount, totalPrice - promotionDiscount - membershipDiscount);
+ }
+} | Java | 미래의 멀티쓰레드 환경까지 생각하신 것 같아요 !
하지만 현재는 단일 쓰레드 환경이기 때문에 현재 환경에 맞는 동기화를 유지하는게 좋지 않을까요 ? 어떻게 생각하시는지 궁금해요 |
@@ -0,0 +1,36 @@
+package store.domain;
+
+public class Stock {
+
+ private int promotionStock;
+ private int regularStock;
+
+ public Stock(int promotionStock, int regularStock) {
+ this.promotionStock = promotionStock;
+ this.regularStock = regularStock;
+ }
+
+ public void minusPromotionStock(int quantity) {
+ promotionStock -= quantity;
+ }
+
+ public void minusRegularStock(int quantity) {
+ regularStock -= quantity;
+ }
+
+ public int getRegularStock() {
+ return regularStock;
+ }
+
+ public int getPromotionStock() {
+ return promotionStock;
+ }
+
+ public void setRegularStock(int regularStock) {
+ this.regularStock = regularStock;
+ }
+
+ public void setPromotionStock(int promotionStock) {
+ this.promotionStock = promotionStock;
+ }
+} | Java | Product 클래스의 불변성을 강조하고 싶으시다면 Stock 클래스 또한 setter를 제거하고 새 객체를 만드는 방식으로 하시는건 어떨까요 ? 변동성이 클 경우 리소스 소모가 있기 때문에 고려하시면 좋을 것 같아요 |
@@ -0,0 +1,28 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Products {
+ private List<Product> products;
+
+ public Products(
+ List<Product> products) {
+ this.products = new ArrayList<>(products);
+ }
+
+ public Product findProductByName(String name) {
+ return products.stream()
+ .filter(product -> product.name().equals(name))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void addProduct(Product product) {
+ products.add(product);
+ }
+
+ public List<Product> getProducts() {
+ return products.stream().toList();
+ }
+} | Java | 리스트 자체는 변경할 수 없지만
`Product product = new Product("item1", 100, new Stock(10, 5), null);
product.stock().minusPromotionStock(2);` 처럼 내부 객체는 변경이 가능해요.
Stock을 불변객체로 만드는게 좋을 것 같아요 |
@@ -0,0 +1,60 @@
+package store.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import store.domain.Product;
+import store.exception.ErrorMessage;
+import store.exception.ValidatorBuilder;
+
+public class InputView {
+
+ private static final String YES_ANSWER = "Y";
+ private static final String NO_ANSWER = "N";
+
+ public String requestProductSelect() {
+ System.out.println(Sentence.PRODUCT_SELECT_STATEMENT.message);
+ return Console.readLine();
+ }
+
+ public String askAdditionalPurchase(Product product) {
+ System.out.printf(
+ Sentence.NEW_LINE.message + Sentence.ADDITIONAL_PURCHASE_FORMAT.message + Sentence.NEW_LINE.message,
+ product.name(), product.promotion().getGet());
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ public String askNoPromotion(Product product, int shortageQuantity) {
+ System.out.printf(Sentence.NEW_LINE.message + Sentence.NO_PROMOTION_STATEMENT.message
+ + Sentence.NEW_LINE.message, product.name(), shortageQuantity);
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ public String askMembership() {
+ System.out.println(Sentence.NEW_LINE.message + Sentence.MEMBERSHIP_STATEMENT.message);
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ public String askPurchaseAgain() {
+ System.out.println(Sentence.NEW_LINE.message + Sentence.PURCHASE_AGAIN_STATEMENT.message);
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ void validateInput(String userInput) {
+ ValidatorBuilder.from(userInput)
+ .validate(input -> input == null || input.isBlank(), ErrorMessage.INPUT_NOT_EMPTY)
+ .validate(input -> !input.equals(YES_ANSWER) && !input.equals(
+ NO_ANSWER), ErrorMessage.INVALID_YN_INPUT)
+ .get();
+ }
+} | Java | 컨트롤러에서도 같은 상수를 사용하는데 public으로 사용하면 어떨까요 ? private로 하신 이유가 있으신지 궁금합니다 ! |
@@ -0,0 +1,28 @@
+package store.dto;
+
+import store.domain.Product;
+import store.domain.PurchaseItem;
+
+public record GivenItemDto(
+ String name,
+ int freeQuantity,
+ int price) {
+
+ public static GivenItemDto from(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+ int freeQuantity = calculateFreeQuantity(purchaseItem);
+
+ return new GivenItemDto(product.name(), freeQuantity, product.price());
+ }
+
+ private static int calculateFreeQuantity(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+
+ if (product.promotion() != null) {
+ return product.promotion()
+ .calculateFreeQuantity(purchaseItem.getQuantity(), product.stock().getPromotionStock());
+ }
+
+ return 0;
+ }
+} | Java | DTO는 데이터를 전달하기 위한 객체로 알고 있는데 이렇게 서비스 관련 로직까지 들어있어 이 부분을 밖으로 빼는게 좋을거같은데 어떻게 생각하시나요? |
@@ -0,0 +1,28 @@
+package store.dto;
+
+import store.domain.Product;
+import store.domain.PurchaseItem;
+
+public record GivenItemDto(
+ String name,
+ int freeQuantity,
+ int price) {
+
+ public static GivenItemDto from(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+ int freeQuantity = calculateFreeQuantity(purchaseItem);
+
+ return new GivenItemDto(product.name(), freeQuantity, product.price());
+ }
+
+ private static int calculateFreeQuantity(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+
+ if (product.promotion() != null) {
+ return product.promotion()
+ .calculateFreeQuantity(purchaseItem.getQuantity(), product.stock().getPromotionStock());
+ }
+
+ return 0;
+ }
+} | Java | 정적 팩토리 메서드 패턴을 사용하시는 기준이 궁금합니다! 언제 생성자를 사용하시고 언제 정적 팩토리 메서드 패턴을 사용하시나요? |
@@ -0,0 +1,94 @@
+package store.util;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotion;
+import store.domain.Stock;
+
+public class ProductLoader {
+
+ private static final String SPLITTER = ",";
+ private static final int NAME_INDEX = 0;
+ private static final int PRICE_INDEX = 1;
+ private static final int STOCK_INDEX = 2;
+ private static final int PROMOTION_INDEX = 3;
+
+ private final Map<String, Promotion> promotions;
+
+ public ProductLoader(Map<String, Promotion> promotions) {
+ this.promotions = promotions;
+ }
+
+ public Products loadProducts(String filePath) {
+ Products products = new Products(new ArrayList<>());
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ br.readLine();
+ br.lines().forEach(line -> processLine(line, products));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ return products;
+ }
+
+ private void processLine(String line, Products products) {
+ String[] parts = line.split(SPLITTER);
+ String name = parts[NAME_INDEX];
+ int price = parseNumber(parts[PRICE_INDEX]);
+ int stockQuantity = parseNumber(parts[STOCK_INDEX]);
+ Promotion promotion = parsePromotion(parts[PROMOTION_INDEX]);
+
+ updateOrAddProduct(name, price, stockQuantity, promotion, products);
+ }
+
+ private void updateOrAddProduct(String name, int price, int stockQuantity, Promotion promotion, Products products) {
+ Product existingProduct = products.findProductByName(name);
+
+ if (existingProduct == null) {
+ addNewProduct(name, price, stockQuantity, promotion, products);
+ return;
+ }
+
+ updateStock(existingProduct, stockQuantity, promotion);
+ }
+
+ private void addNewProduct(String name, Integer price, Integer stockQuantity, Promotion promotion,
+ Products products) {
+ if (promotion != null) {
+ Stock stock = new Stock(stockQuantity, 0);
+ products.addProduct(new Product(name, price, stock, promotion));
+ return;
+ }
+
+ Stock stock = new Stock(0, stockQuantity);
+ products.addProduct(new Product(name, price, stock, promotion));
+ }
+
+ private void updateStock(Product product, int stockQuantity, Promotion promotion) {
+ Stock currentStock = product.stock();
+
+ if (promotion != null) {
+ currentStock.setPromotionStock(stockQuantity);
+ return;
+ }
+
+ currentStock.setRegularStock(stockQuantity);
+ }
+
+ private int parseNumber(String number) {
+ try {
+ return Integer.parseInt(number);
+ } catch (NumberFormatException e) {
+ throw e;
+ }
+ }
+
+ private Promotion parsePromotion(String promotionName) {
+ return promotions.get(promotionName);
+ }
+} | Java | 인덱스를 상수화해서 각 인덱스의 의미를 정확히 파악할 수 있네요! 하나 배워갑니다 😊 |
@@ -0,0 +1,64 @@
+package store.domain;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDate;
+import store.dto.PromotionDetailDto;
+
+public class Promotion {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final LocalDate startDate,
+ final LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public boolean isWithinPromotionPeriod() {
+ LocalDate today = DateTimes.now().toLocalDate();
+ return (today.isEqual(startDate) || today.isAfter(startDate))
+ && (today.isEqual(endDate) || today.isBefore(endDate));
+ }
+
+ public int calculateAdditionalPurchase(int purchaseQuantity) {
+ int remain = purchaseQuantity % sumOfBuyAndGet();
+
+ if (remain != 0) {
+ return sumOfBuyAndGet() - remain;
+ }
+
+ return remain;
+ }
+
+ public PromotionDetailDto calculatePromotionAndFree(int requestedQuantity, int promotionStock) {
+ int availablePromotion = (promotionStock / sumOfBuyAndGet()) * sumOfBuyAndGet();
+ return new PromotionDetailDto(availablePromotion, requestedQuantity - availablePromotion);
+ }
+
+ public int calculateFreeQuantity(int requestedQuantity, int promotionStock) {
+ if (requestedQuantity > promotionStock) {
+ return promotionStock / sumOfBuyAndGet();
+ }
+
+ return requestedQuantity / sumOfBuyAndGet();
+ }
+
+ private int sumOfBuyAndGet() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getGet() {
+ return get;
+ }
+} | Java | 좋은 의견인거 같습니다! 저도 하나 배워가네요 |
@@ -0,0 +1,28 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Products {
+ private List<Product> products;
+
+ public Products(
+ List<Product> products) {
+ this.products = new ArrayList<>(products);
+ }
+
+ public Product findProductByName(String name) {
+ return products.stream()
+ .filter(product -> product.name().equals(name))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void addProduct(Product product) {
+ products.add(product);
+ }
+
+ public List<Product> getProducts() {
+ return products.stream().toList();
+ }
+} | Java | 저는 null을 반환하는 것보다 Optional을 통해 null이 발생할 수 있음을 확실히 알리는 것을 선호합니다. 현재는 개인 혼자 개발하기에 null이 발생할 수 있음을 알고 로직을 작성할 수 있습니다. 하지만 만약 협업 상황에서 처음 클래스의 메소드를 보면 보통 메소드 명, 파라미터, 리턴 타입으로 메소드의 역할과 기능을 파악하게 되는데 null이 발생하는지 로직을 세부적으로 읽어봐야하는 상황이 발생합니다. 이에 대비하여 Optional을 통해 null이 발생할 수 있음을 알립니다! 저의 개인적인 생각이니 참고만 부탁드릴게요 ㅎㅎ 😊 |
@@ -0,0 +1,50 @@
+package store.exception;
+
+import java.util.function.Predicate;
+
+public class ValidatorBuilder<T> {
+
+ private final T value;
+ private int numericValue;
+
+ private ValidatorBuilder(final T Value) {
+ this.value = Value;
+ }
+
+ public static <T> ValidatorBuilder<T> from(final T Value) {
+ return new ValidatorBuilder<T>(Value);
+ }
+
+ public ValidatorBuilder<T> validate(final Predicate<T> condition, final ErrorMessage errorMessage) {
+ if (condition.test(value)) {
+ throw new IllegalArgumentException(errorMessage.message);
+ }
+
+ return this;
+ }
+
+ public ValidatorBuilder<T> validateInteger(final Predicate<Integer> condition, final ErrorMessage errorMessage) {
+ if (condition.test(numericValue)) {
+ throw new IllegalArgumentException(errorMessage.message);
+ }
+
+ return this;
+ }
+
+ public ValidatorBuilder<T> validateIsInteger() {
+ try {
+ numericValue = Integer.parseInt(value.toString());
+ return this;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(ErrorMessage.PURCHASE_QUANTITY_NOT_INTEGER.message);
+ }
+ }
+
+ public T get() {
+ return value;
+ }
+
+ public int getNumericValue() {
+ return numericValue;
+ }
+} | Java | 제네릭 활용을 잘 하시네요! 👍 |
@@ -1,7 +1,15 @@
package store;
+import java.io.IOException;
+import store.controller.StoreManager;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ try {
+ StoreManager storeManager = new StoreManager();
+ storeManager.run();
+ } catch (IOException e) {
+ System.err.println("[ERROR] 프로그램 실행 중 오류가 발생했습니다: " + e.getMessage());
+ }
}
} | Java | 해당 예외는 Controller에서 처리해주는건 어떨까요? |
@@ -0,0 +1,38 @@
+package store.view;
+
+import camp.nextstep.edu.missionutils.Console;
+
+public class InputView {
+
+ public String readPurchaseList() {
+ String message = "\n구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])";
+ return prompt(message);
+ }
+
+ public String readAdditionalPromotion(String productName, int quantity) {
+ String message = String.format("\n현재 %s %d개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)", productName, quantity);
+ return prompt(message);
+ }
+
+ public String readProceedWithoutPromotion(String productName, int quantity) {
+ String message = String.format("\n현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)", productName, quantity);
+ return prompt(message);
+
+ }
+
+ public String readMembershipDiscount() {
+ String message = "\n멤버십 할인을 받으시겠습니까? (Y/N)";
+ return prompt(message);
+
+ }
+
+ public String readContinueShopping() {
+ String message = "\n감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)";
+ return prompt(message);
+ }
+
+ private String prompt(String message) {
+ System.out.println(message);
+ return Console.readLine();
+ }
+} | Java | 사용하는 문자열을 상수화 해주는건 어떨까요? |
@@ -0,0 +1,19 @@
+name,price,quantity,promotion
+콜라,1000,10,탄산2+1
+콜라,1000,10,null
+사이다,1000,8,탄산2+1
+사이다,1000,7,null
+오렌지주스,1800,9,MD추천상품
+오렌지주스,1800,0,null
+탄산수,1200,5,탄산2+1
+탄산수,1200,0,null
+물,500,10,null
+비타민워터,1500,6,null
+감자칩,1500,5,반짝할인
+감자칩,1500,5,null
+초코바,1200,5,MD추천상품
+초코바,1200,5,null
+에너지바,2000,5,null
+정식도시락,6400,8,null
+컵라면,1700,1,MD추천상품
+컵라면,1700,10,null | Unknown | 파일 이름을 변경했을때 테스트가 실패하지는 않았나요? |
@@ -0,0 +1,18 @@
+package store.handler;
+
+public enum ErrorHandler {
+ INVALID_FORMAT("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요."),
+ PRODUCT_NOT_FOUND("존재하지 않는 상품입니다. 다시 입력해 주세요."),
+ QUANTITY_EXCEEDS_STOCK("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."),
+ GENERIC_INVALID_INPUT("잘못된 입력입니다. 다시 입력해 주세요.");
+
+ private final String message;
+
+ ErrorHandler(String message) {
+ this.message = message;
+ }
+
+ public IllegalArgumentException getException() {
+ return new IllegalArgumentException(message);
+ }
+} | Java | enum을 이용한 예외처리 좋은 것 같습니다👍👍 |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | 파일 입출력은 view의 역할이라고 생각하는데 어떻게 생각하시나요!? |
@@ -0,0 +1,53 @@
+package store.handler;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Promotion;
+
+public class PromotionsFileHandler {
+ private static final Path PROMOTIONS_FILE_PATH = Path.of("src/main/resources/promotions.md");
+ public static final String NON_PROMOTION_NAME = "null";
+ public static final Promotion NON_PROMOTION = new Promotion(NON_PROMOTION_NAME, 1, 0);
+ private static final Map<String, Promotion> promotions = new HashMap<>();
+
+ public void loadPromotions() throws IOException {
+ List<String> lines = Files.readAllLines(PROMOTIONS_FILE_PATH);
+ promotions.put(NON_PROMOTION_NAME, NON_PROMOTION);
+ lines.stream().skip(1).forEach(this::processPromotionLine); // Skip header line
+ }
+
+ private void processPromotionLine(String line) {
+ String[] parts = parseAndTrimLine(line);
+ String name = parts[0];
+ int discountRate = Integer.parseInt(parts[1]);
+ int limit = Integer.parseInt(parts[2]);
+
+ if (isPromotionValid(parts)) {
+ promotions.put(name, new Promotion(name, discountRate, limit));
+ }
+ }
+
+ private String[] parseAndTrimLine(String line) {
+ return Arrays.stream(line.split(","))
+ .map(String::trim)
+ .toArray(String[]::new);
+ }
+
+ private boolean isPromotionValid(String[] parts) {
+ LocalDate today = DateTimes.now().toLocalDate();
+ LocalDate startDate = LocalDate.parse(parts[3]);
+ LocalDate endDate = LocalDate.parse(parts[4]);
+ return !today.isBefore(startDate) && !today.isAfter(endDate);
+ }
+
+ public static Promotion getPromotionByName(String name) {
+ return promotions.getOrDefault(name, promotions.get(NON_PROMOTION_NAME));
+ }
+} | Java | 주석보다는 메소드의 이름으로 명시해보는건 어떨까요? |
@@ -0,0 +1,34 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class Cart {
+ private final List<CartItem> items = new ArrayList<>();
+
+ public void addItem(CartItem item) {
+ items.add(item);
+ }
+
+ public List<CartItem> getItems() {
+ return Collections.unmodifiableList(items);
+ }
+
+ public int totalQuantity() {
+ return items.stream().mapToInt(CartItem::calcTotalQuantity).sum();
+ }
+
+ public int totalPrice() {
+ return items.stream().mapToInt(CartItem::totalPrice).sum();
+ }
+
+ public int totalRetailPrice() {
+ return items.stream().mapToInt(CartItem::totalRetailPrice).sum();
+ }
+
+ public int totalFreePrice() {
+ return items.stream().mapToInt(CartItem::totalFreePrice).sum();
+ }
+}
+ | Java | 전체적으로 Model이 해당 도메인에 대한 비즈니스 로직을 수행하기 보다는 Dataclass처럼 사용되고 있는 것 같아요!
어울리는 로직들을 Model로 옮겨올 수 있을 것 같아요 |
@@ -0,0 +1,38 @@
+package store.service;
+
+import store.controller.CartManager;
+import store.domain.Cart;
+import store.domain.Receipt;
+
+public class PaymentService {
+ private static final double MEMBERSHIP_DISCOUNT_RATE = 0.3;
+ private final static int MEMBERSHIP_DISCOUNT_LIMIT = 8000;
+
+ private final CartManager cartManager;
+ private int membershipDiscountBalance;
+
+ public PaymentService(CartManager cartManager) {
+ this.cartManager = cartManager;
+ this.membershipDiscountBalance = MEMBERSHIP_DISCOUNT_LIMIT;
+ }
+
+ public Cart getCartItems(String purchaseList) {
+ return cartManager.generateCart(purchaseList);
+ }
+
+ public Receipt createReceipt(Cart cart, boolean applyMembership) {
+ int membershipDiscount = calcMembershipDiscount(applyMembership, cart.totalRetailPrice());
+ return new Receipt(cart, cart.totalPrice(), cart.totalFreePrice(), membershipDiscount);
+ }
+
+ private int calcMembershipDiscount(boolean apply, int eligibleAmount) {
+ if (apply) {
+ int discountAmount = Math.min((int) (eligibleAmount * MEMBERSHIP_DISCOUNT_RATE),
+ membershipDiscountBalance);
+ membershipDiscountBalance -= discountAmount;
+
+ return discountAmount;
+ }
+ return 0;
+ }
+} | Java | 라인 포맷팅을 더 이쁘게 할 수 있을 것 같아요!
모듈화 하는 것도 방법인것 같아요😃
```suggestion
int discountAmount = Math.min(
(int) (eligibleAmount * MEMBERSHIP_DISCOUNT_RATE),
membershipDiscountBalance
);
``` |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | 전체적으로 비즈니스 로직이 Controller에 작성되어있는 느낌이 듭니다! 별도의 Service에 책임을 분리해보는건 어떨까요? |
@@ -1,7 +1,15 @@
package store;
+import java.io.IOException;
+import store.controller.StoreManager;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ try {
+ StoreManager storeManager = new StoreManager();
+ storeManager.run();
+ } catch (IOException e) {
+ System.err.println("[ERROR] 프로그램 실행 중 오류가 발생했습니다: " + e.getMessage());
+ }
}
} | Java | 출력은 OutputView에서 처리하는 것이 적절해보입니다! |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | `replaceAll("[\\[\\]]", "")` 변환대상인 문자열이 어떤 의미를 가지고 있는지 상수로 나타내주시면 좋을 것 같습니다! |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | `remainingCnt` Cnt 정도면 충분히 어떤 의미로 작성된 것인지 알 수 있지만, 가급적이면 좀 길더라도 Count라는
풀네임을 써주셔도 좋을 것 같습니다! |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | `isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()`
if문 내에 여러 조건을 검증하는 것이 보여지니까 읽는 입장에서 다소 복잡하게 느껴질 수 있을 것 같습니다.
해당 조건들을 검증하는 하나의 메서드를 정의하여 사용해주시면 눈에 더 잘 들어올 것 같단 생각이 듭니다! |
@@ -0,0 +1,99 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.GENERIC_INVALID_INPUT;
+import static store.handler.ErrorHandler.INVALID_FORMAT;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.function.Supplier;
+import java.util.regex.Pattern;
+import store.domain.Cart;
+import store.domain.Product;
+import store.domain.Receipt;
+import store.service.PaymentService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreManager {
+ private static final Pattern PURCHASE_LIST_PATTERN = Pattern.compile(
+ "\\[(\\p{L}+)-(\\d+)](,\\[(\\p{L}+)-(\\d+)])*");
+
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final PaymentService paymentService;
+ private final List<Product> products;
+
+ public StoreManager() throws IOException {
+ CartManager cartManager = new CartManager();
+ paymentService = new PaymentService(cartManager);
+ products = cartManager.getAllProducts();
+ }
+
+ public void run() {
+ boolean continueShopping;
+ do {
+ displayStoreProducts();
+ Cart cart = getValidCart();
+ boolean applyMembership = getMembershipStatus();
+ processPayment(cart, applyMembership);
+ continueShopping = checkContinueShopping();
+ } while (continueShopping);
+ }
+
+ private void displayStoreProducts() {
+ outputView.printWelcomeMessage();
+ outputView.printStockOverviewMessage();
+ outputView.printStockItemDetails(products);
+ }
+
+ private Cart getValidCart() {
+ return repeatUntilSuccess(() -> {
+ String purchaseList = inputView.readPurchaseList();
+ validatePurchaseList(purchaseList);
+ return paymentService.getCartItems(purchaseList);
+ });
+ }
+
+ private boolean getMembershipStatus() {
+ return repeatUntilSuccess(() -> {
+ String input = inputView.readMembershipDiscount();
+ validateYesNoInput(input);
+ return input.equals("Y");
+ });
+ }
+
+ private void processPayment(Cart cart, boolean applyMembership) {
+ Receipt receipt = paymentService.createReceipt(cart, applyMembership);
+ outputView.printReceipt(receipt);
+ }
+
+ private boolean checkContinueShopping() {
+ return repeatUntilSuccess(() -> {
+ String input = inputView.readContinueShopping();
+ validateYesNoInput(input);
+ return input.equals("Y");
+ });
+ }
+
+ private void validatePurchaseList(String input) {
+ if (!PURCHASE_LIST_PATTERN.matcher(input).matches()) {
+ throw INVALID_FORMAT.getException();
+ }
+ }
+
+ private void validateYesNoInput(String input) {
+ if (!input.equals("Y") && !input.equals("N")) {
+ throw GENERIC_INVALID_INPUT.getException();
+ }
+ }
+
+ private <T> T repeatUntilSuccess(Supplier<T> supplier) {
+ while (true) {
+ try {
+ return supplier.get();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | 함수형 인터페이스를 사용해서 반복로직을 감소시켜주셨네요! 👍👍 |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | 1을 상수로 정의해주시면 스킵하는 부분이 어느 부분인지 알기 쉬울 것 같습니다 |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | `0`이 의미하는 바가 무엇인지 알 수 있을까요? |
@@ -0,0 +1,53 @@
+package store.handler;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Promotion;
+
+public class PromotionsFileHandler {
+ private static final Path PROMOTIONS_FILE_PATH = Path.of("src/main/resources/promotions.md");
+ public static final String NON_PROMOTION_NAME = "null";
+ public static final Promotion NON_PROMOTION = new Promotion(NON_PROMOTION_NAME, 1, 0);
+ private static final Map<String, Promotion> promotions = new HashMap<>();
+
+ public void loadPromotions() throws IOException {
+ List<String> lines = Files.readAllLines(PROMOTIONS_FILE_PATH);
+ promotions.put(NON_PROMOTION_NAME, NON_PROMOTION);
+ lines.stream().skip(1).forEach(this::processPromotionLine); // Skip header line
+ }
+
+ private void processPromotionLine(String line) {
+ String[] parts = parseAndTrimLine(line);
+ String name = parts[0];
+ int discountRate = Integer.parseInt(parts[1]);
+ int limit = Integer.parseInt(parts[2]);
+
+ if (isPromotionValid(parts)) {
+ promotions.put(name, new Promotion(name, discountRate, limit));
+ }
+ }
+
+ private String[] parseAndTrimLine(String line) {
+ return Arrays.stream(line.split(","))
+ .map(String::trim)
+ .toArray(String[]::new);
+ }
+
+ private boolean isPromotionValid(String[] parts) {
+ LocalDate today = DateTimes.now().toLocalDate();
+ LocalDate startDate = LocalDate.parse(parts[3]);
+ LocalDate endDate = LocalDate.parse(parts[4]);
+ return !today.isBefore(startDate) && !today.isAfter(endDate);
+ }
+
+ public static Promotion getPromotionByName(String name) {
+ return promotions.getOrDefault(name, promotions.get(NON_PROMOTION_NAME));
+ }
+} | Java | `today.isAfter(startDate) && today.isBefore(endDate);`은 어떨까요?
개인적으로 ! 연산자가 들어가면 코드를 보는 입장에서 한번 더 생각을 하게 만드는 것 같습니다 |
@@ -0,0 +1,59 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+
+public class StocksFileHandler {
+ private static final Path STOCKS_FILE_PATH = Path.of("src/main/resources/stocks.md");
+
+ private final ProductsFileHandler productsFileHandler;
+
+ public StocksFileHandler() {
+ this.productsFileHandler = new ProductsFileHandler(STOCKS_FILE_PATH);
+ }
+
+ public List<Product> loadStocks() throws IOException {
+ ensureStocksFileExists();
+ productsFileHandler.loadLatestProductsFile();
+ updateStocksFile();
+ return productsFileHandler.parseItemsFromFile(STOCKS_FILE_PATH);
+ }
+
+ private void ensureStocksFileExists() throws IOException {
+ if (Files.notExists(STOCKS_FILE_PATH)) {
+ Files.createFile(STOCKS_FILE_PATH);
+ }
+ }
+
+ private void updateStocksFile() throws IOException {
+ Map<String, Product> productMap = buildProductsMap();
+ writeProductsToStocksFile(productMap);
+ }
+
+ private Map<String, Product> buildProductsMap() throws IOException {
+ List<Product> products = productsFileHandler.parseItemsFromFile(STOCKS_FILE_PATH);
+ Map<String, Product> productMap = new LinkedHashMap<>();
+ for (Product product : products) {
+ productMap.merge(product.getKeyForMap(), product, this::mergeProducts);
+ }
+ return productMap;
+ }
+
+ private Product mergeProducts(Product existing, Product toAdd) {
+ return new Product(existing.getName(), existing.getPrice(),
+ existing.getQuantity() + toAdd.getQuantity(), existing.getPromotion());
+ }
+
+ private void writeProductsToStocksFile(Map<String, Product> productMap) throws IOException {
+ List<String> lines = new ArrayList<>();
+ lines.add(ProductsFileHandler.HEADER);
+ productMap.values().forEach(product -> lines.add(productsFileHandler.formatProductLine(product)));
+ Files.write(STOCKS_FILE_PATH, lines);
+ }
+} | Java | 변수명에 자료형이 들어가는 것은 지양하는 것이 좋다고 들었습니다! |
@@ -0,0 +1,38 @@
+package store.service;
+
+import store.controller.CartManager;
+import store.domain.Cart;
+import store.domain.Receipt;
+
+public class PaymentService {
+ private static final double MEMBERSHIP_DISCOUNT_RATE = 0.3;
+ private final static int MEMBERSHIP_DISCOUNT_LIMIT = 8000;
+
+ private final CartManager cartManager;
+ private int membershipDiscountBalance;
+
+ public PaymentService(CartManager cartManager) {
+ this.cartManager = cartManager;
+ this.membershipDiscountBalance = MEMBERSHIP_DISCOUNT_LIMIT;
+ }
+
+ public Cart getCartItems(String purchaseList) {
+ return cartManager.generateCart(purchaseList);
+ }
+
+ public Receipt createReceipt(Cart cart, boolean applyMembership) {
+ int membershipDiscount = calcMembershipDiscount(applyMembership, cart.totalRetailPrice());
+ return new Receipt(cart, cart.totalPrice(), cart.totalFreePrice(), membershipDiscount);
+ }
+
+ private int calcMembershipDiscount(boolean apply, int eligibleAmount) {
+ if (apply) {
+ int discountAmount = Math.min((int) (eligibleAmount * MEMBERSHIP_DISCOUNT_RATE),
+ membershipDiscountBalance);
+ membershipDiscountBalance -= discountAmount;
+
+ return discountAmount;
+ }
+ return 0;
+ }
+} | Java | 접근 제어자 작성 순서가 `static final`로 통일되는 것이 좋을 것 같습니다 |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | 편의점의 파일 입출력은 데이터 소스 관리에 가까워 handler나 repository의 역할에 더 가까운 것 같습니다..! |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | 재고가 없는 경우 상품의 수량을 의미합니다! 이것도 별도의 상수로 처리하면 좋았을 것 같네요. |
@@ -0,0 +1,53 @@
+package store.handler;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Promotion;
+
+public class PromotionsFileHandler {
+ private static final Path PROMOTIONS_FILE_PATH = Path.of("src/main/resources/promotions.md");
+ public static final String NON_PROMOTION_NAME = "null";
+ public static final Promotion NON_PROMOTION = new Promotion(NON_PROMOTION_NAME, 1, 0);
+ private static final Map<String, Promotion> promotions = new HashMap<>();
+
+ public void loadPromotions() throws IOException {
+ List<String> lines = Files.readAllLines(PROMOTIONS_FILE_PATH);
+ promotions.put(NON_PROMOTION_NAME, NON_PROMOTION);
+ lines.stream().skip(1).forEach(this::processPromotionLine); // Skip header line
+ }
+
+ private void processPromotionLine(String line) {
+ String[] parts = parseAndTrimLine(line);
+ String name = parts[0];
+ int discountRate = Integer.parseInt(parts[1]);
+ int limit = Integer.parseInt(parts[2]);
+
+ if (isPromotionValid(parts)) {
+ promotions.put(name, new Promotion(name, discountRate, limit));
+ }
+ }
+
+ private String[] parseAndTrimLine(String line) {
+ return Arrays.stream(line.split(","))
+ .map(String::trim)
+ .toArray(String[]::new);
+ }
+
+ private boolean isPromotionValid(String[] parts) {
+ LocalDate today = DateTimes.now().toLocalDate();
+ LocalDate startDate = LocalDate.parse(parts[3]);
+ LocalDate endDate = LocalDate.parse(parts[4]);
+ return !today.isBefore(startDate) && !today.isAfter(endDate);
+ }
+
+ public static Promotion getPromotionByName(String name) {
+ return promotions.getOrDefault(name, promotions.get(NON_PROMOTION_NAME));
+ }
+} | Java | 메서드의 이름으로 어떻게 명시하면 될까요? 별도의 메서드로 분리하라는 의미이실까요? |
@@ -0,0 +1,19 @@
+name,price,quantity,promotion
+콜라,1000,10,탄산2+1
+콜라,1000,10,null
+사이다,1000,8,탄산2+1
+사이다,1000,7,null
+오렌지주스,1800,9,MD추천상품
+오렌지주스,1800,0,null
+탄산수,1200,5,탄산2+1
+탄산수,1200,0,null
+물,500,10,null
+비타민워터,1500,6,null
+감자칩,1500,5,반짝할인
+감자칩,1500,5,null
+초코바,1200,5,MD추천상품
+초코바,1200,5,null
+에너지바,2000,5,null
+정식도시락,6400,8,null
+컵라면,1700,1,MD추천상품
+컵라면,1700,10,null | Unknown | 원본 products.md 파일은 파일 이름과 데이터를 아예 변경하지 않았습니다! product.md로 새로운 stocks.md 파일을 생성해 상품 데이터 처리를 했습니다! |
@@ -26,11 +26,32 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
- compileOnly 'org.projectlombok:lombok'
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ implementation 'org.springframework.boot:spring-boot-starter-validation'
+ implementation 'org.springframework.boot:spring-boot-starter-mail'
+
+ // jwt
+ implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5'
+
+ // MapStruct
+ implementation 'org.mapstruct:mapstruct:1.4.2.Final'
+ annotationProcessor "org.mapstruct:mapstruct-processor:1.4.2.Final"
+ annotationProcessor "org.projectlombok:lombok-mapstruct-binding:0.1.0"
+
+ // H2
runtimeOnly 'com.h2database:h2'
+
+ // Lombok
+ compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
+
+ // Test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
+
+
}
tasks.named('test') { | Unknown | Gradle 형식이 일치하지 않습니다.
다른 곳과 동일하게 조정해주세요.
```groovy
implementaion 'io.jsonwebtoken:jjwt-api:0.11.5'
``` |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.event.ResetPasswordEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberResetService {
+
+ private final MemberProcessor memberProcessor;
+
+ private static final String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SPECIAL_CHARACTERS = "!@#$%^&*()\\-_=+";
+ private static final int MAX_SPECIAL_CHARACTER = 3;
+ private static final int MIN_LENGTH = 8;
+ private static final int MAX_LENGTH = 16;
+
+ @Transactional
+ public void resetPassword(final MemberPasswordResetDto.Command request) {
+ String resetPassword = createResetPassword();
+
+ memberProcessor.resetPassword(new MemberPasswordResetDto.Command(request.getEmail(), resetPassword));
+
+ Events.raise(ResetPasswordEvent.of(request.getEmail(), resetPassword));
+ }
+
+ public String createResetPassword() {
+ Random random = new SecureRandom();
+ final int passwordLength = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
+ StringBuilder password = new StringBuilder(passwordLength);
+
+ int specialCharacterLength = addSpecialCharacters(password);
+ addValidCharacters(specialCharacterLength, passwordLength, password);
+
+ return shufflePassword(password);
+ }
+
+ private String shufflePassword(final StringBuilder password) {
+ List<Character> characters = password.toString().chars()
+ .mapToObj(i -> (char)i)
+ .collect(Collectors.toList());
+ Collections.shuffle(characters);
+ StringBuilder result = new StringBuilder(characters.size());
+ characters.forEach(result::append);
+
+ return result.toString();
+ }
+
+ private void addValidCharacters(final int specialCharacterLength, final int passwordLength,
+ final StringBuilder password) {
+ Random random = new SecureRandom();
+ for (int i = specialCharacterLength; i < passwordLength; i++) {
+ int index = random.nextInt(VALID_CHARACTERS.length());
+ password.append(VALID_CHARACTERS.charAt(index));
+ }
+ }
+
+ private int addSpecialCharacters(final StringBuilder password) {
+ Random random = new SecureRandom();
+ final int specialCharacterLength = random.nextInt(MAX_SPECIAL_CHARACTER) + 1;
+
+ for (int i = 0; i < specialCharacterLength; i++) {
+ password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
+ }
+
+ return specialCharacterLength;
+ }
+} | Java | `@Transactional` 어노테이션을 클래스 레벨로 올리는게 맞는지에 대해서는 의문이 듭니다.
- DB에 접근하지 않는 메서드를 수행할 때도 `@Transactional` 에 의해 앞뒤로 추가 로직이 실행되며.
- readonly 가 아닌 경우엔 아래에서 어차피 또 사용하는지라 불필요한 코드가 늘어나는게 아닌가 싶습니다. |
@@ -0,0 +1,30 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import java.util.List;
+
+import io.study.springbootlayered.api.member.domain.entity.AuthorityType;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.entity.MemberAuthority;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberDetailDto {
+
+ @Getter
+ @RequiredArgsConstructor
+ public static class Info {
+ private final String email;
+ private final String nickname;
+ private final List<AuthorityType> roles;
+
+ public static MemberDetailDto.Info of(Member member) {
+ List<AuthorityType> roles = member.getAuthorities().stream()
+ .map(MemberAuthority::getAuthority)
+ .toList();
+ return new MemberDetailDto.Info(member.getEmail(), member.getNickname(), roles);
+ }
+ }
+} | Java | Gradle 설정에 의하면 Java 버전이 21인데, 충분히 Record로 대체 가능한 코드로 보입니다. |
@@ -0,0 +1,30 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import java.util.List;
+
+import io.study.springbootlayered.api.member.domain.entity.AuthorityType;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.entity.MemberAuthority;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberDetailDto {
+
+ @Getter
+ @RequiredArgsConstructor
+ public static class Info {
+ private final String email;
+ private final String nickname;
+ private final List<AuthorityType> roles;
+
+ public static MemberDetailDto.Info of(Member member) {
+ List<AuthorityType> roles = member.getAuthorities().stream()
+ .map(MemberAuthority::getAuthority)
+ .toList();
+ return new MemberDetailDto.Info(member.getEmail(), member.getNickname(), roles);
+ }
+ }
+} | Java | Validation 을 사용해서 빈값이 들어오지 않도록 하면 좋겠네요. |
@@ -0,0 +1,19 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import lombok.AccessLevel;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberPasswordResetDto {
+
+ @Getter
+ @Builder
+ @RequiredArgsConstructor
+ public static class Command {
+ private final String email;
+ private final String password;
+ }
+} | Java | 필드가 두개인데 굳이 빌더를 사용해야 하나 싶은데요,
당장 바로 아래의 MemberSigninDto 에서는 `@Builder`가 없네요. |
@@ -0,0 +1,19 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import lombok.AccessLevel;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberPasswordResetDto {
+
+ @Getter
+ @Builder
+ @RequiredArgsConstructor
+ public static class Command {
+ private final String email;
+ private final String password;
+ }
+} | Java | 모든 Dto가 내부적으로 또 Dto를 갖고 있는 이상한 구조네요...
그냥 서로 다른 파일로 분리하는게 가독성 측면에서 더 낫지 않을까요?
특히나 내부적으로 같은 이름을 쓰고 있기 때문에, 행여나 실수로 Static Import를 하는 순간 이게 어디에서 온건지 파악할 방법이 아예 없어집니다. |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.event.ResetPasswordEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberResetService {
+
+ private final MemberProcessor memberProcessor;
+
+ private static final String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SPECIAL_CHARACTERS = "!@#$%^&*()\\-_=+";
+ private static final int MAX_SPECIAL_CHARACTER = 3;
+ private static final int MIN_LENGTH = 8;
+ private static final int MAX_LENGTH = 16;
+
+ @Transactional
+ public void resetPassword(final MemberPasswordResetDto.Command request) {
+ String resetPassword = createResetPassword();
+
+ memberProcessor.resetPassword(new MemberPasswordResetDto.Command(request.getEmail(), resetPassword));
+
+ Events.raise(ResetPasswordEvent.of(request.getEmail(), resetPassword));
+ }
+
+ public String createResetPassword() {
+ Random random = new SecureRandom();
+ final int passwordLength = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
+ StringBuilder password = new StringBuilder(passwordLength);
+
+ int specialCharacterLength = addSpecialCharacters(password);
+ addValidCharacters(specialCharacterLength, passwordLength, password);
+
+ return shufflePassword(password);
+ }
+
+ private String shufflePassword(final StringBuilder password) {
+ List<Character> characters = password.toString().chars()
+ .mapToObj(i -> (char)i)
+ .collect(Collectors.toList());
+ Collections.shuffle(characters);
+ StringBuilder result = new StringBuilder(characters.size());
+ characters.forEach(result::append);
+
+ return result.toString();
+ }
+
+ private void addValidCharacters(final int specialCharacterLength, final int passwordLength,
+ final StringBuilder password) {
+ Random random = new SecureRandom();
+ for (int i = specialCharacterLength; i < passwordLength; i++) {
+ int index = random.nextInt(VALID_CHARACTERS.length());
+ password.append(VALID_CHARACTERS.charAt(index));
+ }
+ }
+
+ private int addSpecialCharacters(final StringBuilder password) {
+ Random random = new SecureRandom();
+ final int specialCharacterLength = random.nextInt(MAX_SPECIAL_CHARACTER) + 1;
+
+ for (int i = 0; i < specialCharacterLength; i++) {
+ password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
+ }
+
+ return specialCharacterLength;
+ }
+} | Java | 결국 `SpecialCharactes` 와 `ValidCharacters` 의 조합으로 구성된다고 볼 수 있겠네요.
- 어차피 문자열 섞는건 똑같습니다.
```java
private String createRandomString(String baseStr, int length) {
return random.ints(length, 0, baseStr.length())
.mapToObj(baseStr::charAt)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
```
- 그러면, 우리는 길이만 정하면 되겠네요. 굳이 분리된 메서드가 아니라, 저 둘의 길이를 미리 정하고 저 메서드를 호출해버리면 훨씬 낫겠죠? |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.event.ResetPasswordEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberResetService {
+
+ private final MemberProcessor memberProcessor;
+
+ private static final String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SPECIAL_CHARACTERS = "!@#$%^&*()\\-_=+";
+ private static final int MAX_SPECIAL_CHARACTER = 3;
+ private static final int MIN_LENGTH = 8;
+ private static final int MAX_LENGTH = 16;
+
+ @Transactional
+ public void resetPassword(final MemberPasswordResetDto.Command request) {
+ String resetPassword = createResetPassword();
+
+ memberProcessor.resetPassword(new MemberPasswordResetDto.Command(request.getEmail(), resetPassword));
+
+ Events.raise(ResetPasswordEvent.of(request.getEmail(), resetPassword));
+ }
+
+ public String createResetPassword() {
+ Random random = new SecureRandom();
+ final int passwordLength = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
+ StringBuilder password = new StringBuilder(passwordLength);
+
+ int specialCharacterLength = addSpecialCharacters(password);
+ addValidCharacters(specialCharacterLength, passwordLength, password);
+
+ return shufflePassword(password);
+ }
+
+ private String shufflePassword(final StringBuilder password) {
+ List<Character> characters = password.toString().chars()
+ .mapToObj(i -> (char)i)
+ .collect(Collectors.toList());
+ Collections.shuffle(characters);
+ StringBuilder result = new StringBuilder(characters.size());
+ characters.forEach(result::append);
+
+ return result.toString();
+ }
+
+ private void addValidCharacters(final int specialCharacterLength, final int passwordLength,
+ final StringBuilder password) {
+ Random random = new SecureRandom();
+ for (int i = specialCharacterLength; i < passwordLength; i++) {
+ int index = random.nextInt(VALID_CHARACTERS.length());
+ password.append(VALID_CHARACTERS.charAt(index));
+ }
+ }
+
+ private int addSpecialCharacters(final StringBuilder password) {
+ Random random = new SecureRandom();
+ final int specialCharacterLength = random.nextInt(MAX_SPECIAL_CHARACTER) + 1;
+
+ for (int i = 0; i < specialCharacterLength; i++) {
+ password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
+ }
+
+ return specialCharacterLength;
+ }
+} | Java | 매번 Random 객체를 생성하지 말고, 그냥 최상단에 private final 로 올려버리세요.
`private final Random random = new SecureRandom();` |
@@ -0,0 +1,32 @@
+package io.study.springbootlayered.api.member.application;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.event.SignupEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberSignupService {
+
+ private final MemberProcessor memberProcessor;
+
+ @Transactional
+ public MemberSignupDto.Info signup(final MemberSignupDto.Command request) {
+ /** 회원 가입 **/
+ MemberSignupDto.Info info = memberProcessor.register(request);
+
+ /** 회원가입 완료 후 이메일 전송 **/
+ String registeredEmail = info.getEmail();
+ Events.raise(SignupEvent.of(registeredEmail));
+
+ return info;
+ }
+} | Java | 인라인 주석은 // 가 좋겠죠? |
@@ -0,0 +1,23 @@
+package io.study.springbootlayered.api.member.domain.entity;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Embeddable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+@Embeddable
+@Getter
+@EqualsAndHashCode
+public class MemberPassword {
+
+ @Column(name = "password", nullable = false)
+ private String value;
+
+ protected MemberPassword() {
+ }
+
+ public MemberPassword(final String value) {
+ this.value = value;
+ }
+
+} | Java | 위에는 Equals와 hashCode를 직접 정의하더니, 이번에는 롬복을 사용하네요? |
@@ -0,0 +1,42 @@
+package io.study.springbootlayered.api.member.domain.event;
+
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.event.TransactionalEventListener;
+
+import io.study.springbootlayered.infra.mail.MailService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class MemberEventListener {
+
+ private final MailService mailService;
+
+ @Async
+ @TransactionalEventListener
+ public void signupEventListener(final SignupEvent event) {
+ log.info("MemberEventListener.signupEventListener !!");
+
+ String[] toEmail = toEmailArray(event.getEmail());
+ mailService.sendMail(toEmail, "회원가입 완료 안내", "회원가입이 완료되었습니다.");
+ }
+
+ private String[] toEmailArray(final String... email) {
+ return email;
+ }
+
+ @Async
+ @TransactionalEventListener
+ public void resetPasswordEventListener(final ResetPasswordEvent event) {
+ log.info("MemberEventListener.resetPasswordEventListener !!");
+
+ String[] toEmail = toEmailArray(event.getEmail());
+ String password = event.getTempPassword();
+
+ mailService.sendMail(toEmail, "임시 비밀번호 발급 안내", "임시 비밀번호 : " + password);
+ }
+
+} | Java | 일반적으로 개발 환경에서는 log level을 debug로, 운영 환경에서는 info/warn 수준으로 설정합니다.
운영 환경에서 해당 요청이 들어올 "때 마다" 해당 로그가 출력되게 되면, 에러 디버깅 과정에서 매우 번거로워질 확률이 높습니다.
개발 과정에서의 디버깅용인지, 운영 환경에서 실제로 필요한 로그인지 잘 생각해보시고 로그 레벨을 지정하는게 좋습니다. |
@@ -0,0 +1,15 @@
+package io.study.springbootlayered.api.member.domain.event;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+@Getter
+@RequiredArgsConstructor
+public class SignupEvent {
+
+ private final String email;
+
+ public static SignupEvent of(String email) {
+ return new SignupEvent(email);
+ }
+} | Java | 생성자랑 역할이 똑같네요. |
@@ -0,0 +1,63 @@
+package io.study.springbootlayered.api.member.domain;
+
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Component;
+
+import io.study.springbootlayered.api.member.domain.dto.MemberDetailDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.repository.MemberQueryRepository;
+import io.study.springbootlayered.api.member.domain.repository.MemberRepository;
+import io.study.springbootlayered.api.member.domain.validation.MemberValidator;
+import io.study.springbootlayered.web.exception.ApiException;
+import io.study.springbootlayered.web.exception.error.MemberErrorCode;
+import lombok.RequiredArgsConstructor;
+
+@Component
+@RequiredArgsConstructor
+public class MemberProcessorImpl implements MemberProcessor {
+
+ private final MemberQueryRepository memberQueryRepository;
+ private final MemberRepository memberRepository;
+ private final PasswordEncoder passwordEncoder;
+ private final MemberValidator memberValidator;
+
+ @Override
+ public MemberSignupDto.Info register(final MemberSignupDto.Command request) {
+ memberValidator.signinValidate(request);
+ Member initBasicMember = Member.createBasicMember(request.getEmail(), request.getNickname(),
+ encodePassword(request.getPassword()));
+ Member savedMember = memberRepository.save(initBasicMember);
+
+ return new MemberSignupDto.Info(savedMember.getEmail());
+ }
+
+ @Override
+ public MemberDetailDto.Info getMember(final Long memberId) {
+ Member findMember = findById(memberId);
+
+ return MemberDetailDto.Info.of(findMember);
+ }
+
+ @Override
+ public void resetPassword(final MemberPasswordResetDto.Command command) {
+ Member findMember = findByEmail(command.getEmail());
+ findMember.changePassword(encodePassword(command.getPassword()));
+ }
+
+ private Member findById(final Long memberId) {
+ return memberQueryRepository.findById(memberId)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private Member findByEmail(final String email) {
+ return memberQueryRepository.findByEmail(email)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private String encodePassword(final String password) {
+ return passwordEncoder.encode(password);
+ }
+
+} | Java | ~~Impl 형식의 클래스의 존재 여부를 이해하긴 어렵네요.
- 다른 구현체의 가능성이 존재하나요?
- 위의 다른 Processor는 막상 타 클래스를 상속하는 구조라 Impl을 안 달고 있네요. |
@@ -0,0 +1,63 @@
+package io.study.springbootlayered.api.member.domain;
+
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Component;
+
+import io.study.springbootlayered.api.member.domain.dto.MemberDetailDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.repository.MemberQueryRepository;
+import io.study.springbootlayered.api.member.domain.repository.MemberRepository;
+import io.study.springbootlayered.api.member.domain.validation.MemberValidator;
+import io.study.springbootlayered.web.exception.ApiException;
+import io.study.springbootlayered.web.exception.error.MemberErrorCode;
+import lombok.RequiredArgsConstructor;
+
+@Component
+@RequiredArgsConstructor
+public class MemberProcessorImpl implements MemberProcessor {
+
+ private final MemberQueryRepository memberQueryRepository;
+ private final MemberRepository memberRepository;
+ private final PasswordEncoder passwordEncoder;
+ private final MemberValidator memberValidator;
+
+ @Override
+ public MemberSignupDto.Info register(final MemberSignupDto.Command request) {
+ memberValidator.signinValidate(request);
+ Member initBasicMember = Member.createBasicMember(request.getEmail(), request.getNickname(),
+ encodePassword(request.getPassword()));
+ Member savedMember = memberRepository.save(initBasicMember);
+
+ return new MemberSignupDto.Info(savedMember.getEmail());
+ }
+
+ @Override
+ public MemberDetailDto.Info getMember(final Long memberId) {
+ Member findMember = findById(memberId);
+
+ return MemberDetailDto.Info.of(findMember);
+ }
+
+ @Override
+ public void resetPassword(final MemberPasswordResetDto.Command command) {
+ Member findMember = findByEmail(command.getEmail());
+ findMember.changePassword(encodePassword(command.getPassword()));
+ }
+
+ private Member findById(final Long memberId) {
+ return memberQueryRepository.findById(memberId)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private Member findByEmail(final String email) {
+ return memberQueryRepository.findByEmail(email)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private String encodePassword(final String password) {
+ return passwordEncoder.encode(password);
+ }
+
+} | Java | 해당 쿼리가 다른 곳에서 재사용되지 않을 것이라는 보장이 있나요?
이런 기본적인 Validation 용 쿼리는 분리해서 다루는게 좋을 것 같아요. |
@@ -0,0 +1,32 @@
+package io.study.springbootlayered.api.member.application;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.event.SignupEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberSignupService {
+
+ private final MemberProcessor memberProcessor;
+
+ @Transactional
+ public MemberSignupDto.Info signup(final MemberSignupDto.Command request) {
+ /** 회원 가입 **/
+ MemberSignupDto.Info info = memberProcessor.register(request);
+
+ /** 회원가입 완료 후 이메일 전송 **/
+ String registeredEmail = info.getEmail();
+ Events.raise(SignupEvent.of(registeredEmail));
+
+ return info;
+ }
+} | Java | 로그 미사용인데 해당 어노테이션 사용하고 있네요. |
@@ -0,0 +1,66 @@
+package christmas.domain;
+
+import static christmas.exception.ErrorMessage.DAY_NOT_IN_RANGE;
+import static christmas.exception.ErrorMessage.ENDS_WITH_DELIMITER;
+
+import christmas.domain.constant.EventConstraint;
+import christmas.exception.OrderException;
+
+public class Day {
+ private final int day;
+
+ private Day(int day) {
+ this.day = day;
+ validate();
+ }
+
+ public static Day of(int day){
+ return new Day(day);
+ }
+
+ public int getDDayDiscountAmount(){
+ if(isBeforeDDay()){
+ return EventConstraint.INITIAL_D_DAY_DISCOUNT_AMOUNT.getValue() + (day-1) * 100;
+ }
+ return 0;
+ }
+
+ public boolean isBeforeDDay(){
+ return day <= EventConstraint.D_DAY.getValue();
+ }
+
+ public boolean isWeekDay(){
+ for (int i = 1; i <= 30; i += 7) {
+ if (day == i || day == i + 1) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean isWeekEnd(){
+ for (int i = 1; i <= 30; i += 7) {
+ if (day == i || day == i + 1) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasStar(){
+ if(day == 25)return true;
+ for(int i = 3; i <= 31; i += 7){
+ if(day == i)return true;
+ }
+ return false;
+ }
+
+ public void validate(){
+ validateEventPeriod();
+ }
+ private void validateEventPeriod(){
+ if (day < EventConstraint.MIN_DAY.getValue() || day > EventConstraint.MAX_DAY.getValue()) {
+ throw OrderException.from(DAY_NOT_IN_RANGE);
+ }
+ }
+} | Java | EventConstraint에서 선언한 상수를 가져다 쓰지 않은 이유가 있나요? |
@@ -0,0 +1,64 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import christmas.domain.constant.EventConstraint;
+import christmas.exception.ErrorMessage;
+import christmas.exception.OrderException;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+public class DayTest {
+
+ @DisplayName("Day 객체를 올바르게 생성하는지 테스트")
+ @Test
+ void createDay() {
+ assertThat(Day.of(5)).isNotNull();
+ }
+
+ @DisplayName("Day 객체를 생성할 때 day가 유효한 범위 내인지 확인")
+ @Test
+ void createDayWithInvalidDay() {
+ assertThatThrownBy(() -> Day.of(40))
+ .isInstanceOf(OrderException.class)
+ .hasMessageContaining(ErrorMessage.DAY_NOT_IN_RANGE.getMessage());
+ }
+
+ @DisplayName("getDDayDiscountAmount 메서드 테스트")
+ @Test
+ void getDDayDiscountAmount() {
+ assertThat(Day.of(24).getDDayDiscountAmount()).isEqualTo(
+ EventConstraint.INITIAL_D_DAY_DISCOUNT_AMOUNT.getValue() + (24-1) * 100);
+ assertThat(Day.of(26).getDDayDiscountAmount()).isEqualTo(0);
+ }
+
+ @DisplayName("isBeforeDDay 메서드 테스트")
+ @Test
+ void isBeforeDDay() {
+ assertThat(Day.of(24).isBeforeDDay()).isTrue();
+ assertThat(Day.of(26).isBeforeDDay()).isFalse();
+ }
+
+ @DisplayName("isWeekDay 메서드 테스트")
+ @Test
+ void isWeekDay() {
+ assertThat(Day.of(5).isWeekDay()).isTrue();
+ assertThat(Day.of(8).isWeekDay()).isFalse();
+ }
+
+ @DisplayName("isWeekEnd 메서드 테스트")
+ @Test
+ void isWeekEnd() {
+ assertThat(Day.of(5).isWeekEnd()).isFalse();
+ assertThat(Day.of(8).isWeekEnd()).isTrue();
+ }
+
+ @DisplayName("hasStar 메서드 테스트")
+ @Test
+ void hasStar() {
+ assertThat(Day.of(25).hasStar()).isTrue();
+ assertThat(Day.of(26).hasStar()).isFalse();
+ }
+}
+ | Java | @ParamiterizedTest의 어노테이션을 활용해서 중복을 줄일 수 있을거 같습니다. |
@@ -0,0 +1,5 @@
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+
+export const PRODUCTS_ENDPOINT = `${API_URL}/products`;
+export const CART_ITEMS_ENDPOINT = `${API_URL}/cart-items`;
+export const CART_ITEMS_COUNTS_ENDPOINT = `${CART_ITEMS_ENDPOINT}/counts`; | TypeScript | 이런 endpoint들을 하나의 객체로 관리해도 좋을 것 같아요! |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`;
+
+if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set"
+ );
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+
+ return response;
+};
+
+const requestBuilder = (options: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+ const { method, body } = options;
+
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | fetch에 필요한 중복된 로직을 분리한 부분. 인상적입니다. |
@@ -0,0 +1,25 @@
+import { useEffect } from "react";
+import { useErrorContext } from "../../hooks/useErrorContext";
+import { ErrorToastStyle } from "./ErrorToast.style";
+
+const ErrorToast = () => {
+ const { error, hideError } = useErrorContext();
+
+ useEffect(() => {
+ setTimeout(() => {
+ hideError();
+ }, 3000);
+ }, [error, hideError]);
+
+ if (!error) {
+ return null;
+ }
+
+ return (
+ <ErrorToastStyle>
+ 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.
+ </ErrorToastStyle>
+ );
+};
+
+export default ErrorToast; | Unknown | toast를 띄어줄 시간을 따로 상수로 관리하는 것도 좋을 것 같아요 |
@@ -0,0 +1,51 @@
+import useProducts from "../../hooks/useProducts";
+import ProductListHeader from "../ProductListHeader/ProductListHeader";
+import ProductItem from "./ProductItem/ProductItem";
+import * as PL from "./ProductList.style";
+import useInfiniteScroll from "../../hooks/useInfiniteScroll";
+import usePagination from "../../hooks/usePagination";
+
+const ProductList = () => {
+ const { page, nextPage, resetPage } = usePagination();
+
+ const { products, loading, hasMore, handleCategory, handleSort } =
+ useProducts({
+ page,
+ resetPage,
+ });
+
+ const { lastElementRef: lastProductElementRef } = useInfiniteScroll({
+ hasMore,
+ loading,
+ nextPage,
+ });
+
+ return (
+ <>
+ <ProductListHeader
+ handleCategory={handleCategory}
+ handleSort={handleSort}
+ />
+ {!loading && products.length === 0 ? (
+ <PL.Empty>상품이 존재하지 않습니다! 🥲</PL.Empty>
+ ) : (
+ <PL.ProductListStyle>
+ {products.map((item, index) => {
+ return (
+ <ProductItem
+ product={item}
+ key={item.id}
+ ref={
+ index === products.length - 1 ? lastProductElementRef : null
+ }
+ />
+ );
+ })}
+ </PL.ProductListStyle>
+ )}
+ {loading && <PL.Loading>로딩중! 💪</PL.Loading>}
+ </>
+ );
+};
+
+export default ProductList; | Unknown | 현재 새로운 fetch를 통해 새로운 데이터를 가지고 오면 스크롤 위치가 강제로 올라가는 버그가 있습니다. 제가 생각하기에는 ProductListStyle가 조건부로 렌더링되어 컴포넌트가 매번 새롭게 만들어집니다. 그래서 리액트가 동일한 컴포넌트로 인지하지 못해서 발생한 문제 같습니다. 다음과 같은 코드로 문제를 해결할 수 있을 것 같습니다.
```tsx
return (
<>
<ProductListHeader
handleCategory={handleCategory}
handleSort={handleSort}
/>
{products !== null && (
<PL.ProductListStyle>
{products.map((item, index) => {
return (
<ProductItem
product={item}
key={`${item.id}${index}`}
/>
);
})}
</PL.ProductListStyle>
)}
{!loading && products.length === 0 && (
<PL.Empty>상품이 존재하지 않습니다! 🥲</PL.Empty>
)}
{loading && <PL.Loading>로딩중! 💪</PL.Loading>}
{!loading && (
<div
ref={lastProductElementRef}
style={{ height: '30px', fontSize: '5rem' }}
></div>
)}
</>
);
};
```
이런 방식으로 렌더링하게되면 ProductListStyle위치는 products가 null이 아닌 이상에야 계속 같은 위치에 존재하므로 스크롤이 위로 올라가지 않습니다. |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`;
+
+if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set"
+ );
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+
+ return response;
+};
+
+const requestBuilder = (options: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+ const { method, body } = options;
+
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | fetch의 공통된 로직을 두번이나 감싸서 깔끔하게 정리해 준 것이 마음에 드네요~!
제 미션에도 적용시켜봐야겠어요 ㅋㅋㅋ 🚀 🚀🚀🚀 |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams): string => {
+ return Object.entries(params)
+ .map(([key, value]) => {
+ if (value === undefined) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
+ value.join(",")
+ )}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}) => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async () => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | 아마 key로 접근해서 값을 가져오기 위해서 index signature를 사용하려고 하셨던 걸까요?!
하지만 이렇게 되면, 예상치 못하게 `page = "page1"` 과 같은 prop이나
의도하지 않은 key값이 들어올 경우, queryParams interface에서 걸러지지 않을 것 같아요.
여유있으실 때 한번 생각해 보시면 좋을 것 같아요 :) |
@@ -0,0 +1,34 @@
+import styled from "styled-components";
+
+export const ButtonStyle = styled.button`
+ cursor: pointer;
+ border: none;
+ outline: none;
+`;
+
+export const CartControlButtonStyle = styled(ButtonStyle)`
+ display: flex;
+ position: absolute;
+ right: 8px;
+ align-items: center;
+ border-radius: 4px;
+ padding: 4px 8px;
+ gap: 1px;
+ bottom: 15px;
+ font-weight: 600;
+ font-size: 12px;
+
+ img {
+ width: 14px;
+ height: 14px;
+ }
+`;
+
+export const AddCartStyle = styled(CartControlButtonStyle)`
+ background-color: #000000;
+ color: #ffffff;
+`;
+export const RemoveCartStyle = styled(CartControlButtonStyle)`
+ background-color: #eaeaea;
+ color: #000000;
+`; | TypeScript | 저는 Button의 Prop을 받아서 색상을 바꿔주는 식으로 작성했어요!
```suggestion
export const ButtonStyle = styled.button<ButtonProps>`
cursor: pointer;
border: none;
outline: none;
${({ color }) => {
if (color === "primary") {
return `
background-color: black;
color: white;
`;
}
if (color === "secondary") {
return `
background-color: lightGrey;
color: black;
`;
}
return `
background-color: white;
color: black;
border: 1px solid lightGray;
`;
}}
`;
```
style의 코드가 보기 좋지 않지만, 사용하는 곳에서 별도의 태그를 선언하지 않아도 쓸 수 있는 장점이 있더라구요~
아마 수야의 코드에서는 이렇게 되겠네요
```tsx
const CartControlButton = ({ isInCart, onClick }: CartControlButtonProps) => {
return (
<CartControlButtonStyle onClick={onClick} $color={isInCart?'secondary':'primary'}>
<img src={isInCart?RemoveCart:AddCart} alt={isInCart?'장바구니 빼기':'장바구니 더하기'} />
<span>{isInCart?'빼기':'더하기'}</span>
</CartControlButtonStyle>
);
};
```
막상 다 적고 보니까, 수야의 코드가 더 깔끔해 보이네요 ㅋㅋㅋㅋㅋ
참고 하실 수 있을 것 같아서 적어봤고, 저도 저와 다른 코드 방식을 보니 재밌었습니다 :) |
@@ -0,0 +1,39 @@
+import styled from "styled-components";
+
+export const HeaderStyle = styled.header`
+ display: flex;
+ background-color: #000000;
+ width: inherit;
+ height: 64px;
+ position: fixed;
+ z-index: 1;
+ padding: 16px 24px 16px;
+ box-sizing: border-box;
+`;
+
+export const LogoImg = styled.img`
+ width: 56px;
+`;
+
+export const CartImg = styled.img`
+ width: 32px;
+ position: absolute;
+ right: 24px;
+ bottom: 16px;
+`;
+
+export const CartCount = styled.div`
+ background-color: #ffffff;
+ border-radius: 999px;
+ width: 19px;
+ height: 19px;
+ font-size: 10px;
+ font-weight: 700;
+ position: absolute;
+ right: 24px;
+ bottom: 16px;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`; | TypeScript | 프로젝트의 컴포넌트 규모가 복잡해지면, zindex 관리가 힘들더라구요
헤더를 1로 해놨는데, 헤더보다 낮은 어떠한 component가 생길수도 있고...!
그래서 저도 추천받은 방법이 zIndex들을 상수로 관리해서 한곳에서 편하게 볼 수 있도록 하는거였어요
저도 자주 사용하진 않지만, 꿀팁 공유해봅니다 ㅎㅎ |
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useState,
+ ReactNode,
+ useEffect,
+ useCallback,
+} from "react";
+import { getCartItems } from "../api";
+import { useErrorContext } from "../hooks/useErrorContext";
+
+export interface CartItemsContextType {
+ cartItems: CartItem[];
+ refreshCartItems: () => void;
+}
+
+export const CartItemsContext = createContext<CartItemsContextType | undefined>(
+ undefined
+);
+
+interface CartItemsProviderProps {
+ children: ReactNode;
+}
+
+export const CartItemsProvider: React.FC<CartItemsProviderProps> = ({
+ children,
+}) => {
+ const { showError } = useErrorContext();
+
+ const [toggle, setToggle] = useState(false);
+
+ const [cartItems, setCartItems] = useState<CartItem[]>([]);
+
+ const refreshCartItems = useCallback(() => {
+ setToggle((prev) => !prev);
+ }, []);
+
+ useEffect(() => {
+ const fetchCartItems = async () => {
+ try {
+ const cartItems = await getCartItems();
+ setCartItems(cartItems);
+ } catch (error) {
+ if (error instanceof Error) {
+ showError(error.message);
+ }
+ }
+ };
+
+ fetchCartItems();
+ }, [toggle, showError]);
+
+ return (
+ <CartItemsContext.Provider value={{ cartItems, refreshCartItems }}>
+ {children}
+ </CartItemsContext.Provider>
+ );
+}; | Unknown | 저는 Quantity만을 context로 관리했는데, 전체 List를 context 로 관리하셨군요!!
Provider를 custom 해주는 것도 매우 좋은 것 같습니다 :)
좋은 정보 배우고 갑니다!! |
@@ -0,0 +1,34 @@
+import styled from "styled-components";
+
+export const ButtonStyle = styled.button`
+ cursor: pointer;
+ border: none;
+ outline: none;
+`;
+
+export const CartControlButtonStyle = styled(ButtonStyle)`
+ display: flex;
+ position: absolute;
+ right: 8px;
+ align-items: center;
+ border-radius: 4px;
+ padding: 4px 8px;
+ gap: 1px;
+ bottom: 15px;
+ font-weight: 600;
+ font-size: 12px;
+
+ img {
+ width: 14px;
+ height: 14px;
+ }
+`;
+
+export const AddCartStyle = styled(CartControlButtonStyle)`
+ background-color: #000000;
+ color: #ffffff;
+`;
+export const RemoveCartStyle = styled(CartControlButtonStyle)`
+ background-color: #eaeaea;
+ color: #000000;
+`; | TypeScript | Button에 `hover` 속성도 있으면 어떨까 싶네요! |
@@ -0,0 +1,37 @@
+import { forwardRef } from "react";
+import * as PI from "./ProductItem.style";
+import CartControlButton from "../../Button/CartControlButton";
+import useProductInCart from "../../../hooks/useProductInCart";
+
+interface ProductProps {
+ product: Product;
+}
+
+const ProductItem = forwardRef<HTMLDivElement, ProductProps>(
+ ({ product }, ref) => {
+ const { isProductInCart, handleProductInCart } = useProductInCart(
+ product.id
+ );
+
+ return (
+ <PI.ProductItemStyle ref={ref}>
+ <PI.ProductImg
+ src={`${product.imageUrl}`}
+ alt={`${product.name} 상품 이미지`}
+ />
+ <PI.ProductGroup>
+ <PI.ProductContent>
+ <PI.ProductName>{product.name}</PI.ProductName>
+ <span>{product.price.toLocaleString("ko-kr")}원</span>
+ </PI.ProductContent>
+ <CartControlButton
+ onClick={handleProductInCart}
+ isInCart={isProductInCart}
+ />
+ </PI.ProductGroup>
+ </PI.ProductItemStyle>
+ );
+ }
+);
+
+export default ProductItem; | Unknown | 혹시 try-catch 에서 catch되는 error가 `Error` 타입이 아닌 경우도 있나요?!
단순히 궁금해서 여쭤봅니다...!
catch되는 것은 Error만 catch되는줄 알아서, 이 로직이 필요한가 하는 생각이 들었어요 ㅋㅋ |
@@ -0,0 +1,51 @@
+import useProducts from "../../hooks/useProducts";
+import ProductListHeader from "../ProductListHeader/ProductListHeader";
+import ProductItem from "./ProductItem/ProductItem";
+import * as PL from "./ProductList.style";
+import useInfiniteScroll from "../../hooks/useInfiniteScroll";
+import usePagination from "../../hooks/usePagination";
+
+const ProductList = () => {
+ const { page, nextPage, resetPage } = usePagination();
+
+ const { products, loading, hasMore, handleCategory, handleSort } =
+ useProducts({
+ page,
+ resetPage,
+ });
+
+ const { lastElementRef: lastProductElementRef } = useInfiniteScroll({
+ hasMore,
+ loading,
+ nextPage,
+ });
+
+ return (
+ <>
+ <ProductListHeader
+ handleCategory={handleCategory}
+ handleSort={handleSort}
+ />
+ {!loading && products.length === 0 ? (
+ <PL.Empty>상품이 존재하지 않습니다! 🥲</PL.Empty>
+ ) : (
+ <PL.ProductListStyle>
+ {products.map((item, index) => {
+ return (
+ <ProductItem
+ product={item}
+ key={item.id}
+ ref={
+ index === products.length - 1 ? lastProductElementRef : null
+ }
+ />
+ );
+ })}
+ </PL.ProductListStyle>
+ )}
+ {loading && <PL.Loading>로딩중! 💪</PL.Loading>}
+ </>
+ );
+};
+
+export default ProductList; | Unknown | 오... 해결법 제시까지 대단하네요 🚀 🚀🚀🚀🚀🚀🚀 |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`;
+
+if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set"
+ );
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+
+ return response;
+};
+
+const requestBuilder = (options: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+ const { method, body } = options;
+
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | `requestBuilder` 라는 이름으로 요청을 만드는 책임을 가진 함수를 별도로 분리해주신 부분이 인상깊네요!👍👍 |
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useState,
+ ReactNode,
+ useEffect,
+ useCallback,
+} from "react";
+import { getCartItems } from "../api";
+import { useErrorContext } from "../hooks/useErrorContext";
+
+export interface CartItemsContextType {
+ cartItems: CartItem[];
+ refreshCartItems: () => void;
+}
+
+export const CartItemsContext = createContext<CartItemsContextType | undefined>(
+ undefined
+);
+
+interface CartItemsProviderProps {
+ children: ReactNode;
+}
+
+export const CartItemsProvider: React.FC<CartItemsProviderProps> = ({
+ children,
+}) => {
+ const { showError } = useErrorContext();
+
+ const [toggle, setToggle] = useState(false);
+
+ const [cartItems, setCartItems] = useState<CartItem[]>([]);
+
+ const refreshCartItems = useCallback(() => {
+ setToggle((prev) => !prev);
+ }, []);
+
+ useEffect(() => {
+ const fetchCartItems = async () => {
+ try {
+ const cartItems = await getCartItems();
+ setCartItems(cartItems);
+ } catch (error) {
+ if (error instanceof Error) {
+ showError(error.message);
+ }
+ }
+ };
+
+ fetchCartItems();
+ }, [toggle, showError]);
+
+ return (
+ <CartItemsContext.Provider value={{ cartItems, refreshCartItems }}>
+ {children}
+ </CartItemsContext.Provider>
+ );
+}; | Unknown | `useCallback`과`toggle`이라는 상태를 통해 `fetchCartItems`을 재실행시킨다는 발상이 몹시 새롭게 느껴지네요! 한 번도 생각해보지 못했던 방식인데... 상태는 최소화되어야 한다고 생각하는 편이지만, 특정 트리거를 위해 상태를 활용하는 것이 좋은지 저도 한 번 고민해볼 수 있었던 것 같아요!
한편으로는 상태를 만들지않고, `fetchCartItems`로직을 `useEffect` 밖으로 뺀 뒤 refreshCartItems 을 잘 작성해주면 상태가 필요하지 않을 것 같다는 생각이 들기도 합니다! (이 부분은 개발자의 취향이나 선호에 가까울 수 있을 것 같아요..!) |
@@ -0,0 +1,15 @@
+import { useContext } from "react";
+import {
+ CartItemsContext,
+ CartItemsContextType,
+} from "../context/CartItemsContext";
+
+export const useCartItemsContext = (): CartItemsContextType => {
+ const context = useContext(CartItemsContext);
+ if (!context) {
+ throw new Error(
+ "useCartItemsContext must be used within an CartItemsProvider"
+ );
+ }
+ return context;
+}; | TypeScript | 현재 `useErrorContext`와 `useCartItemsContext`는 context가 `undefined`인 경우 에러를 던져 타입을 좁히기 위한 커스텀 훅인 것 같습니다. 제가 느끼기엔 두 훅 모두 같은 역할을 해주고 있는 것 같아서 context를 인자로 받는다면 하나의 훅으로 합쳐서 재사용해주어도 좋을 것 같습니다!ㅎㅎ |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams): string => {
+ return Object.entries(params)
+ .map(([key, value]) => {
+ if (value === undefined) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
+ value.join(",")
+ )}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}) => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async () => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | 몹시 흥미로운 함수네요!👍👍 별거 아니지만 이러한 부분은 api 내부 util로 파일을 분리해주셔도 좋을 것 같아요! |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams): string => {
+ return Object.entries(params)
+ .map(([key, value]) => {
+ if (value === undefined) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
+ value.join(",")
+ )}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}) => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async () => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | 추상화된 `fetchWithAuth` 내부에서 이미 `response.ok`가 아닌 경우 에러를 던지도록 처리해두었는데 여기를 포함하여 모든 fetch 함수에서 여전히 에러를 던지시는 이유가 있으실까요..?? |
@@ -0,0 +1,5 @@
+package store.constants;
+
+public class MembershipConstants {
+ public static final double DISCOUNT_RATE = 0.30;
+} | Java | 이 부분은 클래스를 생성할 수 없게끔 생성자를 private으로 만들면 좋을 것 같아요. |
@@ -0,0 +1,18 @@
+package store.constants;
+
+public class ReceiptConstants {
+ public static final String ORDER_DETAIL_FORMAT = "%-10s %6s %12s";
+ public static final String PROMOTION_DETAIL_FORMAT = "%-10s %6s";
+ public static final String TOTAL_DETAIL_FORMAT = "%-10s %18s";
+ public static final String LINE_SEPARATOR = "====================================";
+ public static final String PROMOTION_HEADER = "=============증\t\t정===============";
+ public static final String RECEIPT_HEADER = "==============W 편의점================";
+ public static final String PRODUCT_HEADER = "%-10s %6s %12s";
+ public static final String PRODUCT_NAME = "상품명";
+ public static final String QUANTITY = "수량";
+ public static final String PRICE = "금액";
+ public static final String TOTAL_PURCHASE_AMOUNT = "총구매액";
+ public static final String EVENT_DISCOUNT = "행사할인";
+ public static final String MEMBERSHIP_DISCOUNT = "멤버십할인";
+ public static final String FINAL_AMOUNT = "내실돈";
+} | Java | Enum을 사용하지 않으신 이유가 있을까요?
String.format을 사용하실 때 Enum 내에 변환해서 반환하면 OuptView에서도 더 깔끔하게 로직을 처리할 수 있을 것 같아요! |
@@ -0,0 +1,38 @@
+package store.controller;
+
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.dto.StoreDto;
+import store.dto.StoreInitializationDto;
+import store.parser.ProductParser;
+import store.parser.PromotionParser;
+import store.service.FileReaderService;
+
+public class FileReaderController {
+ private final FileReaderService fileReaderService;
+ private final PromotionParser promotionParser;
+ private final ProductParser productParser;
+
+ public FileReaderController() {
+ this.fileReaderService = new FileReaderService();
+ this.productParser = new ProductParser();
+ this.promotionParser = new PromotionParser();
+ }
+
+ public StoreDto runFileData() {
+ return initialize();
+ }
+
+ public StoreDto initialize() {
+ StoreInitializationDto storeInitializationDto = fileReaderService.initializeStoreData();
+ return parseStoreData(storeInitializationDto);
+ }
+
+ public StoreDto parseStoreData(StoreInitializationDto storeInitializationDto) {
+ List<Promotion> promotions = promotionParser.parse(storeInitializationDto.promotionDtos());
+ Map<String, Product> products = productParser.parse(storeInitializationDto.productDtos(), promotions);
+ return new StoreDto(products, promotions);
+ }
+} | Java | 이런 부분은 private를 통해 캡슐화하는 것이 어떨까요? |
@@ -0,0 +1,23 @@
+package store.controller;
+
+import store.domain.Store;
+import store.dto.StoreDto;
+import store.service.StoreService;
+
+public class StoreController {
+
+ private final StoreService storeService;
+
+ public StoreController() {
+ this.storeService = new StoreService();
+ }
+
+ public void run(StoreDto storeDto) {
+ Store store = createStore(storeDto);
+ storeService.processOrder(store);
+ }
+
+ private Store createStore(StoreDto storeDto) {
+ return new Store(storeDto);
+ }
+} | Java | 외부에서 의존성 주입하는 방식을 사용하지 않으신 이유가 있을까요? |
@@ -0,0 +1,35 @@
+package store.domain;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+public class Cart {
+ private final Map<String, CartItem> cartItems;
+
+ public Cart() {
+ this.cartItems = new LinkedHashMap<>();
+ }
+
+ public void addItem(List<CartItem> cartItems) {
+ for (CartItem cartItem : cartItems) {
+ this.cartItems.put(cartItem.getProduct().getName(), cartItem);
+ }
+ }
+
+ public List<CartItem> getAllItemsInCart() {
+ return cartItems.values().stream().toList();
+ }
+
+ public int getTotalFreeItemQuantity() {
+ return cartItems.values().stream().mapToInt(CartItem::getFreeQuantity).sum();
+ }
+
+ public int getTotalFreeItemPrice() {
+ return cartItems.values().stream().mapToInt(CartItem::getTotalFreePrice).sum();
+ }
+
+ public int getTotalItemPrice() {
+ return cartItems.values().stream().mapToInt(CartItem::totalPrice).sum();
+ }
+} | Java | Stream API는 가독성을 위해 엔터를 사용하면 더 좋을 것 같아요! |
@@ -0,0 +1,56 @@
+package store.domain;
+
+import static store.message.ErrorMessage.INSUFFICIENT_STOCK_ERROR;
+
+import store.validation.CartItemValidator;
+
+public class CartItem {
+ private final Product product;
+ private int quantity;
+ private int freeQuantity;
+
+ public CartItem(Product product, int quantity) {
+ CartItemValidator.validateCartItem(quantity);
+ this.product = product;
+ this.quantity = quantity;
+ }
+
+ public void increaseQuantity(int updateQuantity) {
+ this.freeQuantity += updateQuantity;
+ }
+
+ public void decreaseQuantity(int updateQuantity) {
+ this.quantity -= updateQuantity;
+ if (quantity <= 0) {
+ throw new IllegalArgumentException(INSUFFICIENT_STOCK_ERROR.getMessage());
+ }
+ }
+
+ public String getProductName() {
+ return product.getName();
+ }
+
+ public int totalPrice() {
+ return product.getPrice() * getTotalQuantity();
+ }
+
+ public int getTotalFreePrice() {
+ return product.getPrice() * freeQuantity;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getTotalQuantity() {
+ return quantity + freeQuantity;
+ }
+
+ public Product getProduct() {
+ return product;
+ }
+
+ public int getFreeQuantity() {
+ return freeQuantity;
+ }
+} | Java | 디미터 법칙을 준수하기 위해 작성하신 메서드로 보입니다. 저도 이런 방식으로 진행했는데요, 3주차 피드백과 자바 스타일 가이드에서 Getter를 사용하기보다 객체 내에서 처리하는 방식이 더 좋다는 내용이 있었습니다.
이 부분은 어떻게 생각하시나요? |
@@ -0,0 +1,136 @@
+package store.domain;
+
+import static store.constants.ProductConstants.OUT_OF_STOCK;
+import static store.constants.ProductConstants.PRODUCT_DESCRIPTION_PREFIX;
+import static store.constants.ProductConstants.UNIT_QUANTITY;
+import static store.constants.ProductConstants.UNIT_WON;
+import static store.message.ErrorMessage.NOT_FOUND_PROMOTION;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.validation.ProductValidator;
+
+public class Product {
+ private String name;
+ private int price;
+ private int quantity;
+ private Optional<Promotion> promotion;
+
+ private Product() {
+ }
+
+ public Product(ProductDto productDto, Optional<Promotion> promotion) {
+ ProductValidator.validate(productDto);
+ this.name = productDto.name();
+ this.price = Integer.parseInt(productDto.price());
+ this.quantity = Integer.parseInt(productDto.quantity());
+ this.promotion = promotion;
+ }
+
+ /**
+ * 프로모션을 적용 여부 검증
+ */
+ public boolean isEligibleForStandardPromotion(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return orderedQuantity <= quantity
+ && getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 보너스 상품이 적용 여부 검증
+ */
+ public boolean isEligibleForBonusProduct(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return getRemainingItemsForPromotion(orderedQuantity, promotionInfo) >= promotionInfo.getBuy()
+ && orderedQuantity + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 프로모션 조건을 만족하는 남은 수량을 계산
+ */
+ public int getRemainingItemsForPromotion(int orderedQuantity, Promotion promotionInfo) {
+ return orderedQuantity % promotionInfo.getTotalRequiredQuantity();
+ }
+
+ /**
+ * 보너스 상품의 수량을 계산
+ */
+ public int calculateBonusQuantity(int orderedQuantity, Promotion promotion) {
+ return (orderedQuantity / promotion.getTotalRequiredQuantity()) * promotion.getGet();
+ }
+
+ /**
+ * 프로모션이 적용된 후, 실제 주문 가능한 수량을 계산
+ */
+ public int calculateQuantityAfterPromotion(int orderedQuantity) {
+ Promotion promotionInfo = getPromotionOrElseThrow();
+ int requiredQuantity = promotionInfo.getTotalRequiredQuantity();
+ return (orderedQuantity - quantity) + (quantity % requiredQuantity);
+ }
+
+ /**
+ * 프로모션이 존재하지 않으면 예외 발생
+ */
+ public Promotion getPromotionOrElseThrow() {
+ return promotion.orElseThrow(() -> new IllegalArgumentException(NOT_FOUND_PROMOTION.getMessage()));
+ }
+
+ /**
+ * 값을 가지고 있는 주체이기 때문에 상품 리스트를 포맷을 합니다.
+ */
+ @Override
+ public String toString() {
+ return PRODUCT_DESCRIPTION_PREFIX
+ + name + " "
+ + getFormatKoreanLocale(price) + UNIT_WON
+ + getFormattedQuantity()
+ + getFormattedPromotion();
+ }
+
+ public String getFormattedQuantity() {
+ if (quantity < 1) {
+ return OUT_OF_STOCK;
+ }
+ return getFormatKoreanLocale(quantity) + UNIT_QUANTITY;
+ }
+
+ public String getFormatKoreanLocale(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+
+ public String getFormattedPromotion() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Optional<Promotion> getPromotion() {
+ return promotion;
+ }
+
+ public boolean isPromotionalProduct() {
+ return promotion.isPresent();
+ }
+
+ public void decreaseQuantity(int orderQuantity) {
+ this.quantity -= orderQuantity;
+ }
+} | Java | 1주차 피드백에서, 주석을 사용하기 보다는 메서드명을 통해 의도를 파악하게 하는 것이 더 좋다는 내용이 있었습니다. 이 부분에 따로 주석을 표시한 이유가 있을까요? |
@@ -0,0 +1,55 @@
+package store.domain;
+
+import java.time.LocalDateTime;
+import store.dto.PromotionDto;
+import store.util.DateUtil;
+import store.validation.PromotionValidator;
+
+public class Promotion {
+
+ private String name; //프로모션명
+ private int buy; // 구매조건
+ private int get; //증정수량
+ private LocalDateTime startDate;
+ private LocalDateTime endDate;
+
+ private Promotion() {
+ }
+
+ public Promotion(PromotionDto promotionDto) {
+ PromotionValidator.validate(promotionDto);
+ this.name = promotionDto.name();
+ this.buy = Integer.parseInt(promotionDto.buy());
+ this.get = Integer.parseInt(promotionDto.get());
+ this.startDate = DateUtil.dateParse(promotionDto.startDate());
+ this.endDate = DateUtil.dateParse(promotionDto.endDate());
+ }
+
+ public boolean isPromotionName(String productPromotionName) {
+ return this.name.equals(productPromotionName);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getTotalRequiredQuantity() {
+ return buy + get;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public LocalDateTime getStartDate() {
+ return startDate;
+ }
+
+ public LocalDateTime getEndDate() {
+ return endDate;
+ }
+} | Java | 요것도 주석보다는 변수명을 잘 짓는게 좋을 것 같아요! |
@@ -0,0 +1,55 @@
+package store.domain;
+
+import java.time.LocalDateTime;
+import store.dto.PromotionDto;
+import store.util.DateUtil;
+import store.validation.PromotionValidator;
+
+public class Promotion {
+
+ private String name; //프로모션명
+ private int buy; // 구매조건
+ private int get; //증정수량
+ private LocalDateTime startDate;
+ private LocalDateTime endDate;
+
+ private Promotion() {
+ }
+
+ public Promotion(PromotionDto promotionDto) {
+ PromotionValidator.validate(promotionDto);
+ this.name = promotionDto.name();
+ this.buy = Integer.parseInt(promotionDto.buy());
+ this.get = Integer.parseInt(promotionDto.get());
+ this.startDate = DateUtil.dateParse(promotionDto.startDate());
+ this.endDate = DateUtil.dateParse(promotionDto.endDate());
+ }
+
+ public boolean isPromotionName(String productPromotionName) {
+ return this.name.equals(productPromotionName);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getTotalRequiredQuantity() {
+ return buy + get;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public LocalDateTime getStartDate() {
+ return startDate;
+ }
+
+ public LocalDateTime getEndDate() {
+ return endDate;
+ }
+} | Java | getGet() 메서드명을 보시면 가독성이 매우 떨어지는 것 같아요! |
@@ -0,0 +1,152 @@
+package store.domain;
+
+import static store.constants.ReceiptConstants.EVENT_DISCOUNT;
+import static store.constants.ReceiptConstants.FINAL_AMOUNT;
+import static store.constants.ReceiptConstants.LINE_SEPARATOR;
+import static store.constants.ReceiptConstants.MEMBERSHIP_DISCOUNT;
+import static store.constants.ReceiptConstants.ORDER_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PRICE;
+import static store.constants.ReceiptConstants.PRODUCT_HEADER;
+import static store.constants.ReceiptConstants.PRODUCT_NAME;
+import static store.constants.ReceiptConstants.PROMOTION_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PROMOTION_HEADER;
+import static store.constants.ReceiptConstants.QUANTITY;
+import static store.constants.ReceiptConstants.RECEIPT_HEADER;
+import static store.constants.ReceiptConstants.TOTAL_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.TOTAL_PURCHASE_AMOUNT;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+
+public class Receipt {
+ private final Store store;
+ private final Cart cart;
+ private final Membership membership;
+
+ public Receipt(Store store, Cart cart, Membership membership) {
+ this.store = store;
+ this.cart = cart;
+ this.membership = membership;
+ }
+
+ @Override
+ public String toString() {
+ return buildReceiptContent();
+ }
+
+ public boolean hasFreeItems() {
+ return cart.getTotalFreeItemQuantity() > 0;
+ }
+
+ /**
+ * 장바구니 및 멤버십 정보를 바탕으로 영수증 내용을 빌드하는 메서드입니다.
+ * <p>
+ * 추가로 증정된 상품이 없다면 상품내역 정보는 출력하지 않습니다.
+ */
+ public String buildReceiptContent() {
+ StringBuilder result = new StringBuilder();
+ result.append(getReceiptHeader());
+ result.append(toStringOrderDetail());
+ if (hasFreeItems()) {
+ result.append(toStringRemainingItemsForPromotion());
+ }
+ result.append(toStringTotal());
+ return result.toString();
+ }
+
+ /**
+ * 영수증 헤더를 반환하는 메서드입니다.
+ */
+ public String getReceiptHeader() {
+ StringBuilder header = new StringBuilder();
+ header.append(RECEIPT_HEADER).append("\n");
+ header.append(String.format(PRODUCT_HEADER, PRODUCT_NAME, QUANTITY, PRICE)).append("\n");
+ return header.toString();
+ }
+
+ /**
+ * 주문 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringOrderDetail() {
+ StringBuilder orderDetail = new StringBuilder();
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ orderDetail.append(String.format(ORDER_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getQuantity()), numberFormat(cartItem.totalPrice())))
+ .append("\n");
+ }
+ return orderDetail.toString();
+ }
+
+ /**
+ * 증정 상품 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringRemainingItemsForPromotion() {
+ StringBuilder remainingitems = new StringBuilder();
+ remainingitems.append(PROMOTION_HEADER).append("\n");
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ if (cartItem.getFreeQuantity() > 0) {
+ remainingitems.append(String.format(PROMOTION_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getFreeQuantity())))
+ .append("\n");
+ }
+ }
+ return remainingitems.toString();
+ }
+
+ /**
+ * 총 금액 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringTotal() {
+ StringBuilder total = new StringBuilder();
+ total.append(LINE_SEPARATOR).append("\n");
+
+ total.append(formatTotalItemPrice())
+ .append("\n");
+ total.append(formatEventDiscount())
+ .append("\n");
+ total.append(formatMembershipDiscount())
+ .append("\n");
+ total.append(formatFinalAmount())
+ .append("\n");
+
+ return total.toString();
+ }
+
+ /**
+ * 총 구매 금액을 포맷팅하여 반환
+ */
+ public String formatTotalItemPrice() {
+ return String.format(TOTAL_DETAIL_FORMAT, TOTAL_PURCHASE_AMOUNT, numberFormat(cart.getTotalItemPrice()));
+ }
+
+ /**
+ * 이벤트 할인 금액을 포맷팅하여 반환
+ */
+ public String formatEventDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, EVENT_DISCOUNT, numberFormat(cart.getTotalFreeItemPrice()));
+ }
+
+ /**
+ * 멤버십 할인 금액을 포맷팅하여 반환
+ */
+ public String formatMembershipDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, MEMBERSHIP_DISCOUNT, numberFormat(membership.getMembershipPrice()));
+ }
+
+ /**
+ * 최종 금액을 포맷팅하여 반환
+ */
+ public String formatFinalAmount() {
+ int finalAmount = cart.getTotalItemPrice() - cart.getTotalFreeItemPrice() - membership.getMembershipPrice();
+ return String.format(TOTAL_DETAIL_FORMAT, FINAL_AMOUNT, numberFormat(finalAmount));
+ }
+
+ /**
+ * 숫자를 한국의 숫자 포맷에 맞게 형식화하는 메서드입니다.
+ */
+ public String numberFormat(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+} | Java | 여기는 왜 빈라인을 추가하지 않으셨나요? 이전 코드에는 일관성 있게 추가한 것 같아서요! |
@@ -0,0 +1,152 @@
+package store.domain;
+
+import static store.constants.ReceiptConstants.EVENT_DISCOUNT;
+import static store.constants.ReceiptConstants.FINAL_AMOUNT;
+import static store.constants.ReceiptConstants.LINE_SEPARATOR;
+import static store.constants.ReceiptConstants.MEMBERSHIP_DISCOUNT;
+import static store.constants.ReceiptConstants.ORDER_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PRICE;
+import static store.constants.ReceiptConstants.PRODUCT_HEADER;
+import static store.constants.ReceiptConstants.PRODUCT_NAME;
+import static store.constants.ReceiptConstants.PROMOTION_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PROMOTION_HEADER;
+import static store.constants.ReceiptConstants.QUANTITY;
+import static store.constants.ReceiptConstants.RECEIPT_HEADER;
+import static store.constants.ReceiptConstants.TOTAL_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.TOTAL_PURCHASE_AMOUNT;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+
+public class Receipt {
+ private final Store store;
+ private final Cart cart;
+ private final Membership membership;
+
+ public Receipt(Store store, Cart cart, Membership membership) {
+ this.store = store;
+ this.cart = cart;
+ this.membership = membership;
+ }
+
+ @Override
+ public String toString() {
+ return buildReceiptContent();
+ }
+
+ public boolean hasFreeItems() {
+ return cart.getTotalFreeItemQuantity() > 0;
+ }
+
+ /**
+ * 장바구니 및 멤버십 정보를 바탕으로 영수증 내용을 빌드하는 메서드입니다.
+ * <p>
+ * 추가로 증정된 상품이 없다면 상품내역 정보는 출력하지 않습니다.
+ */
+ public String buildReceiptContent() {
+ StringBuilder result = new StringBuilder();
+ result.append(getReceiptHeader());
+ result.append(toStringOrderDetail());
+ if (hasFreeItems()) {
+ result.append(toStringRemainingItemsForPromotion());
+ }
+ result.append(toStringTotal());
+ return result.toString();
+ }
+
+ /**
+ * 영수증 헤더를 반환하는 메서드입니다.
+ */
+ public String getReceiptHeader() {
+ StringBuilder header = new StringBuilder();
+ header.append(RECEIPT_HEADER).append("\n");
+ header.append(String.format(PRODUCT_HEADER, PRODUCT_NAME, QUANTITY, PRICE)).append("\n");
+ return header.toString();
+ }
+
+ /**
+ * 주문 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringOrderDetail() {
+ StringBuilder orderDetail = new StringBuilder();
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ orderDetail.append(String.format(ORDER_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getQuantity()), numberFormat(cartItem.totalPrice())))
+ .append("\n");
+ }
+ return orderDetail.toString();
+ }
+
+ /**
+ * 증정 상품 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringRemainingItemsForPromotion() {
+ StringBuilder remainingitems = new StringBuilder();
+ remainingitems.append(PROMOTION_HEADER).append("\n");
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ if (cartItem.getFreeQuantity() > 0) {
+ remainingitems.append(String.format(PROMOTION_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getFreeQuantity())))
+ .append("\n");
+ }
+ }
+ return remainingitems.toString();
+ }
+
+ /**
+ * 총 금액 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringTotal() {
+ StringBuilder total = new StringBuilder();
+ total.append(LINE_SEPARATOR).append("\n");
+
+ total.append(formatTotalItemPrice())
+ .append("\n");
+ total.append(formatEventDiscount())
+ .append("\n");
+ total.append(formatMembershipDiscount())
+ .append("\n");
+ total.append(formatFinalAmount())
+ .append("\n");
+
+ return total.toString();
+ }
+
+ /**
+ * 총 구매 금액을 포맷팅하여 반환
+ */
+ public String formatTotalItemPrice() {
+ return String.format(TOTAL_DETAIL_FORMAT, TOTAL_PURCHASE_AMOUNT, numberFormat(cart.getTotalItemPrice()));
+ }
+
+ /**
+ * 이벤트 할인 금액을 포맷팅하여 반환
+ */
+ public String formatEventDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, EVENT_DISCOUNT, numberFormat(cart.getTotalFreeItemPrice()));
+ }
+
+ /**
+ * 멤버십 할인 금액을 포맷팅하여 반환
+ */
+ public String formatMembershipDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, MEMBERSHIP_DISCOUNT, numberFormat(membership.getMembershipPrice()));
+ }
+
+ /**
+ * 최종 금액을 포맷팅하여 반환
+ */
+ public String formatFinalAmount() {
+ int finalAmount = cart.getTotalItemPrice() - cart.getTotalFreeItemPrice() - membership.getMembershipPrice();
+ return String.format(TOTAL_DETAIL_FORMAT, FINAL_AMOUNT, numberFormat(finalAmount));
+ }
+
+ /**
+ * 숫자를 한국의 숫자 포맷에 맞게 형식화하는 메서드입니다.
+ */
+ public String numberFormat(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+} | Java | 개행 문자도 상수화하면 어떠신가요? |
@@ -0,0 +1,68 @@
+package store.parser;
+
+import static store.message.ErrorMessage.INVALID_DATA_FORMAT;
+
+import java.util.List;
+import store.dto.ProductDto;
+import store.dto.PromotionDto;
+
+public class FileReaderParser {
+
+ private static final String COMMA_DELIMITER = ",";
+ private static final String NULL_PROMOTION = "null";
+ private static final int EXPECTED_PRODUCT_LENGTH = 4;
+ private static final int EXPECTED_PROMOTION_LENGTH = 5;
+ private static final int HEADER_SKIP_COUNT = 1;
+
+ public List<ProductDto> parseProduct(List<String> productData) {
+ List<String> productRows = removeHeader(productData);
+ return productRows.stream()
+ .map(this::parseProductRow)
+ .toList();
+ }
+
+ public List<PromotionDto> parsePromotion(List<String> promotionData) {
+ List<String> promotionRows = removeHeader(promotionData);
+ return promotionRows.stream()
+ .map(this::parsePromotionRow)
+ .toList();
+ }
+
+ public ProductDto parseProductRow(String row) {
+ String[] split = row.split(COMMA_DELIMITER);
+ validateDataLength(split, EXPECTED_PRODUCT_LENGTH);
+ return createProductDto(split);
+ }
+
+ public PromotionDto parsePromotionRow(String row) {
+ String[] split = row.split(COMMA_DELIMITER);
+ validateDataLength(split, EXPECTED_PROMOTION_LENGTH);
+ return createPromotionDto(split);
+ }
+
+ public void validateDataLength(String[] split, int expectedLength) {
+ if (split.length != expectedLength) {
+ throw new IllegalStateException(INVALID_DATA_FORMAT.getMessage());
+ }
+ }
+
+ public ProductDto createProductDto(String[] split) {
+ return ProductDto.toProductDto(split[0], split[1], split[2], normalizePromotion(split[3]));
+ }
+
+ public PromotionDto createPromotionDto(String[] split) {
+ return new PromotionDto(split[0], split[1], split[2], split[3], split[4]);
+ }
+
+ public String normalizePromotion(String promotion) {
+ if (NULL_PROMOTION.equals(promotion)) {
+ return null;
+ }
+ return promotion;
+ }
+
+ public List<String> removeHeader(List<String> rows) {
+ return rows.stream().skip(HEADER_SKIP_COUNT).toList();
+ }
+
+} | Java | 파서 같은 경우는 유틸 클래스로 따로 작성하지 않으신 이유가 있을까요? |
@@ -0,0 +1,21 @@
+package store;
+
+import store.controller.FileReaderController;
+import store.controller.StoreController;
+import store.domain.Store;
+import store.dto.StoreDto;
+
+public class FrontController {
+ private final FileReaderController fileReaderController;
+ private final StoreController storeController;
+
+ public FrontController() {
+ this.fileReaderController = new FileReaderController();
+ this.storeController = new StoreController();
+ }
+
+ public void run() {
+ StoreDto storeDto = fileReaderController.runFileData();
+ storeController.run(storeDto);
+ }
+} | Java | frontController를 이용해서 파일 먼저 입력을 받으셨군요 좋은것 같아요! 👍 |
@@ -0,0 +1,136 @@
+package store.domain;
+
+import static store.constants.ProductConstants.OUT_OF_STOCK;
+import static store.constants.ProductConstants.PRODUCT_DESCRIPTION_PREFIX;
+import static store.constants.ProductConstants.UNIT_QUANTITY;
+import static store.constants.ProductConstants.UNIT_WON;
+import static store.message.ErrorMessage.NOT_FOUND_PROMOTION;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.validation.ProductValidator;
+
+public class Product {
+ private String name;
+ private int price;
+ private int quantity;
+ private Optional<Promotion> promotion;
+
+ private Product() {
+ }
+
+ public Product(ProductDto productDto, Optional<Promotion> promotion) {
+ ProductValidator.validate(productDto);
+ this.name = productDto.name();
+ this.price = Integer.parseInt(productDto.price());
+ this.quantity = Integer.parseInt(productDto.quantity());
+ this.promotion = promotion;
+ }
+
+ /**
+ * 프로모션을 적용 여부 검증
+ */
+ public boolean isEligibleForStandardPromotion(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return orderedQuantity <= quantity
+ && getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 보너스 상품이 적용 여부 검증
+ */
+ public boolean isEligibleForBonusProduct(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return getRemainingItemsForPromotion(orderedQuantity, promotionInfo) >= promotionInfo.getBuy()
+ && orderedQuantity + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 프로모션 조건을 만족하는 남은 수량을 계산
+ */
+ public int getRemainingItemsForPromotion(int orderedQuantity, Promotion promotionInfo) {
+ return orderedQuantity % promotionInfo.getTotalRequiredQuantity();
+ }
+
+ /**
+ * 보너스 상품의 수량을 계산
+ */
+ public int calculateBonusQuantity(int orderedQuantity, Promotion promotion) {
+ return (orderedQuantity / promotion.getTotalRequiredQuantity()) * promotion.getGet();
+ }
+
+ /**
+ * 프로모션이 적용된 후, 실제 주문 가능한 수량을 계산
+ */
+ public int calculateQuantityAfterPromotion(int orderedQuantity) {
+ Promotion promotionInfo = getPromotionOrElseThrow();
+ int requiredQuantity = promotionInfo.getTotalRequiredQuantity();
+ return (orderedQuantity - quantity) + (quantity % requiredQuantity);
+ }
+
+ /**
+ * 프로모션이 존재하지 않으면 예외 발생
+ */
+ public Promotion getPromotionOrElseThrow() {
+ return promotion.orElseThrow(() -> new IllegalArgumentException(NOT_FOUND_PROMOTION.getMessage()));
+ }
+
+ /**
+ * 값을 가지고 있는 주체이기 때문에 상품 리스트를 포맷을 합니다.
+ */
+ @Override
+ public String toString() {
+ return PRODUCT_DESCRIPTION_PREFIX
+ + name + " "
+ + getFormatKoreanLocale(price) + UNIT_WON
+ + getFormattedQuantity()
+ + getFormattedPromotion();
+ }
+
+ public String getFormattedQuantity() {
+ if (quantity < 1) {
+ return OUT_OF_STOCK;
+ }
+ return getFormatKoreanLocale(quantity) + UNIT_QUANTITY;
+ }
+
+ public String getFormatKoreanLocale(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+
+ public String getFormattedPromotion() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Optional<Promotion> getPromotion() {
+ return promotion;
+ }
+
+ public boolean isPromotionalProduct() {
+ return promotion.isPresent();
+ }
+
+ public void decreaseQuantity(int orderQuantity) {
+ this.quantity -= orderQuantity;
+ }
+} | Java | 이름은 변경 가능성이 없기때문에 final로 선언해주면 좋을 것 같아요! |
@@ -0,0 +1,136 @@
+package store.domain;
+
+import static store.constants.ProductConstants.OUT_OF_STOCK;
+import static store.constants.ProductConstants.PRODUCT_DESCRIPTION_PREFIX;
+import static store.constants.ProductConstants.UNIT_QUANTITY;
+import static store.constants.ProductConstants.UNIT_WON;
+import static store.message.ErrorMessage.NOT_FOUND_PROMOTION;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.validation.ProductValidator;
+
+public class Product {
+ private String name;
+ private int price;
+ private int quantity;
+ private Optional<Promotion> promotion;
+
+ private Product() {
+ }
+
+ public Product(ProductDto productDto, Optional<Promotion> promotion) {
+ ProductValidator.validate(productDto);
+ this.name = productDto.name();
+ this.price = Integer.parseInt(productDto.price());
+ this.quantity = Integer.parseInt(productDto.quantity());
+ this.promotion = promotion;
+ }
+
+ /**
+ * 프로모션을 적용 여부 검증
+ */
+ public boolean isEligibleForStandardPromotion(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return orderedQuantity <= quantity
+ && getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 보너스 상품이 적용 여부 검증
+ */
+ public boolean isEligibleForBonusProduct(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return getRemainingItemsForPromotion(orderedQuantity, promotionInfo) >= promotionInfo.getBuy()
+ && orderedQuantity + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 프로모션 조건을 만족하는 남은 수량을 계산
+ */
+ public int getRemainingItemsForPromotion(int orderedQuantity, Promotion promotionInfo) {
+ return orderedQuantity % promotionInfo.getTotalRequiredQuantity();
+ }
+
+ /**
+ * 보너스 상품의 수량을 계산
+ */
+ public int calculateBonusQuantity(int orderedQuantity, Promotion promotion) {
+ return (orderedQuantity / promotion.getTotalRequiredQuantity()) * promotion.getGet();
+ }
+
+ /**
+ * 프로모션이 적용된 후, 실제 주문 가능한 수량을 계산
+ */
+ public int calculateQuantityAfterPromotion(int orderedQuantity) {
+ Promotion promotionInfo = getPromotionOrElseThrow();
+ int requiredQuantity = promotionInfo.getTotalRequiredQuantity();
+ return (orderedQuantity - quantity) + (quantity % requiredQuantity);
+ }
+
+ /**
+ * 프로모션이 존재하지 않으면 예외 발생
+ */
+ public Promotion getPromotionOrElseThrow() {
+ return promotion.orElseThrow(() -> new IllegalArgumentException(NOT_FOUND_PROMOTION.getMessage()));
+ }
+
+ /**
+ * 값을 가지고 있는 주체이기 때문에 상품 리스트를 포맷을 합니다.
+ */
+ @Override
+ public String toString() {
+ return PRODUCT_DESCRIPTION_PREFIX
+ + name + " "
+ + getFormatKoreanLocale(price) + UNIT_WON
+ + getFormattedQuantity()
+ + getFormattedPromotion();
+ }
+
+ public String getFormattedQuantity() {
+ if (quantity < 1) {
+ return OUT_OF_STOCK;
+ }
+ return getFormatKoreanLocale(quantity) + UNIT_QUANTITY;
+ }
+
+ public String getFormatKoreanLocale(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+
+ public String getFormattedPromotion() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Optional<Promotion> getPromotion() {
+ return promotion;
+ }
+
+ public boolean isPromotionalProduct() {
+ return promotion.isPresent();
+ }
+
+ public void decreaseQuantity(int orderQuantity) {
+ this.quantity -= orderQuantity;
+ }
+} | Java | Optional 좋네요 👍 |
@@ -0,0 +1,136 @@
+package store.domain;
+
+import static store.constants.ProductConstants.OUT_OF_STOCK;
+import static store.constants.ProductConstants.PRODUCT_DESCRIPTION_PREFIX;
+import static store.constants.ProductConstants.UNIT_QUANTITY;
+import static store.constants.ProductConstants.UNIT_WON;
+import static store.message.ErrorMessage.NOT_FOUND_PROMOTION;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.validation.ProductValidator;
+
+public class Product {
+ private String name;
+ private int price;
+ private int quantity;
+ private Optional<Promotion> promotion;
+
+ private Product() {
+ }
+
+ public Product(ProductDto productDto, Optional<Promotion> promotion) {
+ ProductValidator.validate(productDto);
+ this.name = productDto.name();
+ this.price = Integer.parseInt(productDto.price());
+ this.quantity = Integer.parseInt(productDto.quantity());
+ this.promotion = promotion;
+ }
+
+ /**
+ * 프로모션을 적용 여부 검증
+ */
+ public boolean isEligibleForStandardPromotion(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return orderedQuantity <= quantity
+ && getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 보너스 상품이 적용 여부 검증
+ */
+ public boolean isEligibleForBonusProduct(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return getRemainingItemsForPromotion(orderedQuantity, promotionInfo) >= promotionInfo.getBuy()
+ && orderedQuantity + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 프로모션 조건을 만족하는 남은 수량을 계산
+ */
+ public int getRemainingItemsForPromotion(int orderedQuantity, Promotion promotionInfo) {
+ return orderedQuantity % promotionInfo.getTotalRequiredQuantity();
+ }
+
+ /**
+ * 보너스 상품의 수량을 계산
+ */
+ public int calculateBonusQuantity(int orderedQuantity, Promotion promotion) {
+ return (orderedQuantity / promotion.getTotalRequiredQuantity()) * promotion.getGet();
+ }
+
+ /**
+ * 프로모션이 적용된 후, 실제 주문 가능한 수량을 계산
+ */
+ public int calculateQuantityAfterPromotion(int orderedQuantity) {
+ Promotion promotionInfo = getPromotionOrElseThrow();
+ int requiredQuantity = promotionInfo.getTotalRequiredQuantity();
+ return (orderedQuantity - quantity) + (quantity % requiredQuantity);
+ }
+
+ /**
+ * 프로모션이 존재하지 않으면 예외 발생
+ */
+ public Promotion getPromotionOrElseThrow() {
+ return promotion.orElseThrow(() -> new IllegalArgumentException(NOT_FOUND_PROMOTION.getMessage()));
+ }
+
+ /**
+ * 값을 가지고 있는 주체이기 때문에 상품 리스트를 포맷을 합니다.
+ */
+ @Override
+ public String toString() {
+ return PRODUCT_DESCRIPTION_PREFIX
+ + name + " "
+ + getFormatKoreanLocale(price) + UNIT_WON
+ + getFormattedQuantity()
+ + getFormattedPromotion();
+ }
+
+ public String getFormattedQuantity() {
+ if (quantity < 1) {
+ return OUT_OF_STOCK;
+ }
+ return getFormatKoreanLocale(quantity) + UNIT_QUANTITY;
+ }
+
+ public String getFormatKoreanLocale(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+
+ public String getFormattedPromotion() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Optional<Promotion> getPromotion() {
+ return promotion;
+ }
+
+ public boolean isPromotionalProduct() {
+ return promotion.isPresent();
+ }
+
+ public void decreaseQuantity(int orderQuantity) {
+ this.quantity -= orderQuantity;
+ }
+} | Java | Model에서 DTO를 의존하면 View에 의존하는것과 비슷하다고 생각합니다.
DTO의 변경에 Model의 코드가 변경되어야해요!
Service에서 DTO관련된 로직을 전처리 해주면 좋을 것 같아요😃 |
@@ -0,0 +1,136 @@
+package store.domain;
+
+import static store.constants.ProductConstants.OUT_OF_STOCK;
+import static store.constants.ProductConstants.PRODUCT_DESCRIPTION_PREFIX;
+import static store.constants.ProductConstants.UNIT_QUANTITY;
+import static store.constants.ProductConstants.UNIT_WON;
+import static store.message.ErrorMessage.NOT_FOUND_PROMOTION;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.validation.ProductValidator;
+
+public class Product {
+ private String name;
+ private int price;
+ private int quantity;
+ private Optional<Promotion> promotion;
+
+ private Product() {
+ }
+
+ public Product(ProductDto productDto, Optional<Promotion> promotion) {
+ ProductValidator.validate(productDto);
+ this.name = productDto.name();
+ this.price = Integer.parseInt(productDto.price());
+ this.quantity = Integer.parseInt(productDto.quantity());
+ this.promotion = promotion;
+ }
+
+ /**
+ * 프로모션을 적용 여부 검증
+ */
+ public boolean isEligibleForStandardPromotion(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return orderedQuantity <= quantity
+ && getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 보너스 상품이 적용 여부 검증
+ */
+ public boolean isEligibleForBonusProduct(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return getRemainingItemsForPromotion(orderedQuantity, promotionInfo) >= promotionInfo.getBuy()
+ && orderedQuantity + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 프로모션 조건을 만족하는 남은 수량을 계산
+ */
+ public int getRemainingItemsForPromotion(int orderedQuantity, Promotion promotionInfo) {
+ return orderedQuantity % promotionInfo.getTotalRequiredQuantity();
+ }
+
+ /**
+ * 보너스 상품의 수량을 계산
+ */
+ public int calculateBonusQuantity(int orderedQuantity, Promotion promotion) {
+ return (orderedQuantity / promotion.getTotalRequiredQuantity()) * promotion.getGet();
+ }
+
+ /**
+ * 프로모션이 적용된 후, 실제 주문 가능한 수량을 계산
+ */
+ public int calculateQuantityAfterPromotion(int orderedQuantity) {
+ Promotion promotionInfo = getPromotionOrElseThrow();
+ int requiredQuantity = promotionInfo.getTotalRequiredQuantity();
+ return (orderedQuantity - quantity) + (quantity % requiredQuantity);
+ }
+
+ /**
+ * 프로모션이 존재하지 않으면 예외 발생
+ */
+ public Promotion getPromotionOrElseThrow() {
+ return promotion.orElseThrow(() -> new IllegalArgumentException(NOT_FOUND_PROMOTION.getMessage()));
+ }
+
+ /**
+ * 값을 가지고 있는 주체이기 때문에 상품 리스트를 포맷을 합니다.
+ */
+ @Override
+ public String toString() {
+ return PRODUCT_DESCRIPTION_PREFIX
+ + name + " "
+ + getFormatKoreanLocale(price) + UNIT_WON
+ + getFormattedQuantity()
+ + getFormattedPromotion();
+ }
+
+ public String getFormattedQuantity() {
+ if (quantity < 1) {
+ return OUT_OF_STOCK;
+ }
+ return getFormatKoreanLocale(quantity) + UNIT_QUANTITY;
+ }
+
+ public String getFormatKoreanLocale(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+
+ public String getFormattedPromotion() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Optional<Promotion> getPromotion() {
+ return promotion;
+ }
+
+ public boolean isPromotionalProduct() {
+ return promotion.isPresent();
+ }
+
+ public void decreaseQuantity(int orderQuantity) {
+ this.quantity -= orderQuantity;
+ }
+} | Java | Optional의 기능을 활용해보면 어떨까요!?
```suggestion
public boolean isEligibleForStandardPromotion(int orderedQuantity) {
return promotion.map(promotionInfo ->
orderedQuantity <= quantity &&
getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity
).orElse(false);
}
``` |
@@ -0,0 +1,136 @@
+package store.domain;
+
+import static store.constants.ProductConstants.OUT_OF_STOCK;
+import static store.constants.ProductConstants.PRODUCT_DESCRIPTION_PREFIX;
+import static store.constants.ProductConstants.UNIT_QUANTITY;
+import static store.constants.ProductConstants.UNIT_WON;
+import static store.message.ErrorMessage.NOT_FOUND_PROMOTION;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.validation.ProductValidator;
+
+public class Product {
+ private String name;
+ private int price;
+ private int quantity;
+ private Optional<Promotion> promotion;
+
+ private Product() {
+ }
+
+ public Product(ProductDto productDto, Optional<Promotion> promotion) {
+ ProductValidator.validate(productDto);
+ this.name = productDto.name();
+ this.price = Integer.parseInt(productDto.price());
+ this.quantity = Integer.parseInt(productDto.quantity());
+ this.promotion = promotion;
+ }
+
+ /**
+ * 프로모션을 적용 여부 검증
+ */
+ public boolean isEligibleForStandardPromotion(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return orderedQuantity <= quantity
+ && getRemainingItemsForPromotion(orderedQuantity, promotionInfo) + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 보너스 상품이 적용 여부 검증
+ */
+ public boolean isEligibleForBonusProduct(int orderedQuantity) {
+ if (promotion.isEmpty()) {
+ return false;
+ }
+ Promotion promotionInfo = promotion.get();
+ return getRemainingItemsForPromotion(orderedQuantity, promotionInfo) >= promotionInfo.getBuy()
+ && orderedQuantity + promotionInfo.getGet() <= quantity;
+ }
+
+ /**
+ * 프로모션 조건을 만족하는 남은 수량을 계산
+ */
+ public int getRemainingItemsForPromotion(int orderedQuantity, Promotion promotionInfo) {
+ return orderedQuantity % promotionInfo.getTotalRequiredQuantity();
+ }
+
+ /**
+ * 보너스 상품의 수량을 계산
+ */
+ public int calculateBonusQuantity(int orderedQuantity, Promotion promotion) {
+ return (orderedQuantity / promotion.getTotalRequiredQuantity()) * promotion.getGet();
+ }
+
+ /**
+ * 프로모션이 적용된 후, 실제 주문 가능한 수량을 계산
+ */
+ public int calculateQuantityAfterPromotion(int orderedQuantity) {
+ Promotion promotionInfo = getPromotionOrElseThrow();
+ int requiredQuantity = promotionInfo.getTotalRequiredQuantity();
+ return (orderedQuantity - quantity) + (quantity % requiredQuantity);
+ }
+
+ /**
+ * 프로모션이 존재하지 않으면 예외 발생
+ */
+ public Promotion getPromotionOrElseThrow() {
+ return promotion.orElseThrow(() -> new IllegalArgumentException(NOT_FOUND_PROMOTION.getMessage()));
+ }
+
+ /**
+ * 값을 가지고 있는 주체이기 때문에 상품 리스트를 포맷을 합니다.
+ */
+ @Override
+ public String toString() {
+ return PRODUCT_DESCRIPTION_PREFIX
+ + name + " "
+ + getFormatKoreanLocale(price) + UNIT_WON
+ + getFormattedQuantity()
+ + getFormattedPromotion();
+ }
+
+ public String getFormattedQuantity() {
+ if (quantity < 1) {
+ return OUT_OF_STOCK;
+ }
+ return getFormatKoreanLocale(quantity) + UNIT_QUANTITY;
+ }
+
+ public String getFormatKoreanLocale(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+
+ public String getFormattedPromotion() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Optional<Promotion> getPromotion() {
+ return promotion;
+ }
+
+ public boolean isPromotionalProduct() {
+ return promotion.isPresent();
+ }
+
+ public void decreaseQuantity(int orderQuantity) {
+ this.quantity -= orderQuantity;
+ }
+} | Java | 꼼꼼함이 보이네요 👀 |
@@ -0,0 +1,152 @@
+package store.domain;
+
+import static store.constants.ReceiptConstants.EVENT_DISCOUNT;
+import static store.constants.ReceiptConstants.FINAL_AMOUNT;
+import static store.constants.ReceiptConstants.LINE_SEPARATOR;
+import static store.constants.ReceiptConstants.MEMBERSHIP_DISCOUNT;
+import static store.constants.ReceiptConstants.ORDER_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PRICE;
+import static store.constants.ReceiptConstants.PRODUCT_HEADER;
+import static store.constants.ReceiptConstants.PRODUCT_NAME;
+import static store.constants.ReceiptConstants.PROMOTION_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PROMOTION_HEADER;
+import static store.constants.ReceiptConstants.QUANTITY;
+import static store.constants.ReceiptConstants.RECEIPT_HEADER;
+import static store.constants.ReceiptConstants.TOTAL_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.TOTAL_PURCHASE_AMOUNT;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+
+public class Receipt {
+ private final Store store;
+ private final Cart cart;
+ private final Membership membership;
+
+ public Receipt(Store store, Cart cart, Membership membership) {
+ this.store = store;
+ this.cart = cart;
+ this.membership = membership;
+ }
+
+ @Override
+ public String toString() {
+ return buildReceiptContent();
+ }
+
+ public boolean hasFreeItems() {
+ return cart.getTotalFreeItemQuantity() > 0;
+ }
+
+ /**
+ * 장바구니 및 멤버십 정보를 바탕으로 영수증 내용을 빌드하는 메서드입니다.
+ * <p>
+ * 추가로 증정된 상품이 없다면 상품내역 정보는 출력하지 않습니다.
+ */
+ public String buildReceiptContent() {
+ StringBuilder result = new StringBuilder();
+ result.append(getReceiptHeader());
+ result.append(toStringOrderDetail());
+ if (hasFreeItems()) {
+ result.append(toStringRemainingItemsForPromotion());
+ }
+ result.append(toStringTotal());
+ return result.toString();
+ }
+
+ /**
+ * 영수증 헤더를 반환하는 메서드입니다.
+ */
+ public String getReceiptHeader() {
+ StringBuilder header = new StringBuilder();
+ header.append(RECEIPT_HEADER).append("\n");
+ header.append(String.format(PRODUCT_HEADER, PRODUCT_NAME, QUANTITY, PRICE)).append("\n");
+ return header.toString();
+ }
+
+ /**
+ * 주문 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringOrderDetail() {
+ StringBuilder orderDetail = new StringBuilder();
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ orderDetail.append(String.format(ORDER_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getQuantity()), numberFormat(cartItem.totalPrice())))
+ .append("\n");
+ }
+ return orderDetail.toString();
+ }
+
+ /**
+ * 증정 상품 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringRemainingItemsForPromotion() {
+ StringBuilder remainingitems = new StringBuilder();
+ remainingitems.append(PROMOTION_HEADER).append("\n");
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ if (cartItem.getFreeQuantity() > 0) {
+ remainingitems.append(String.format(PROMOTION_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getFreeQuantity())))
+ .append("\n");
+ }
+ }
+ return remainingitems.toString();
+ }
+
+ /**
+ * 총 금액 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringTotal() {
+ StringBuilder total = new StringBuilder();
+ total.append(LINE_SEPARATOR).append("\n");
+
+ total.append(formatTotalItemPrice())
+ .append("\n");
+ total.append(formatEventDiscount())
+ .append("\n");
+ total.append(formatMembershipDiscount())
+ .append("\n");
+ total.append(formatFinalAmount())
+ .append("\n");
+
+ return total.toString();
+ }
+
+ /**
+ * 총 구매 금액을 포맷팅하여 반환
+ */
+ public String formatTotalItemPrice() {
+ return String.format(TOTAL_DETAIL_FORMAT, TOTAL_PURCHASE_AMOUNT, numberFormat(cart.getTotalItemPrice()));
+ }
+
+ /**
+ * 이벤트 할인 금액을 포맷팅하여 반환
+ */
+ public String formatEventDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, EVENT_DISCOUNT, numberFormat(cart.getTotalFreeItemPrice()));
+ }
+
+ /**
+ * 멤버십 할인 금액을 포맷팅하여 반환
+ */
+ public String formatMembershipDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, MEMBERSHIP_DISCOUNT, numberFormat(membership.getMembershipPrice()));
+ }
+
+ /**
+ * 최종 금액을 포맷팅하여 반환
+ */
+ public String formatFinalAmount() {
+ int finalAmount = cart.getTotalItemPrice() - cart.getTotalFreeItemPrice() - membership.getMembershipPrice();
+ return String.format(TOTAL_DETAIL_FORMAT, FINAL_AMOUNT, numberFormat(finalAmount));
+ }
+
+ /**
+ * 숫자를 한국의 숫자 포맷에 맞게 형식화하는 메서드입니다.
+ */
+ public String numberFormat(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+} | Java | Model레이어에서 View의 내용을 가공하기 보단, Controller or Service에서 진행해주는건 어떨까요?
지금은 View가 변경되면 Model도 변경되어야 할것 같아요! |
@@ -0,0 +1,152 @@
+package store.domain;
+
+import static store.constants.ReceiptConstants.EVENT_DISCOUNT;
+import static store.constants.ReceiptConstants.FINAL_AMOUNT;
+import static store.constants.ReceiptConstants.LINE_SEPARATOR;
+import static store.constants.ReceiptConstants.MEMBERSHIP_DISCOUNT;
+import static store.constants.ReceiptConstants.ORDER_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PRICE;
+import static store.constants.ReceiptConstants.PRODUCT_HEADER;
+import static store.constants.ReceiptConstants.PRODUCT_NAME;
+import static store.constants.ReceiptConstants.PROMOTION_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.PROMOTION_HEADER;
+import static store.constants.ReceiptConstants.QUANTITY;
+import static store.constants.ReceiptConstants.RECEIPT_HEADER;
+import static store.constants.ReceiptConstants.TOTAL_DETAIL_FORMAT;
+import static store.constants.ReceiptConstants.TOTAL_PURCHASE_AMOUNT;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+
+public class Receipt {
+ private final Store store;
+ private final Cart cart;
+ private final Membership membership;
+
+ public Receipt(Store store, Cart cart, Membership membership) {
+ this.store = store;
+ this.cart = cart;
+ this.membership = membership;
+ }
+
+ @Override
+ public String toString() {
+ return buildReceiptContent();
+ }
+
+ public boolean hasFreeItems() {
+ return cart.getTotalFreeItemQuantity() > 0;
+ }
+
+ /**
+ * 장바구니 및 멤버십 정보를 바탕으로 영수증 내용을 빌드하는 메서드입니다.
+ * <p>
+ * 추가로 증정된 상품이 없다면 상품내역 정보는 출력하지 않습니다.
+ */
+ public String buildReceiptContent() {
+ StringBuilder result = new StringBuilder();
+ result.append(getReceiptHeader());
+ result.append(toStringOrderDetail());
+ if (hasFreeItems()) {
+ result.append(toStringRemainingItemsForPromotion());
+ }
+ result.append(toStringTotal());
+ return result.toString();
+ }
+
+ /**
+ * 영수증 헤더를 반환하는 메서드입니다.
+ */
+ public String getReceiptHeader() {
+ StringBuilder header = new StringBuilder();
+ header.append(RECEIPT_HEADER).append("\n");
+ header.append(String.format(PRODUCT_HEADER, PRODUCT_NAME, QUANTITY, PRICE)).append("\n");
+ return header.toString();
+ }
+
+ /**
+ * 주문 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringOrderDetail() {
+ StringBuilder orderDetail = new StringBuilder();
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ orderDetail.append(String.format(ORDER_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getQuantity()), numberFormat(cartItem.totalPrice())))
+ .append("\n");
+ }
+ return orderDetail.toString();
+ }
+
+ /**
+ * 증정 상품 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringRemainingItemsForPromotion() {
+ StringBuilder remainingitems = new StringBuilder();
+ remainingitems.append(PROMOTION_HEADER).append("\n");
+
+ for (CartItem cartItem : cart.getAllItemsInCart()) {
+ if (cartItem.getFreeQuantity() > 0) {
+ remainingitems.append(String.format(PROMOTION_DETAIL_FORMAT, cartItem.getProductName(),
+ numberFormat(cartItem.getFreeQuantity())))
+ .append("\n");
+ }
+ }
+ return remainingitems.toString();
+ }
+
+ /**
+ * 총 금액 내역을 문자열로 반환하는 메서드입니다.
+ */
+ public String toStringTotal() {
+ StringBuilder total = new StringBuilder();
+ total.append(LINE_SEPARATOR).append("\n");
+
+ total.append(formatTotalItemPrice())
+ .append("\n");
+ total.append(formatEventDiscount())
+ .append("\n");
+ total.append(formatMembershipDiscount())
+ .append("\n");
+ total.append(formatFinalAmount())
+ .append("\n");
+
+ return total.toString();
+ }
+
+ /**
+ * 총 구매 금액을 포맷팅하여 반환
+ */
+ public String formatTotalItemPrice() {
+ return String.format(TOTAL_DETAIL_FORMAT, TOTAL_PURCHASE_AMOUNT, numberFormat(cart.getTotalItemPrice()));
+ }
+
+ /**
+ * 이벤트 할인 금액을 포맷팅하여 반환
+ */
+ public String formatEventDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, EVENT_DISCOUNT, numberFormat(cart.getTotalFreeItemPrice()));
+ }
+
+ /**
+ * 멤버십 할인 금액을 포맷팅하여 반환
+ */
+ public String formatMembershipDiscount() {
+ return String.format(TOTAL_DETAIL_FORMAT, MEMBERSHIP_DISCOUNT, numberFormat(membership.getMembershipPrice()));
+ }
+
+ /**
+ * 최종 금액을 포맷팅하여 반환
+ */
+ public String formatFinalAmount() {
+ int finalAmount = cart.getTotalItemPrice() - cart.getTotalFreeItemPrice() - membership.getMembershipPrice();
+ return String.format(TOTAL_DETAIL_FORMAT, FINAL_AMOUNT, numberFormat(finalAmount));
+ }
+
+ /**
+ * 숫자를 한국의 숫자 포맷에 맞게 형식화하는 메서드입니다.
+ */
+ public String numberFormat(int number) {
+ return NumberFormat.getInstance(Locale.KOREA).format(number);
+ }
+} | Java | 함수형 인터페이스도 depth가 있다고 생각합니다!
모듈화를 해보는건 어떨까요? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.