code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,70 @@
+package store.model.repository;
+
+import store.Message.ErrorMessage;
+import store.config.DataInitializer;
+import store.config.ProductsData;
+import store.model.domain.Product;
+import store.constant.ProductType;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductRepository {
+ public static final String DEFAULT_PRODUCT_FILE_PATH = "src/main/resources/products.md";
+
+ private final Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ private final Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ public ProductRepository(String filePath) {
+ DataInitializer initializer = DataInitializer.getInstance();
+ try {
+ ProductsData productsData = initializer.loadProducts(filePath);
+ this.info.putAll(productsData.info());
+ this.stock.putAll(productsData.stock());
+ } catch (IOException e) {
+ throw new RuntimeException(ErrorMessage.FILE_ERROR.getMessage(filePath));
+ }
+ }
+
+ public ProductRepository() {
+ this(DEFAULT_PRODUCT_FILE_PATH);
+ }
+
+ public List<Product> findAllInfo() {
+ return info.values().stream()
+ .flatMap(innerMap -> innerMap.values().stream())
+ .toList();
+ }
+
+ public Product findInfo(String name, ProductType productType) {
+ Map<String, Product> typeInfo = info.get(productType);
+ return typeInfo.getOrDefault(name, null);
+ }
+
+ public int findStock(String name, ProductType productType) {
+ Map<String, Integer> typeStock = stock.get(productType);
+ return typeStock.getOrDefault(name, 0);
+ }
+
+ public boolean reduceStock(String name, ProductType productType, int quantity) {
+ Map<String, Integer> typeStocks = stock.get(productType);
+ checkStock(name, typeStocks);
+
+ int currentStock = typeStocks.get(name);
+ if (currentStock < quantity) {
+ return false;
+ }
+
+ typeStocks.put(name, currentStock - quantity);
+ return true;
+ }
+
+ private static void checkStock(String name, Map<String, Integer> stock) {
+ if (stock == null || !stock.containsKey(name)) {
+ throw new IllegalStateException(ErrorMessage.NON_EXISTENT_PRODUCT.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | 감사합니다. optional로 반환했다면 호출하는 곳에서 더 깔끔하게 사용할 수 있겠네요! |
@@ -0,0 +1,87 @@
+package store.view;
+
+import store.dto.ProductWithStockDto;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.constant.OutputFormats;
+import store.constant.OutputMessages;
+import store.constant.ReceiptLabels;
+
+import java.util.List;
+
+public class OutputView {
+ private static final String REGULAR = "null";
+
+ public void printHelloMessage() {
+ System.out.println(OutputMessages.WELCOME_MESSAGE);
+ }
+
+ public void printProducts(List<ProductWithStockDto> products) {
+ System.out.println(OutputMessages.CURRENT_PRODUCTS_MESSAGE);
+ products.forEach(this::printProduct);
+ }
+
+ public void printReceipt(List<ShoppingCartCheck> shoppingCartChecks, ReceiptTotals totals) {
+ printReceiptHeader();
+ printReceiptItems(shoppingCartChecks);
+ printReceiptGiftItems(shoppingCartChecks);
+ printReceiptTotals(totals);
+ }
+
+ private void printProduct(ProductWithStockDto product) {
+ String promotion = product.promotion();
+ if (promotion.equals(REGULAR)) {
+ promotion = OutputMessages.EMPTY_STRING;
+ }
+ if (product.stock() == 0) {
+ System.out.printf(OutputFormats.PRODUCT_OUT_OF_STOCK_FORMAT, product.name(), product.price(), OutputMessages.NO_STOCK, promotion);
+ return;
+ }
+ System.out.printf(OutputFormats.PRODUCT_IN_STOCK_FORMAT, product.name(), product.price(), product.stock(), promotion);
+ }
+
+ private void printReceiptHeader() {
+ System.out.println(ReceiptLabels.HEADER);
+ System.out.printf(OutputFormats.HEADER_FORMAT, ReceiptLabels.PRODUCT_NAME, ReceiptLabels.COUNT, ReceiptLabels.PRICE);
+ }
+
+ private void printReceiptItems(List<ShoppingCartCheck> shoppingCartChecks) {
+ for (ShoppingCartCheck dto : shoppingCartChecks) {
+ int price = dto.getProductPrice() * dto.getRequestCount();
+ System.out.printf(OutputFormats.ITEM_FORMAT, dto.getProductName(), dto.getRequestCount(), price);
+ }
+ }
+
+ private void printReceiptGiftItems(List<ShoppingCartCheck> shoppingCartChecks) {
+ List<ShoppingCartCheck> giftItems = shoppingCartChecks.stream()
+ .filter(dto -> dto.getFreeCount() > 0)
+ .filter(ShoppingCartCheck::isActivePromotion)
+ .toList();
+
+ if (!giftItems.isEmpty()) {
+ System.out.println(ReceiptLabels.GIFT_HEADER);
+ for (ShoppingCartCheck dto : giftItems) {
+ System.out.printf(OutputFormats.GIFT_ITEM_FORMAT, dto.getProductName(), dto.getFreeCount());
+ }
+ }
+ }
+
+ private void printReceiptTotals(ReceiptTotals totals) {
+ System.out.println(ReceiptLabels.FOOTER);
+ System.out.printf(OutputFormats.ITEM_FORMAT, ReceiptLabels.TOTAL_LABEL, totals.totalCount, totals.totalPrice);
+
+ String giftPriceDisplay = formatDiscount(totals.giftPrice);
+ System.out.printf(OutputFormats.DISCOUNT_FORMAT, ReceiptLabels.EVENT_DISCOUNT_LABEL, giftPriceDisplay);
+
+ String membershipPriceDisplay = formatDiscount(totals.membershipPrice);
+ System.out.printf(OutputFormats.DISCOUNT_FORMAT, ReceiptLabels.MEMBERSHIP_DISCOUNT_LABEL, membershipPriceDisplay);
+
+ int finalAmount = totals.totalPrice + totals.giftPrice + totals.membershipPrice;
+ System.out.printf(OutputFormats.TOTAL_FORMAT, ReceiptLabels.FINAL_AMOUNT_LABEL, finalAmount);
+ }
+
+ private String formatDiscount(int discount) {
+ if (discount == 0) return "-0";
+ return String.format("%,d", discount);
+ }
+}
\ No newline at end of file | Java | 감사합니다. |
@@ -1,7 +1,27 @@
package store;
+import camp.nextstep.edu.missionutils.Console;
+import store.controller.StoreController;
+import store.model.repository.ProductRepository;
+import store.model.repository.PromotionRepository;
+import store.model.service.ReceiptCalculationService;
+import store.model.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ ProductRepository productRepository = new ProductRepository();
+ PromotionRepository promotionRepository = new PromotionRepository();
+
+ StoreService storeService = new StoreService(productRepository, promotionRepository);
+ ReceiptCalculationService receiptCalculationService = new ReceiptCalculationService();
+
+ InputView inputView = new InputView();
+ OutputView outputView = new OutputView();
+ StoreController storeController = new StoreController(inputView, outputView, storeService, receiptCalculationService);
+
+ storeController.run();
+ Console.close();
}
} | Java | Repository 계층을 사용하면 얻을 수 있는 장점이 무엇인지 궁금합니다! |
@@ -0,0 +1,24 @@
+package store.Message;
+
+public enum ErrorMessage {
+
+ INVALID_FORMAT("올바르지 않은 형식으로 입력했습니다."),
+ NON_EXISTENT_PRODUCT("존재하지 않는 상품입니다."),
+ EXCEEDS_STOCK("재고 수량을 초과하여 구매할 수 없습니다."),
+ GENERIC_ERROR("잘못된 입력입니다."),
+ FILE_ERROR("잘못된 데이터 파일입니다:");
+
+ private final String message;
+
+ ErrorMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return String.format("[ERROR] %s 다시 입력해 주세요.", message);
+ }
+
+ public String getMessage(String detail) {
+ return String.format("[ERROR] %s : %s", message, detail);
+ }
+}
\ No newline at end of file | Java | 메시지 포멧 형식에서 값을 삽입하는 방법이 신기합니다. 이 부분도 상수로 정의해 적용해 보는 건 어떨까요!? |
@@ -0,0 +1,122 @@
+package store.config;
+
+import store.model.domain.Product;
+import store.constant.ProductType;
+import store.model.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class DataInitializer {
+ public static final String REGULAR = "null";
+
+ private static DataInitializer instance;
+
+ private DataInitializer() {
+ }
+
+ public static DataInitializer getInstance() {
+ if (instance == null) {
+ instance = new DataInitializer();
+ }
+ return instance;
+ }
+
+ public ProductsData loadProducts(String filePath) throws IOException {
+ Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processProduct(br, info, stock);
+ }
+
+ return new ProductsData(info, stock);
+ }
+
+ public Map<String, Promotion> loadPromotions(String filePath) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processPromotion(br, promotions);
+ }
+
+ return promotions;
+ }
+
+ private BufferedReader readFile(String filePath) throws IOException {
+ return new BufferedReader(new FileReader(filePath));
+ }
+
+ private void processProduct(BufferedReader br,
+ Map<ProductType, Map<String, Product>> info,
+ Map<ProductType, Map<String, Integer>> stock) throws IOException {
+ Map<String, Product> regularProducts = new LinkedHashMap<>();
+ Map<String, Product> promotionProducts = new LinkedHashMap<>();
+ Map<String, Integer> regularStocks = new HashMap<>();
+ Map<String, Integer> promotionStocks = new HashMap<>();
+
+ br.readLine(); // 헤더 생략
+ String line;
+ while ((line = br.readLine()) != null) {
+ ProductData productData = parseProduct(line);
+ addProduct(productData, regularProducts, promotionProducts, regularStocks, promotionStocks);
+ }
+
+ info.put(ProductType.REGULAR, regularProducts);
+ info.put(ProductType.PROMOTION, promotionProducts);
+ stock.put(ProductType.REGULAR, regularStocks);
+ stock.put(ProductType.PROMOTION, promotionStocks);
+ }
+
+ private ProductData parseProduct(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int price = Integer.parseInt(data[1]);
+ int quantity = Integer.parseInt(data[2]);
+ String promotion = data[3];
+ return new ProductData(name, price, quantity, promotion);
+ }
+
+ private void addProduct(ProductData productData,
+ Map<String, Product> regularProducts,
+ Map<String, Product> promotionProducts,
+ Map<String, Integer> regularStocks,
+ Map<String, Integer> promotionStocks) {
+ Product product = new Product(productData.name(), productData.price(), productData.promotion());
+
+ if (productData.promotion().equals(REGULAR)) {
+ regularProducts.put(productData.name(), product);
+ regularStocks.put(productData.name(), productData.quantity());
+ return;
+ }
+
+ regularProducts.computeIfAbsent(productData.name(), n -> new Product(n, productData.price(), REGULAR));
+ regularStocks.putIfAbsent(productData.name(), 0);
+ promotionProducts.put(productData.name(), product);
+ promotionStocks.put(productData.name(), productData.quantity());
+ }
+
+ private void processPromotion(BufferedReader br, Map<String, Promotion> promotions) throws IOException {
+ br.readLine(); // 헤더 생략
+ String line;
+ while ((line = br.readLine()) != null) {
+ Promotion promotion = parsePromotion(line);
+ promotions.put(promotion.getName(), promotion);
+ }
+ }
+
+ private Promotion parsePromotion(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int buy = Integer.parseInt(data[1]);
+ int get = Integer.parseInt(data[2]);
+ LocalDate startDate = LocalDate.parse(data[3]);
+ LocalDate endDate = LocalDate.parse(data[4]);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | 저는 공백도 하나의 컨벤션이라고 생각합니다. 한 번 로직을 분리후, 줄내림으로 가독성을 향상해 보는 건 어떨까요!? |
@@ -0,0 +1,14 @@
+package store.constant;
+
+public class ReceiptLabels {
+ public static final String HEADER = "\n==============W 편의점================";
+ public static final String GIFT_HEADER = "=============증\t정===============";
+ public static final String FOOTER = "====================================";
+ public static final String TOTAL_LABEL = "총구매액";
+ public static final String EVENT_DISCOUNT_LABEL = "행사할인";
+ public static final String MEMBERSHIP_DISCOUNT_LABEL = "멤버십할인";
+ public static final String FINAL_AMOUNT_LABEL = "내실돈";
+ public static final String PRODUCT_NAME = "상품명";
+ public static final String COUNT = "수량";
+ public static final String PRICE = "금액";
+}
\ No newline at end of file | Java | 저도 이 부분이 가장 큰 고민인데, Enum을 활용할 수 있지만 매번 .getMessage() 메서드 사용으로 로직이 복잡해지는 느낌이 있습니다. 하지만, 그래도 타입을 보장하기 때문에 Enum 사용을 권장한다고 합니다. 이에 대한 의견을 듣고 싶습니다. |
@@ -0,0 +1,118 @@
+package store.controller;
+
+import store.Message.ErrorMessage;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.model.service.StoreService;
+import store.model.service.ReceiptCalculationService;
+import store.util.StringParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.util.List;
+import java.util.Map;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+ private final ReceiptCalculationService receiptCalculationService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService, ReceiptCalculationService receiptCalculationService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ this.receiptCalculationService = receiptCalculationService;
+ }
+
+ public void run() {
+ do {
+ initializeView();
+ Map<String, Integer> shoppingCart = askPurchase();
+ List<ShoppingCartCheck> shoppingCartChecks = processShoppingCart(shoppingCart);
+ boolean isMembership = processMembership();
+
+ ReceiptTotals totals = receiptCalculationService.calculateTotals(shoppingCartChecks, isMembership);
+ outputView.printReceipt(shoppingCartChecks, totals);
+
+ storeService.reduceProductStocks(shoppingCartChecks);
+ } while (askAdditionalPurchase());
+ }
+
+ private void initializeView() {
+ outputView.printHelloMessage();
+ outputView.printProducts(storeService.getAllProductDtos());
+ }
+
+ private Map<String, Integer> askPurchase() {
+ while (true) {
+ try {
+ String item = inputView.readItem();
+ Map<String, Integer> shoppingCart = StringParser.parseToMap(item);
+ storeService.checkStock(shoppingCart);
+ return shoppingCart;
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private List<ShoppingCartCheck> processShoppingCart(Map<String, Integer> shoppingCart) {
+ List<ShoppingCartCheck> shoppingCartChecks = storeService.checkShoppingCart(shoppingCart);
+ shoppingCartChecks.forEach(this::processPromotionForItem);
+ return shoppingCartChecks;
+ }
+
+ private void processPromotionForItem(ShoppingCartCheck item) {
+ while (item.isCanReceiveAdditionalFree()) {
+ String decision = inputView.readPromotionDecision(item.getProductName());
+ if (decision.equals("Y")) {
+ item.acceptFree();
+ return;
+ }
+ if (decision.equals("N")) {
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+
+ while (item.isActivePromotion() && item.getFullPriceCount() > 0) {
+ String decision = inputView.readFullPriceDecision(item.getProductName(), item.getFullPriceCount());
+ if (decision.equals("Y")) {
+ return;
+ }
+ if (decision.equals("N")) {
+ item.rejectFullPrice();
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean processMembership() {
+ while (true) {
+ String decision = inputView.readMembershipDecision();
+ if (decision.equals("Y")) {
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean askAdditionalPurchase() {
+ while (true) {
+ String decision = inputView.readAdditionalPurchaseDecision();
+ if (decision.equals("Y")) {
+ System.out.println();
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | 매번 Y || N 구분하기 보다는 input에서 boolean 값으로 판별에서 넘겨주는 건 어떨까요!? |
@@ -0,0 +1,27 @@
+package store.util;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class StringParser {
+
+ private StringParser() {
+ }
+
+ public static Map<String, Integer> parseToMap(String input) {
+ Map<String, Integer> result = new HashMap<>();
+
+ Stream.of(input.split(","))
+ .forEach(item -> {
+ item = item.replaceAll("[\\[\\]]", "");
+ String[] nameAndQuantity = item.split("-");
+ if (nameAndQuantity.length != 2) {
+ throw new IllegalArgumentException("상품명과 수량을 정확히 입력해 주세요.");
+ }
+ result.put(nameAndQuantity[0], Integer.valueOf(nameAndQuantity[1]));
+ });
+
+ return result;
+ }
+}
\ No newline at end of file | Java | 2번째 값에 숫자가 아닌 문자가 올 경우 에러 처리를 못하지 않나용!? |
@@ -0,0 +1,34 @@
+package store.model.domain;
+
+import store.constant.ProductType;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private final String promotion;
+
+ public Product(String name, int price, String promotion) {
+ this.name = name;
+ this.price = price;
+ this.promotion = promotion;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public String getPromotion() {
+ return promotion;
+ }
+
+ public ProductType isPromotion() {
+ if (promotion.equals("null")) {
+ return ProductType.REGULAR;
+ }
+ return ProductType.PROMOTION;
+ }
+} | Java | "null" 도 상수로 분리해 프로모션이 없을 때 라는 명칭을 가진 이름을 명시하는 게 좋을 거 같습니다. |
@@ -0,0 +1,47 @@
+package store.model.service;
+
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.constant.Discounts;
+
+import java.util.List;
+
+public class ReceiptCalculationService {
+
+ public ReceiptTotals calculateTotals(List<ShoppingCartCheck> shoppingCartChecks, boolean isMembership) {
+ ReceiptTotals totals = new ReceiptTotals();
+
+ for (ShoppingCartCheck dto : shoppingCartChecks) {
+ int price = dto.getProductPrice() * dto.getRequestCount();
+ totals.totalCount += dto.getRequestCount();
+ totals.totalPrice += price;
+ totals.regularPrice += dto.getRegularCount() * dto.getProductPrice();
+ }
+
+ totals.giftPrice = calculateGiftDiscount(shoppingCartChecks);
+ totals.membershipPrice = calculateMembershipDiscount(totals.regularPrice, isMembership);
+
+ return totals;
+ }
+
+ private int calculateGiftDiscount(List<ShoppingCartCheck> shoppingCartChecks) {
+ int giftPrice = 0;
+ for (ShoppingCartCheck dto : shoppingCartChecks) {
+ if (dto.getFreeCount() > 0 && dto.isActivePromotion()) {
+ giftPrice -= dto.getProductPrice() * dto.getFreeCount();
+ }
+ }
+ return giftPrice;
+ }
+
+ private int calculateMembershipDiscount(int regularPrice, boolean isMembership) {
+ if (isMembership) {
+ double discountPrice = regularPrice * -Discounts.MEMBERSHIP_DISCOUNT_RATE;
+ if (Math.abs(discountPrice) > Discounts.MAX_MEMBERSHIP_DISCOUNT) {
+ return -Discounts.MAX_MEMBERSHIP_DISCOUNT;
+ }
+ return (int) discountPrice;
+ }
+ return 0;
+ }
+}
\ No newline at end of file | Java | 이 부분도 메서드를 분리해 인덴트를 감소시킬 수 있을 거 같아요! |
@@ -1,7 +1,27 @@
package store;
+import camp.nextstep.edu.missionutils.Console;
+import store.controller.StoreController;
+import store.model.repository.ProductRepository;
+import store.model.repository.PromotionRepository;
+import store.model.service.ReceiptCalculationService;
+import store.model.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ ProductRepository productRepository = new ProductRepository();
+ PromotionRepository promotionRepository = new PromotionRepository();
+
+ StoreService storeService = new StoreService(productRepository, promotionRepository);
+ ReceiptCalculationService receiptCalculationService = new ReceiptCalculationService();
+
+ InputView inputView = new InputView();
+ OutputView outputView = new OutputView();
+ StoreController storeController = new StoreController(inputView, outputView, storeService, receiptCalculationService);
+
+ storeController.run();
+ Console.close();
}
} | Java | 의존성 주입 받는 부분이 꽤 많아서 복잡도가 조금 높아 보이는데 이에 대해 어떻게 생각하시나요? |
@@ -0,0 +1,24 @@
+package store.Message;
+
+public enum ErrorMessage {
+
+ INVALID_FORMAT("올바르지 않은 형식으로 입력했습니다."),
+ NON_EXISTENT_PRODUCT("존재하지 않는 상품입니다."),
+ EXCEEDS_STOCK("재고 수량을 초과하여 구매할 수 없습니다."),
+ GENERIC_ERROR("잘못된 입력입니다."),
+ FILE_ERROR("잘못된 데이터 파일입니다:");
+
+ private final String message;
+
+ ErrorMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return String.format("[ERROR] %s 다시 입력해 주세요.", message);
+ }
+
+ public String getMessage(String detail) {
+ return String.format("[ERROR] %s : %s", message, detail);
+ }
+}
\ No newline at end of file | Java | [ERROR] 와 "다시 입력해 주세요." 도 상수 처리하는 것이 좋아 보입니다! |
@@ -0,0 +1,122 @@
+package store.config;
+
+import store.model.domain.Product;
+import store.constant.ProductType;
+import store.model.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class DataInitializer {
+ public static final String REGULAR = "null";
+
+ private static DataInitializer instance;
+
+ private DataInitializer() {
+ }
+
+ public static DataInitializer getInstance() {
+ if (instance == null) {
+ instance = new DataInitializer();
+ }
+ return instance;
+ }
+
+ public ProductsData loadProducts(String filePath) throws IOException {
+ Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processProduct(br, info, stock);
+ }
+
+ return new ProductsData(info, stock);
+ }
+
+ public Map<String, Promotion> loadPromotions(String filePath) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processPromotion(br, promotions);
+ }
+
+ return promotions;
+ }
+
+ private BufferedReader readFile(String filePath) throws IOException {
+ return new BufferedReader(new FileReader(filePath));
+ }
+
+ private void processProduct(BufferedReader br,
+ Map<ProductType, Map<String, Product>> info,
+ Map<ProductType, Map<String, Integer>> stock) throws IOException {
+ Map<String, Product> regularProducts = new LinkedHashMap<>();
+ Map<String, Product> promotionProducts = new LinkedHashMap<>();
+ Map<String, Integer> regularStocks = new HashMap<>();
+ Map<String, Integer> promotionStocks = new HashMap<>();
+
+ br.readLine(); // 헤더 생략
+ String line;
+ while ((line = br.readLine()) != null) {
+ ProductData productData = parseProduct(line);
+ addProduct(productData, regularProducts, promotionProducts, regularStocks, promotionStocks);
+ }
+
+ info.put(ProductType.REGULAR, regularProducts);
+ info.put(ProductType.PROMOTION, promotionProducts);
+ stock.put(ProductType.REGULAR, regularStocks);
+ stock.put(ProductType.PROMOTION, promotionStocks);
+ }
+
+ private ProductData parseProduct(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int price = Integer.parseInt(data[1]);
+ int quantity = Integer.parseInt(data[2]);
+ String promotion = data[3];
+ return new ProductData(name, price, quantity, promotion);
+ }
+
+ private void addProduct(ProductData productData,
+ Map<String, Product> regularProducts,
+ Map<String, Product> promotionProducts,
+ Map<String, Integer> regularStocks,
+ Map<String, Integer> promotionStocks) {
+ Product product = new Product(productData.name(), productData.price(), productData.promotion());
+
+ if (productData.promotion().equals(REGULAR)) {
+ regularProducts.put(productData.name(), product);
+ regularStocks.put(productData.name(), productData.quantity());
+ return;
+ }
+
+ regularProducts.computeIfAbsent(productData.name(), n -> new Product(n, productData.price(), REGULAR));
+ regularStocks.putIfAbsent(productData.name(), 0);
+ promotionProducts.put(productData.name(), product);
+ promotionStocks.put(productData.name(), productData.quantity());
+ }
+
+ private void processPromotion(BufferedReader br, Map<String, Promotion> promotions) throws IOException {
+ br.readLine(); // 헤더 생략
+ String line;
+ while ((line = br.readLine()) != null) {
+ Promotion promotion = parsePromotion(line);
+ promotions.put(promotion.getName(), promotion);
+ }
+ }
+
+ private Promotion parsePromotion(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int buy = Integer.parseInt(data[1]);
+ int get = Integer.parseInt(data[2]);
+ LocalDate startDate = LocalDate.parse(data[3]);
+ LocalDate endDate = LocalDate.parse(data[4]);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | 이 반점도 상수 처리 하면 좋을 것 같아요! |
@@ -0,0 +1,8 @@
+package store.config;
+
+public record ProductData(String name,
+ int price,
+ int quantity,
+ String promotion) {
+}
+ | Java | record 사용하신 점 인상 깊습니다 :) 저도 IntelliJ에서 record 사용을 추천해서 변환하려다가 부작용이 있을까봐 시도하지 않았거든요, 혹시 record를 사용하면 좋은 장점같은 것을 말씀해주실 수 있을까요? |
@@ -0,0 +1,9 @@
+package store.constant;
+
+public class InputMessages {
+ public static final String PURCHASE_PROMPT_MESSAGE = "\n구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])";
+ public static final String MEMBERSHIP_PROMPT_MESSAGE = "\n멤버십 할인을 받으시겠습니까? (Y/N)";
+ public static final String ADDITIONAL_PURCHASE_PROMPT_MESSAGE = "\n감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)";
+ public static final String ADDITIONAL_FREE_PROMPT_MESSAGE = "\n현재 %s은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)%n";
+ public static final String REGULAR_PRICE_PROMPT_MESSAGE = "\n현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)%n";
+} | Java | 어떤 것은 개행 문자가 \n 이고, 어떤 것은 %n 인것에 이유가 있나요? %n으로 통일했으면 좋겠다는 의견입니다 :) |
@@ -0,0 +1,14 @@
+package store.constant;
+
+public class ReceiptLabels {
+ public static final String HEADER = "\n==============W 편의점================";
+ public static final String GIFT_HEADER = "=============증\t정===============";
+ public static final String FOOTER = "====================================";
+ public static final String TOTAL_LABEL = "총구매액";
+ public static final String EVENT_DISCOUNT_LABEL = "행사할인";
+ public static final String MEMBERSHIP_DISCOUNT_LABEL = "멤버십할인";
+ public static final String FINAL_AMOUNT_LABEL = "내실돈";
+ public static final String PRODUCT_NAME = "상품명";
+ public static final String COUNT = "수량";
+ public static final String PRICE = "금액";
+}
\ No newline at end of file | Java | 저도 매번 .getMessage() 를 사용하는 것이 약간 복잡하게 느껴지더라고요.. 이에 대한 해결책이 있다면 공유받고 싶습니다! |
@@ -0,0 +1,18 @@
+package store.constant;
+
+public enum FileConfig {
+ FILE_HEADER(0),
+ PROMOTION_HEADER_SIZE(5),
+ PRODUCT_HEADER_SIZE(4),
+ ;
+
+ private final int value;
+
+ FileConfig(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+} | Java | 파일 이름도 여기에 정의가 되면 좋을 것 같습니다. |
@@ -0,0 +1,23 @@
+package store.controller;
+
+import java.util.List;
+import store.dto.request.ProductInputDto;
+import store.dto.request.PromotionTypeInputDto;
+import store.model.product.PromotionTypeManager;
+import store.model.product.ProductManager;
+
+public class ProductController {
+ private final FileInputHandler fileInputHandler;
+
+ public ProductController() {
+ this.fileInputHandler = new FileInputHandler();
+ }
+
+ public ProductManager initialize() {
+ List<PromotionTypeInputDto> promotionTypeInputDtos = fileInputHandler.getPromotions();
+ PromotionTypeManager promotionTypeManager = new PromotionTypeManager(promotionTypeInputDtos);
+
+ List<ProductInputDto> productInputDtos = fileInputHandler.getProducts();
+ return new ProductManager(promotionTypeManager, productInputDtos);
+ }
+} | Java | 해당 클래스 `ProductController` 는 컨트롤러보다 '서비스'에 가깝다고 봅니다.
initialize 메소드를 보면 파일 읽기 -> Entity 생성 -> Entity 반환 입니다.
흐름을 보았을 때는 컨트롤러 개념과 살짝 거리가 있어보이는데, 컨트롤러로 구현하시신 이유가 있나요? |
@@ -0,0 +1,4 @@
+package store.dto.request;
+
+public record OrderItemInputDto(String productName, int orderQuantity) {
+} | Java | 검증하는 로직도 DTO에 추가하면 좋을 것 같아요~! |
@@ -0,0 +1,7 @@
+package store.exception;
+
+public class ExceptionUtils {
+ public static void throwIllegalArgumentException(ExceptionMessage exceptionMessage) {
+ throw new IllegalArgumentException(exceptionMessage.getMessage());
+ }
+} | Java | 저도 이렇게 한적이 있는데요, 이렇게 하면 최초 에러 발생지가 `ExceptionUtils`가 되어버려서 발생한 예외를 추천하는데 있어 불필요한 예러 전파 단계가 추가 됩니다. 그래서 저는 커스텀 예외를 만들어서 처리하였습니다! |
@@ -0,0 +1,101 @@
+package store.model.order;
+
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import store.dto.request.OrderItemInputDto;
+import store.exception.ExceptionMessage;
+import store.exception.ExceptionUtils;
+import store.model.product.Product;
+import store.model.product.ProductManager;
+import store.model.product.Stock;
+
+public class Order {
+ private final ProductManager productManager;
+ private final List<OrderItem> orderItems = new ArrayList<>();
+ private final LocalDate orderDate;
+
+ public Order(ProductManager productManager, List<OrderItemInputDto> orderItemInputsDto,
+ LocalDate orderDate) {
+ this.productManager = productManager;
+ this.orderDate = orderDate;
+ List<OrderItemInputDto> mergeOrderItemsInput = mergeDuplicateProducts(orderItemInputsDto);
+ for (OrderItemInputDto orderItemInputDto : mergeOrderItemsInput) {
+ createOrderItem(orderItemInputDto.productName(), orderItemInputDto.orderQuantity());
+ }
+ }
+
+ public List<OrderItem> getOrderItems() {
+ return List.copyOf(orderItems);
+ }
+
+ public List<OrderItem> findOrderItemByProductName(String productName) {
+ return orderItems.stream()
+ .filter(orderItem -> orderItem.getProductName().equals(productName))
+ .toList();
+ }
+
+ public void removeOrderItem(OrderItem orderItem) {
+ orderItems.remove(orderItem);
+ }
+
+ private List<OrderItemInputDto> mergeDuplicateProducts(List<OrderItemInputDto> orderItemInputsDto) {
+ Map<String, Integer> mergedProducts = new HashMap<>();
+ for (OrderItemInputDto item : orderItemInputsDto) {
+ mergedProducts.merge(item.productName(), item.orderQuantity(), Integer::sum);
+ }
+ return mergedProducts.entrySet().stream()
+ .map(entry -> new OrderItemInputDto(entry.getKey(), entry.getValue()))
+ .collect(Collectors.toList());
+ }
+
+ private void createOrderItem(String productName, int orderQuantity) {
+ validateProductExistsInStore(productName);
+ validateOrderQuantity(productName, orderQuantity);
+ List<Stock> productStocks = productManager.findStocksByProductName(productName);
+ int remainingQuantity = orderQuantity;
+ for (Stock stock : productStocks) {
+ if (remainingQuantity == 0) {
+ return;
+ }
+ remainingQuantity = createOrderAndUpdateStock(stock, remainingQuantity);
+ }
+ }
+
+ private int createOrderAndUpdateStock(Stock productStock, int remainingQuantity) {
+ if (productStock.getQuantity() <= 0) {
+ return remainingQuantity;
+ }
+ return calculateQuantityAndcreateOrderItem(productStock, remainingQuantity);
+ }
+
+ private int calculateQuantityAndcreateOrderItem(Stock productStock, int remainingQuantity) {
+ if (remainingQuantity <= productStock.getQuantity()) {
+ orderItems.add(new OrderItem(productStock.getProduct(), remainingQuantity));
+ productStock.reduceQuantity(remainingQuantity);
+ return 0;
+ }
+ orderItems.add(new OrderItem(productStock.getProduct(), productStock.getQuantity()));
+ remainingQuantity -= productStock.getQuantity();
+ productStock.reduceQuantity(productStock.getQuantity());
+ return remainingQuantity;
+ }
+
+ private void validateOrderQuantity(String productName, int orderQuantity) {
+ int productTotalQuantity = productManager.getProductTotalQuantity(productName);
+ if (productTotalQuantity < orderQuantity) {
+ ExceptionUtils.throwIllegalArgumentException(ExceptionMessage.INVALID_ORDER_ITEM_QUANTITY);
+ }
+ }
+
+ private void validateProductExistsInStore(String productName) {
+ List<Product> matchingProductsInStore = productManager.findMatchingProducts(productName);
+ if (matchingProductsInStore == null || matchingProductsInStore.isEmpty()) {
+ ExceptionUtils.throwIllegalArgumentException(ExceptionMessage.INVALID_ORDER_PRODUCT);
+ }
+ }
+}
+ | Java | 해당 메서드 이름은 사용자가 주문한 내용(상품이름, 수량)를 통해 `OrderItem`이란 entity로 만드는 작업이라고 생각하였으나, 재고를 수정하는 로직이 들어있는 메소드로 보입니다. 메소드 명을 더 직관적으로 하면 이해하기 더 편할 것 같습니다..!👍
그리고, 만약 `productStocks`에 조회한 모든 `Stock`들을 for문으로 순차적으로 접근하여 사용자가 구입하고자 하는 수량만큼 감소시키는 것 같습니다. 이 부분에서 궁금한 부분은 다음과 같습니다.
1. 프로모션 상품의 재고부터 감소시키는가.
2. 프로모션 상품의 재고를 수정할 때, 프로모션 기간인지 확인하고 재고를 감소시키는가.
3. 모든 `Stock`들에 접근하여 수량을 수정하였으나 for문이 끝났음에도 `remainingQuantity`의 값이 0보다 클 경우가 있는가. |
@@ -0,0 +1,4 @@
+package store.dto.response;
+
+public record PromotionBenefitResultDto(String productName, int promotionBenefitQuantity) {
+} | Java | requestDTO와 responseDTO 패키지를 나눠주신 게 가독성이 좋은 것 같습니다.👍 |
@@ -0,0 +1,129 @@
+package store.model.product;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import store.dto.request.ProductInputDto;
+import store.exception.ExceptionMessage;
+import store.exception.ExceptionUtils;
+
+public class ProductManager {
+ private final PromotionTypeManager promotionTypeManager;
+ private final List<Stock> stocks = new ArrayList<>();
+
+ public ProductManager(PromotionTypeManager promotionTypeManager, List<ProductInputDto> productInputDtos) {
+ this.promotionTypeManager = promotionTypeManager;
+ addProductStock(productInputDtos);
+ addRegularProductsIfOnlyPromotions();
+ }
+
+ public List<Stock> getStocks() {
+ return List.copyOf(stocks);
+ }
+
+ public List<Product> findMatchingProducts(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .map(Stock::getProduct)
+ .toList();
+ }
+
+ public int getProductTotalQuantity(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .mapToInt(Stock::getQuantity)
+ .sum();
+ }
+
+ public int getPromotionProductQuantity(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .filter(stock -> stock.isPromotionStock())
+ .mapToInt(Stock::getQuantity)
+ .sum();
+ }
+
+ public List<Stock> findStocksByProductName(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .sorted()
+ .toList();
+ }
+
+ private void addProductStock(List<ProductInputDto> productsInputDto) {
+ if (productsInputDto == null) {
+ ExceptionUtils.throwIllegalArgumentException(ExceptionMessage.NULL_VALUE_ERROR);
+ }
+ for (ProductInputDto productInput : productsInputDto) {
+ processProductInput(productInput);
+ }
+ }
+
+ private void processProductInput(ProductInputDto productInput) {
+ Optional<PromotionType> matchingPromotionType = promotionTypeManager.getValidPromotionType(
+ productInput.promotion());
+ List<Product> matchingProducts = findMatchingProducts(productInput.name());
+
+ if (matchingProducts.isEmpty()) {
+ createProductAndStock(productInput, matchingPromotionType);
+ return;
+ }
+ handleExistingProducts(productInput, matchingProducts, matchingPromotionType);
+ }
+
+ private void handleExistingProducts(ProductInputDto productInput, List<Product> matchingProducts,
+ Optional<PromotionType> matchingPromotionType) {
+ ProductManagerValidator.validateProductPrice(productInput.price(), matchingProducts);
+
+ if (promotionTypeManager.isPromotionTypeMatched(productInput.name(), productInput.promotion(),
+ matchingProducts)) {
+ addStockQuantity(productInput);
+ return;
+ }
+ ProductManagerValidator.validateProductVariety(matchingProducts, productInput.promotion());
+ createProductAndStock(productInput, matchingPromotionType);
+ }
+
+ private void addStockQuantity(ProductInputDto productInput) {
+ List<Stock> samePromotionStocks = stocks.stream()
+ .filter(stock -> stock.getProduct().isSamePromotionType(productInput.name(), productInput.promotion()))
+ .toList();
+ samePromotionStocks.getFirst().addQuantity(productInput.quantity());
+ }
+
+ private void createProductAndStock(ProductInputDto productInput, Optional<PromotionType> matchingPromotionType) {
+ Product product = new Product(productInput.name(), productInput.price(),
+ matchingPromotionType.orElse(null));
+ stocks.add(new Stock(product, productInput.quantity()));
+ }
+
+ private void addRegularProductsIfOnlyPromotions() {
+ stocks.stream()
+ .collect(Collectors.groupingBy(stock -> stock.getProduct().getName()))
+ .values()
+ .stream()
+ .filter(stockList -> hasPromotionOnly(stockList) && !hasRegularProduct(stockList))
+ .forEach(stockList -> {
+ Product regularProduct = createRegularProductFromFirstPromotion(stockList);
+ stocks.add(new Stock(regularProduct, 0));
+ });
+ }
+
+ private boolean hasPromotionOnly(List<Stock> stockList) {
+ return stockList.stream().anyMatch(stock -> stock.getProduct().getPromotionType().isPresent());
+ }
+
+ private boolean hasRegularProduct(List<Stock> stockList) {
+ return stockList.stream().anyMatch(stock -> stock.getProduct().getPromotionType().isEmpty());
+ }
+
+ private Product createRegularProductFromFirstPromotion(List<Stock> stockList) {
+ return stockList.stream()
+ .filter(stock -> stock.getProduct().getPromotionType().isPresent())
+ .findFirst()
+ .map(stock -> new Product(stock.getProduct().getName(), stock.getProduct().getPrice(), null))
+ .orElseThrow(() -> new IllegalStateException(ExceptionMessage.NULL_VALUE_ERROR.getMessage()));
+ }
+} | Java | get을 계속 해오면서 Promotion에 직접적인 의존을 하고있지 않은 ProductManager에서 결국 Promotion 관련된 기능을 수행하게 됐습니다. ProductManager와 연관된 객체와만 대화할 수 있도록 하면 좋을 것 같습니다. |
@@ -0,0 +1,129 @@
+package store.model.product;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import store.dto.request.ProductInputDto;
+import store.exception.ExceptionMessage;
+import store.exception.ExceptionUtils;
+
+public class ProductManager {
+ private final PromotionTypeManager promotionTypeManager;
+ private final List<Stock> stocks = new ArrayList<>();
+
+ public ProductManager(PromotionTypeManager promotionTypeManager, List<ProductInputDto> productInputDtos) {
+ this.promotionTypeManager = promotionTypeManager;
+ addProductStock(productInputDtos);
+ addRegularProductsIfOnlyPromotions();
+ }
+
+ public List<Stock> getStocks() {
+ return List.copyOf(stocks);
+ }
+
+ public List<Product> findMatchingProducts(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .map(Stock::getProduct)
+ .toList();
+ }
+
+ public int getProductTotalQuantity(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .mapToInt(Stock::getQuantity)
+ .sum();
+ }
+
+ public int getPromotionProductQuantity(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .filter(stock -> stock.isPromotionStock())
+ .mapToInt(Stock::getQuantity)
+ .sum();
+ }
+
+ public List<Stock> findStocksByProductName(String productName) {
+ return stocks.stream()
+ .filter(stock -> stock.isNameEqual(productName))
+ .sorted()
+ .toList();
+ }
+
+ private void addProductStock(List<ProductInputDto> productsInputDto) {
+ if (productsInputDto == null) {
+ ExceptionUtils.throwIllegalArgumentException(ExceptionMessage.NULL_VALUE_ERROR);
+ }
+ for (ProductInputDto productInput : productsInputDto) {
+ processProductInput(productInput);
+ }
+ }
+
+ private void processProductInput(ProductInputDto productInput) {
+ Optional<PromotionType> matchingPromotionType = promotionTypeManager.getValidPromotionType(
+ productInput.promotion());
+ List<Product> matchingProducts = findMatchingProducts(productInput.name());
+
+ if (matchingProducts.isEmpty()) {
+ createProductAndStock(productInput, matchingPromotionType);
+ return;
+ }
+ handleExistingProducts(productInput, matchingProducts, matchingPromotionType);
+ }
+
+ private void handleExistingProducts(ProductInputDto productInput, List<Product> matchingProducts,
+ Optional<PromotionType> matchingPromotionType) {
+ ProductManagerValidator.validateProductPrice(productInput.price(), matchingProducts);
+
+ if (promotionTypeManager.isPromotionTypeMatched(productInput.name(), productInput.promotion(),
+ matchingProducts)) {
+ addStockQuantity(productInput);
+ return;
+ }
+ ProductManagerValidator.validateProductVariety(matchingProducts, productInput.promotion());
+ createProductAndStock(productInput, matchingPromotionType);
+ }
+
+ private void addStockQuantity(ProductInputDto productInput) {
+ List<Stock> samePromotionStocks = stocks.stream()
+ .filter(stock -> stock.getProduct().isSamePromotionType(productInput.name(), productInput.promotion()))
+ .toList();
+ samePromotionStocks.getFirst().addQuantity(productInput.quantity());
+ }
+
+ private void createProductAndStock(ProductInputDto productInput, Optional<PromotionType> matchingPromotionType) {
+ Product product = new Product(productInput.name(), productInput.price(),
+ matchingPromotionType.orElse(null));
+ stocks.add(new Stock(product, productInput.quantity()));
+ }
+
+ private void addRegularProductsIfOnlyPromotions() {
+ stocks.stream()
+ .collect(Collectors.groupingBy(stock -> stock.getProduct().getName()))
+ .values()
+ .stream()
+ .filter(stockList -> hasPromotionOnly(stockList) && !hasRegularProduct(stockList))
+ .forEach(stockList -> {
+ Product regularProduct = createRegularProductFromFirstPromotion(stockList);
+ stocks.add(new Stock(regularProduct, 0));
+ });
+ }
+
+ private boolean hasPromotionOnly(List<Stock> stockList) {
+ return stockList.stream().anyMatch(stock -> stock.getProduct().getPromotionType().isPresent());
+ }
+
+ private boolean hasRegularProduct(List<Stock> stockList) {
+ return stockList.stream().anyMatch(stock -> stock.getProduct().getPromotionType().isEmpty());
+ }
+
+ private Product createRegularProductFromFirstPromotion(List<Stock> stockList) {
+ return stockList.stream()
+ .filter(stock -> stock.getProduct().getPromotionType().isPresent())
+ .findFirst()
+ .map(stock -> new Product(stock.getProduct().getName(), stock.getProduct().getPrice(), null))
+ .orElseThrow(() -> new IllegalStateException(ExceptionMessage.NULL_VALUE_ERROR.getMessage()));
+ }
+} | Java | PromotionManager가 따로 있는데도 불구하고 ProductManager에서 프로모션 조건을 처리하고 재고를 관리하고있는 것 같습니다. 책임을 좀 더 명확히 분리해본다면 어떨까요? |
@@ -0,0 +1,113 @@
+package store.model.order;
+
+import java.time.LocalDate;
+import java.util.List;
+import store.model.product.ProductManager;
+import store.model.product.PromotionType;
+
+public class Promotion {
+ private final ProductManager productManager;
+ private final PromotionType promotionType;
+ private final List<OrderItem> applicableOrderItems;
+ private int totalBonusQuantity;
+ private int remainingQuantity;
+ private int additionalReceivable;
+ private int benefitQuantity;
+ private boolean canReceiveMorePromotion;
+
+ public Promotion(ProductManager productManager, List<OrderItem> applicableOrderItems, LocalDate orderDate) {
+ this.productManager = productManager;
+ this.promotionType = findPromotionType(applicableOrderItems);
+ this.applicableOrderItems = applicableOrderItems;
+ if (isPromotionValid(orderDate)) {
+ applyPromotion();
+ }
+ }
+
+ public int getTotalBonusQuantity() {
+ return totalBonusQuantity;
+ }
+
+ public int getRemainingQuantity() {
+ return remainingQuantity;
+ }
+
+ public int getAdditionalReceivable() {
+ return additionalReceivable;
+ }
+
+ public int getBenefitQuantity() {
+ return benefitQuantity;
+ }
+
+ public boolean isCanReceiveMorePromotion() {
+ return canReceiveMorePromotion;
+ }
+
+ private PromotionType findPromotionType(List<OrderItem> applicableOrderItems) {
+ return applicableOrderItems.stream()
+ .filter(orderItem -> orderItem.getPromotionType().isPresent())
+ .map(orderItem -> orderItem.getPromotionType().get())
+ .findFirst()
+ .orElse(null);
+ }
+
+ private boolean isPromotionValid(LocalDate orderDate) {
+ return promotionType != null &&
+ !orderDate.isBefore(promotionType.getStartDate()) &&
+ !orderDate.isAfter(promotionType.getEndDate());
+ }
+
+ private void applyPromotion() {
+ int promotionProductQuantity = getPromotionProductQuantity();
+ int promotionUnit = promotionType.getBuy() + promotionType.getGet();
+
+ totalBonusQuantity = calculateTotalPromotionQuantity(promotionUnit, promotionProductQuantity);
+ remainingQuantity = calculateRemainingQuantity(totalBonusQuantity);
+ benefitQuantity = totalBonusQuantity / promotionUnit;
+
+ if (remainingQuantity > 0) {
+ calculateAdditionalReceivable(remainingQuantity);
+ }
+ canReceiveMorePromotion = canReceivePromotion(remainingQuantity);
+ }
+
+ private void calculateAdditionalReceivable(int remainingQuantity) {
+ if (remainingQuantity >= promotionType.getBuy()) {
+ additionalReceivable = promotionType.getGet() - (remainingQuantity - promotionType.getBuy());
+ if (additionalReceivable < 0) {
+ additionalReceivable = 0;
+ }
+ return;
+ }
+ additionalReceivable = 0;
+ }
+
+ private int calculateRemainingQuantity(int totalBonusQuantity) {
+ return Math.max(0, getTotalOrderQuantity() - totalBonusQuantity);
+ }
+
+ private boolean canReceivePromotion(int remainingQuantity) {
+ int availableStockForPromotion = productManager.getPromotionProductQuantity(
+ applicableOrderItems.get(0).getProductName());
+ return remainingQuantity >= promotionType.getBuy() && availableStockForPromotion >= promotionType.getGet();
+ }
+
+ private int getTotalOrderQuantity() {
+ return applicableOrderItems.stream()
+ .mapToInt(OrderItem::getQuantity)
+ .sum();
+ }
+
+ private int getPromotionProductQuantity() {
+ return applicableOrderItems.stream()
+ .filter(orderItem -> orderItem.getPromotionType().isPresent())
+ .mapToInt(OrderItem::getQuantity)
+ .sum();
+ }
+
+ private int calculateTotalPromotionQuantity(int promotionUnit, int promotionProductQuantity) {
+ int promotionCount = promotionProductQuantity / promotionUnit;
+ return promotionCount * promotionUnit;
+ }
+} | Java | Promotion 클래스에서 유효성 및 모든 상태와 계산 결과를 포함하고있습니다. 특히 중간계산값인 remainingQuantity, additionalRecevable과 같은 필드를 재사용하기위해서 필드가 많이 추가된 것으로 보입니다. 프로모션 상태와 계산 로직을 따로 분리하여 복잡성을 줄여보는 건 어떨까요? |
@@ -0,0 +1,113 @@
+package store.model.order;
+
+import java.time.LocalDate;
+import java.util.List;
+import store.model.product.ProductManager;
+import store.model.product.PromotionType;
+
+public class Promotion {
+ private final ProductManager productManager;
+ private final PromotionType promotionType;
+ private final List<OrderItem> applicableOrderItems;
+ private int totalBonusQuantity;
+ private int remainingQuantity;
+ private int additionalReceivable;
+ private int benefitQuantity;
+ private boolean canReceiveMorePromotion;
+
+ public Promotion(ProductManager productManager, List<OrderItem> applicableOrderItems, LocalDate orderDate) {
+ this.productManager = productManager;
+ this.promotionType = findPromotionType(applicableOrderItems);
+ this.applicableOrderItems = applicableOrderItems;
+ if (isPromotionValid(orderDate)) {
+ applyPromotion();
+ }
+ }
+
+ public int getTotalBonusQuantity() {
+ return totalBonusQuantity;
+ }
+
+ public int getRemainingQuantity() {
+ return remainingQuantity;
+ }
+
+ public int getAdditionalReceivable() {
+ return additionalReceivable;
+ }
+
+ public int getBenefitQuantity() {
+ return benefitQuantity;
+ }
+
+ public boolean isCanReceiveMorePromotion() {
+ return canReceiveMorePromotion;
+ }
+
+ private PromotionType findPromotionType(List<OrderItem> applicableOrderItems) {
+ return applicableOrderItems.stream()
+ .filter(orderItem -> orderItem.getPromotionType().isPresent())
+ .map(orderItem -> orderItem.getPromotionType().get())
+ .findFirst()
+ .orElse(null);
+ }
+
+ private boolean isPromotionValid(LocalDate orderDate) {
+ return promotionType != null &&
+ !orderDate.isBefore(promotionType.getStartDate()) &&
+ !orderDate.isAfter(promotionType.getEndDate());
+ }
+
+ private void applyPromotion() {
+ int promotionProductQuantity = getPromotionProductQuantity();
+ int promotionUnit = promotionType.getBuy() + promotionType.getGet();
+
+ totalBonusQuantity = calculateTotalPromotionQuantity(promotionUnit, promotionProductQuantity);
+ remainingQuantity = calculateRemainingQuantity(totalBonusQuantity);
+ benefitQuantity = totalBonusQuantity / promotionUnit;
+
+ if (remainingQuantity > 0) {
+ calculateAdditionalReceivable(remainingQuantity);
+ }
+ canReceiveMorePromotion = canReceivePromotion(remainingQuantity);
+ }
+
+ private void calculateAdditionalReceivable(int remainingQuantity) {
+ if (remainingQuantity >= promotionType.getBuy()) {
+ additionalReceivable = promotionType.getGet() - (remainingQuantity - promotionType.getBuy());
+ if (additionalReceivable < 0) {
+ additionalReceivable = 0;
+ }
+ return;
+ }
+ additionalReceivable = 0;
+ }
+
+ private int calculateRemainingQuantity(int totalBonusQuantity) {
+ return Math.max(0, getTotalOrderQuantity() - totalBonusQuantity);
+ }
+
+ private boolean canReceivePromotion(int remainingQuantity) {
+ int availableStockForPromotion = productManager.getPromotionProductQuantity(
+ applicableOrderItems.get(0).getProductName());
+ return remainingQuantity >= promotionType.getBuy() && availableStockForPromotion >= promotionType.getGet();
+ }
+
+ private int getTotalOrderQuantity() {
+ return applicableOrderItems.stream()
+ .mapToInt(OrderItem::getQuantity)
+ .sum();
+ }
+
+ private int getPromotionProductQuantity() {
+ return applicableOrderItems.stream()
+ .filter(orderItem -> orderItem.getPromotionType().isPresent())
+ .mapToInt(OrderItem::getQuantity)
+ .sum();
+ }
+
+ private int calculateTotalPromotionQuantity(int promotionUnit, int promotionProductQuantity) {
+ int promotionCount = promotionProductQuantity / promotionUnit;
+ return promotionCount * promotionUnit;
+ }
+} | Java | 저도 더 받을 수 있는 증정수량에 대한 변수명을 많이 고민했는데 네이밍을 잘 하신 것 같습니다..👍 |
@@ -0,0 +1,64 @@
+package store.model.order;
+
+import java.util.Objects;
+import java.util.Optional;
+import store.model.product.Product;
+import store.model.product.PromotionType;
+
+public class OrderItem implements Comparable<OrderItem> {
+ private final Product product;
+ private int quantity;
+
+ public OrderItem(Product product, int quantity) {
+ this.product = product;
+ this.quantity = quantity;
+ }
+
+ @Override
+ public int compareTo(OrderItem o) {
+ if (this.product.getPromotionType() == null && o.product.getPromotionType() != null) {
+ return 1;
+ }
+ if (this.product.getPromotionType() != null && o.product.getPromotionType() == null) {
+ return -1;
+ }
+ return 0;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ OrderItem orderItem = (OrderItem) o;
+ return quantity == orderItem.quantity && Objects.equals(product, orderItem.product);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(product, quantity);
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Product getProduct() {
+ return product;
+ }
+
+ public void addQuantity(int quantity) {
+ this.quantity += quantity;
+ }
+
+ public Optional<PromotionType> getPromotionType() {
+ return product.getPromotionType();
+ }
+
+ public String getProductName() {
+ return product.getName();
+ }
+} | Java | 와 compareTo를 통해서 프로모션상품이 먼저 정렬되도록 하셨군요? 이런 방법도 있었네요. 저는 Promotion상품인지 아닌지 구분해서 처리하도록 했는데 훨씬 더 유연한 방법인 것 같습니다. |
@@ -0,0 +1,56 @@
+package store.model.order;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import store.constant.StoreConfig;
+import store.dto.response.PromotionResultDto;
+
+public class Membership {
+ public static double calculateMembershipDiscount(Order order, List<PromotionResultDto> promotionResult) {
+ Map<String, List<OrderItem>> groupedOrderItems = groupOrderItemsByProductName(order);
+
+ long totalAmountWithoutPromotion = calculateTotalAmountWithoutPromotion(groupedOrderItems, promotionResult);
+ long totalPromotionAmount = calculateTotalPromotionAmount(order, promotionResult);
+
+ double discountRate = StoreConfig.BASIC_MEMBERSHIP.getValue() / 100.0;
+ double discountAmount = (totalAmountWithoutPromotion + totalPromotionAmount) * discountRate;
+
+ return Math.min(discountAmount, StoreConfig.BASIC_MEMBERSHIP_LIMIT.getValue());
+ }
+
+ private static Map<String, List<OrderItem>> groupOrderItemsByProductName(Order order) {
+ return order.getOrderItems().stream()
+ .collect(Collectors.groupingBy(OrderItem::getProductName));
+ }
+
+ private static long calculateTotalAmountWithoutPromotion(Map<String, List<OrderItem>> groupedOrderItems,
+ List<PromotionResultDto> promotionResult) {
+ return groupedOrderItems.entrySet().stream()
+ .filter(entry -> !isPromotionProduct(entry.getKey(), promotionResult))
+ .flatMap(entry -> entry.getValue().stream())
+ .mapToLong(orderItem -> (long) orderItem.getQuantity() * orderItem.getProduct().getPrice())
+ .sum();
+ }
+
+ private static boolean isPromotionProduct(String productName, List<PromotionResultDto> promotionResult) {
+ return promotionResult.stream()
+ .anyMatch(promotion -> promotion.productName().equals(productName) && promotion.benefitQuantity() > 0);
+ }
+
+ private static int calculateTotalPromotionAmount(Order order, List<PromotionResultDto> promotionResult) {
+ return promotionResult.stream()
+ .filter(promotion -> promotion.remainingQuantity() > 0 && promotion.benefitQuantity() > 0)
+ .mapToInt(promotion -> calculateAmountForRemainingQuantity(order, promotion))
+ .sum();
+ }
+
+ private static int calculateAmountForRemainingQuantity(Order order, PromotionResultDto promotionResultDto) {
+ return (int) order.findOrderItemByProductName(promotionResultDto.productName()).stream()
+ .mapToLong(orderItem -> {
+ int applicableQuantity = Math.min(orderItem.getQuantity(), promotionResultDto.remainingQuantity());
+ return (long) applicableQuantity * orderItem.getProduct().getPrice();
+ })
+ .sum();
+ }
+} | Java | 이부분도 quantity와 price를 통해 orderItem이 직접 totalPrice를 계산하도록 하면 좋을 것 같습니다. |
@@ -1 +1,68 @@
-# java-convenience-store-precourse
+# 편의점
+
+## 프로젝트 소개
+구매자의 할인 혜택과 재고 상황을 고려하여 최종 결제 금액을 계산하고 안내하는 결제 시스템
+- 사용자가 입력한 상품의 가격과 수량을 기반으로 최종 결제 금액을 계산한다.
+- 총구매액은 상품별 가격과 수량을 곱하여 계산하며, 프로모션 및 멤버십 할인 정책을 반영하여 최종 결제 금액을 산출한다.
+- 구매 내역과 산출한 금액 정보를 영수증으로 출력한다.
+- 영수증 출력 후 추가 구매를 진행할지 또는 종료할지를 선택할 수 있다.
+
+## 기능 구현 목록
+
+### 1. 입력 처리
+- [x] **상품 목록 및 행사 목록 파일 입력**
+ - 상품 목록과 행사 목록을 파일 입력을 통해 저장한다.
+- [x] **상품 및 수량 입력**
+ - 구매할 상품과 수량을 `[상품명-수량]` 형식으로 입력받는다.
+- [x] **무료 상품 추가 여부 입력**
+ - 프로모션 혜택을 통해 무료 상품을 받을 수 있는 경우, 상품 추가 여부를 입력받는다.
+- [x] **프로모션 재고 부족 시 일부 수량 정가 결제 여부 입력**
+ - 프로모션 재고가 부족할 경우, 프로모션 미적용 수량에 대한 일반 결제 여부를 입력받는다.
+- [x] **멤버십 할인 적용 여부 입력**
+ - 멤버십 할인 적용 여부를 입력받는다.
+- [x] **추가 구매 여부 입력**
+ - 추가 구매 여부를 입력받는다.
+
+### 2. 출력 처리
+- [x] **상품 목록 출력**
+ - 환영 메시지와 함께 현재 재고가 있는 상품 목록을 화면에 출력한다. 재고가 없는 상품은 "재고 없음"으로 표시한다.
+- [x] **프로모션 추가 상품 증정 안내 메시지 출력**
+ - 고객이 가져온 수량보다 더 많은 수량을 프로모션 혜택으로 받을 수 있는 경우, 추가 혜택 수량을 안내한다.
+- [x] **프로모션 재고 부족 시 정가 결제 안내 메시지 출력**
+ - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, 일반 결제 여부를 묻는 메시지를 출력한다.
+- [x] **멤버십 할인 적용 여부 안내 메시지 출력**
+ - 멤버십 할인을 적용할지 여부를 묻는 메시지를 출력한다.
+- [x] **영수증 출력**
+ - 구매 내역, 증정 상품, 총구매액, 행사할인, 멤버십 할인 금액, 최종 결제 금액을 보기 좋게 정렬하여 영수증으로 출력한다.
+- [x] **추가 구매 여부 안내 메시지 출력**
+ - 추가 구매를 원하는지 여부를 묻는 메시지를 출력한다.
+
+### 3. 주문 정보 관리
+- [x] **주문 정보 저장**
+ - 입력된 값을 기반으로 주문 정보를 저장한다.
+- [x] **결제 가능 여부 확인**
+ - 각 상품의 재고 수량과 구매 수량을 비교하여 결제 가능 여부를 확인한다.
+- [x] **주문 정보 수정**
+ - 무료 상품 추가 및 프로모션 미적용 상품 차감의 경우 구매 수량을 수정한다.
+
+### 4. 결제 및 재고 관리
+- [x] **재고 업데이트**
+ - 구매한 수량만큼 재고를 차감하여 재고 상태를 업데이트한다.
+- [x] **결제 정보 계산 및 저장**
+ - 결제 금액 산출을 위한 각 항목별 판매량을 계산한다.
+ - 프로모션 상품, 증정품, 일반 상품 정보와 멤버십 적용 여부를 저장한다.
+- [x] **영수증 생성**
+ - 결제 정보를 토대로 영수증 출력에 필요한 값을 계산한다.
+ - 구매 상품 내역, 증정 상품 내역, 총 수량 및 금액, 프로모션 할인 금액, 멤버십 할인 금액, 최종 결제 금액
+
+### 5. 예외 처리
+- [x] **잘못된 입력값 예외 처리**
+ - 사용자가 잘못된 값을 입력할 경우 `IllegalArgumentException`를 발생시키고, `[ERROR]`로 시작하는 에러 메시지를 출력한 후 해당 부분부터 입력을 다시 받는다.
+ - [x] 구매할 상품과 수량 형식이 올바르지 않은 경우
+ - `[ERROR] 올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.`
+ - [x] 존재하지 않는 상품을 입력한 경우
+ - `[ERROR] 존재하지 않는 상품입니다. 다시 입력해 주세요.`
+ - [x] 구매 수량이 재고 수량을 초과한 경우
+ - `[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.`
+ - [x] 기타 잘못된 입력의 경우
+ - `[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.`
\ No newline at end of file | Unknown | 요구사항을 깔끔하게 잘 나누어 둔 것 같습니다 |
@@ -1,7 +1,18 @@
package store;
+import java.io.IOException;
+import store.config.ApplicationConfig;
+import store.controller.StoreController;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ try {
+ ApplicationConfig config = new ApplicationConfig();
+ StoreController storeController = config.storeController();
+
+ storeController.run();
+ } catch (IOException e) {
+ System.out.println("resources 파일 오류 발생: " + e.getMessage());
+ }
}
} | Java | 요구사항이 [Error]로 시작하여 오류 메세지를 띄워야한다는 것이 있어 이를 추가하면 좋을 것 같습니다. |
@@ -1,7 +1,18 @@
package store;
+import java.io.IOException;
+import store.config.ApplicationConfig;
+import store.controller.StoreController;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ try {
+ ApplicationConfig config = new ApplicationConfig();
+ StoreController storeController = config.storeController();
+
+ storeController.run();
+ } catch (IOException e) {
+ System.out.println("resources 파일 오류 발생: " + e.getMessage());
+ }
}
} | Java | 파일을 읽어오는 부분에서 오류가 발생할때를 위한 try catch문이라고 생각되는데 이를 파일을 읽어오는 로직에서 따로 처리하는 것이 더 좋을 것 같습니다 |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.io.IOException;
+import store.controller.StoreController;
+import store.util.LocalDateGenerator;
+import store.util.RealLocalDateGenerator;
+import store.domain.StoreManager;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.StoreService;
+import store.util.ResourceFileReader;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ApplicationConfig {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ private final ResourceFileReader resourceFileReader;
+
+ public ApplicationConfig() throws IOException {
+ this.resourceFileReader = new ResourceFileReader(PRODUCT_FILE_PATH, PROMOTION_FILE_PATH);
+ }
+
+ public StoreController storeController() throws IOException {
+ return new StoreController(inputView(), outputView(), storeService());
+ }
+
+ public StoreService storeService() throws IOException {
+ return new StoreService(storeManager(), realLocalTimeGenerator());
+ }
+
+ public InputView inputView() {
+ return new InputView();
+ }
+
+ public OutputView outputView() {
+ return new OutputView();
+ }
+
+ public StoreManager storeManager() throws IOException {
+ return new StoreManager(productRepository(), promotionRepository());
+ }
+
+ public ProductRepository productRepository() throws IOException {
+ return new ProductRepository(resourceFileReader.readProducts());
+ }
+
+ public PromotionRepository promotionRepository() throws IOException {
+ return new PromotionRepository(resourceFileReader.readPromotions());
+ }
+
+ public LocalDateGenerator realLocalTimeGenerator() {
+ return new RealLocalDateGenerator();
+ }
+} | Java | private으로 사용해도 문제가 없을 것이라고 생각되는데 public으로 만드신 이유가 따로 있나요?? |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.io.IOException;
+import store.controller.StoreController;
+import store.util.LocalDateGenerator;
+import store.util.RealLocalDateGenerator;
+import store.domain.StoreManager;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.StoreService;
+import store.util.ResourceFileReader;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ApplicationConfig {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ private final ResourceFileReader resourceFileReader;
+
+ public ApplicationConfig() throws IOException {
+ this.resourceFileReader = new ResourceFileReader(PRODUCT_FILE_PATH, PROMOTION_FILE_PATH);
+ }
+
+ public StoreController storeController() throws IOException {
+ return new StoreController(inputView(), outputView(), storeService());
+ }
+
+ public StoreService storeService() throws IOException {
+ return new StoreService(storeManager(), realLocalTimeGenerator());
+ }
+
+ public InputView inputView() {
+ return new InputView();
+ }
+
+ public OutputView outputView() {
+ return new OutputView();
+ }
+
+ public StoreManager storeManager() throws IOException {
+ return new StoreManager(productRepository(), promotionRepository());
+ }
+
+ public ProductRepository productRepository() throws IOException {
+ return new ProductRepository(resourceFileReader.readProducts());
+ }
+
+ public PromotionRepository promotionRepository() throws IOException {
+ return new PromotionRepository(resourceFileReader.readPromotions());
+ }
+
+ public LocalDateGenerator realLocalTimeGenerator() {
+ return new RealLocalDateGenerator();
+ }
+} | Java | throws를 사용한 이유가 있을까요? file을 제외하고 크게 throw를 던질 이유가 존재하는지 만약 에러가 file을 읽어오는 과정에서만 나타난다면 file을 읽어오는 과정에서 예외를 바로 던져주지 않는지 궁금합니다. |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.io.IOException;
+import store.controller.StoreController;
+import store.util.LocalDateGenerator;
+import store.util.RealLocalDateGenerator;
+import store.domain.StoreManager;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.StoreService;
+import store.util.ResourceFileReader;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ApplicationConfig {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ private final ResourceFileReader resourceFileReader;
+
+ public ApplicationConfig() throws IOException {
+ this.resourceFileReader = new ResourceFileReader(PRODUCT_FILE_PATH, PROMOTION_FILE_PATH);
+ }
+
+ public StoreController storeController() throws IOException {
+ return new StoreController(inputView(), outputView(), storeService());
+ }
+
+ public StoreService storeService() throws IOException {
+ return new StoreService(storeManager(), realLocalTimeGenerator());
+ }
+
+ public InputView inputView() {
+ return new InputView();
+ }
+
+ public OutputView outputView() {
+ return new OutputView();
+ }
+
+ public StoreManager storeManager() throws IOException {
+ return new StoreManager(productRepository(), promotionRepository());
+ }
+
+ public ProductRepository productRepository() throws IOException {
+ return new ProductRepository(resourceFileReader.readProducts());
+ }
+
+ public PromotionRepository promotionRepository() throws IOException {
+ return new PromotionRepository(resourceFileReader.readPromotions());
+ }
+
+ public LocalDateGenerator realLocalTimeGenerator() {
+ return new RealLocalDateGenerator();
+ }
+} | Java | 저의 경우에는 throws를 사용하여 해당 메서드가 어떤 에러를 일으키는지 정리하기위해서도 많이 사용하였는데 이 경우에는 다른 이유인 것 같아 궁금합니다. |
@@ -0,0 +1,11 @@
+package store.constant;
+
+public class ErrorMessages {
+ public static final String INVALID_FORMAT_MESSAGE = "올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.";
+ public static final String INVALID_INPUT_MESSAGE = "잘못된 입력입니다. 다시 입력해 주세요.";
+ public static final String NOT_EXIST_PRODUCT_MESSAGE = "존재하지 않는 상품입니다. 다시 입력해 주세요.";
+ public static final String QUANTITY_EXCEED_MESSAGE = "재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.";
+
+ private ErrorMessages() {
+ }
+} | Java | enum클래스로 만들어 사용하는 것이 더 좋을 것같다는 생각이 드는데 어떻게 생각하시나요? |
@@ -0,0 +1,7 @@
+package store.constant;
+
+public enum OrderStatus {
+ NOT_APPLICABLE,
+ PROMOTION_AVAILABLE_ADDITIONAL_PRODUCT,
+ PROMOTION_STOCK_INSUFFICIENT,
+} | Java | 저의 경우에는 단순히 상태를 나타내는 것이 아닌 해당 상태일때 처리하는 함수도 넣었었습니다. 당장의 코드는 깔끔해졌었지만 나중에 유지보수를 생각하면 이렇게 단순히 상태를 나타내는 것이 더 좋다는 생각이 드네요 |
@@ -0,0 +1,98 @@
+package store.controller;
+
+import java.util.List;
+import store.constant.OrderStatus;
+import store.dto.OrderNotice;
+import store.dto.PurchaseInfo;
+import store.dto.Receipt;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ }
+
+ public void run() {
+ do {
+ runStore();
+ } while (wantMorePurchase());
+ }
+
+ private void runStore() {
+ outputView.printWelcomeMessage();
+ outputView.printProductInventory(storeService.getProducts());
+ enterOrderInfo();
+ checkOrders();
+ outputView.printReceipt(calculateOrders());
+ }
+
+ private void enterOrderInfo() {
+ try {
+ storeService.resetOrders();
+ List<PurchaseInfo> purchases = inputView.readPurchases();
+ storeService.applyPurchaseInfo(purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ enterOrderInfo();
+ }
+ }
+
+ private void checkOrders() {
+ while (storeService.hasNextOrder()) {
+ OrderNotice orderNotice = storeService.checkOrder();
+ OrderStatus orderStatus = orderNotice.orderStatus();
+
+ proceedOrder(orderNotice, orderStatus);
+ }
+ }
+
+ private void proceedOrder(OrderNotice orderNotice, OrderStatus orderStatus) {
+ if (orderStatus != OrderStatus.NOT_APPLICABLE) {
+ try {
+ askAndApplyUserDecision(orderNotice, orderStatus);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ askAndApplyUserDecision(orderNotice, orderStatus);
+ }
+ }
+ }
+
+ private void askAndApplyUserDecision(OrderNotice orderNotice, OrderStatus orderStatus) {
+ if (orderStatus == OrderStatus.PROMOTION_AVAILABLE_ADDITIONAL_PRODUCT) {
+ if (inputView.askAddFreeProduct(orderNotice)) {
+ storeService.modifyOrder(orderNotice.quantity());
+ }
+ }
+ if (orderStatus == OrderStatus.PROMOTION_STOCK_INSUFFICIENT) {
+ if (!inputView.askPurchaseWithoutPromotion(orderNotice)) {
+ storeService.modifyOrder(-orderNotice.quantity());
+ }
+ }
+ }
+
+ private Receipt calculateOrders() {
+ try {
+ return storeService.calculateOrders(inputView.askForMembershipDiscount());
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ return calculateOrders();
+ }
+ }
+
+ private boolean wantMorePurchase() {
+ try {
+ return inputView.askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ return wantMorePurchase();
+ }
+ }
+} | Java | do - while을 보통 사용하라고 리뷰를 남기지만 사용하는 분과 전체 로직을 한번 더 묶어 처리하는 코드를 보니 정말 깔끔하다는 생각이 들어요 |
@@ -0,0 +1,98 @@
+package store.controller;
+
+import java.util.List;
+import store.constant.OrderStatus;
+import store.dto.OrderNotice;
+import store.dto.PurchaseInfo;
+import store.dto.Receipt;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ }
+
+ public void run() {
+ do {
+ runStore();
+ } while (wantMorePurchase());
+ }
+
+ private void runStore() {
+ outputView.printWelcomeMessage();
+ outputView.printProductInventory(storeService.getProducts());
+ enterOrderInfo();
+ checkOrders();
+ outputView.printReceipt(calculateOrders());
+ }
+
+ private void enterOrderInfo() {
+ try {
+ storeService.resetOrders();
+ List<PurchaseInfo> purchases = inputView.readPurchases();
+ storeService.applyPurchaseInfo(purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ enterOrderInfo();
+ }
+ }
+
+ private void checkOrders() {
+ while (storeService.hasNextOrder()) {
+ OrderNotice orderNotice = storeService.checkOrder();
+ OrderStatus orderStatus = orderNotice.orderStatus();
+
+ proceedOrder(orderNotice, orderStatus);
+ }
+ }
+
+ private void proceedOrder(OrderNotice orderNotice, OrderStatus orderStatus) {
+ if (orderStatus != OrderStatus.NOT_APPLICABLE) {
+ try {
+ askAndApplyUserDecision(orderNotice, orderStatus);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ askAndApplyUserDecision(orderNotice, orderStatus);
+ }
+ }
+ }
+
+ private void askAndApplyUserDecision(OrderNotice orderNotice, OrderStatus orderStatus) {
+ if (orderStatus == OrderStatus.PROMOTION_AVAILABLE_ADDITIONAL_PRODUCT) {
+ if (inputView.askAddFreeProduct(orderNotice)) {
+ storeService.modifyOrder(orderNotice.quantity());
+ }
+ }
+ if (orderStatus == OrderStatus.PROMOTION_STOCK_INSUFFICIENT) {
+ if (!inputView.askPurchaseWithoutPromotion(orderNotice)) {
+ storeService.modifyOrder(-orderNotice.quantity());
+ }
+ }
+ }
+
+ private Receipt calculateOrders() {
+ try {
+ return storeService.calculateOrders(inputView.askForMembershipDiscount());
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ return calculateOrders();
+ }
+ }
+
+ private boolean wantMorePurchase() {
+ try {
+ return inputView.askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ return wantMorePurchase();
+ }
+ }
+} | Java | 만약 예외가 계속 발생할 경우 call stack이 가득차는 경우가 생길수도 있을 것 같습니다. 재귀가 아닌 반복문을 사용하여 이를 방지하는 것은 어떨까요? |
@@ -0,0 +1,98 @@
+package store.controller;
+
+import java.util.List;
+import store.constant.OrderStatus;
+import store.dto.OrderNotice;
+import store.dto.PurchaseInfo;
+import store.dto.Receipt;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ }
+
+ public void run() {
+ do {
+ runStore();
+ } while (wantMorePurchase());
+ }
+
+ private void runStore() {
+ outputView.printWelcomeMessage();
+ outputView.printProductInventory(storeService.getProducts());
+ enterOrderInfo();
+ checkOrders();
+ outputView.printReceipt(calculateOrders());
+ }
+
+ private void enterOrderInfo() {
+ try {
+ storeService.resetOrders();
+ List<PurchaseInfo> purchases = inputView.readPurchases();
+ storeService.applyPurchaseInfo(purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ enterOrderInfo();
+ }
+ }
+
+ private void checkOrders() {
+ while (storeService.hasNextOrder()) {
+ OrderNotice orderNotice = storeService.checkOrder();
+ OrderStatus orderStatus = orderNotice.orderStatus();
+
+ proceedOrder(orderNotice, orderStatus);
+ }
+ }
+
+ private void proceedOrder(OrderNotice orderNotice, OrderStatus orderStatus) {
+ if (orderStatus != OrderStatus.NOT_APPLICABLE) {
+ try {
+ askAndApplyUserDecision(orderNotice, orderStatus);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ askAndApplyUserDecision(orderNotice, orderStatus);
+ }
+ }
+ }
+
+ private void askAndApplyUserDecision(OrderNotice orderNotice, OrderStatus orderStatus) {
+ if (orderStatus == OrderStatus.PROMOTION_AVAILABLE_ADDITIONAL_PRODUCT) {
+ if (inputView.askAddFreeProduct(orderNotice)) {
+ storeService.modifyOrder(orderNotice.quantity());
+ }
+ }
+ if (orderStatus == OrderStatus.PROMOTION_STOCK_INSUFFICIENT) {
+ if (!inputView.askPurchaseWithoutPromotion(orderNotice)) {
+ storeService.modifyOrder(-orderNotice.quantity());
+ }
+ }
+ }
+
+ private Receipt calculateOrders() {
+ try {
+ return storeService.calculateOrders(inputView.askForMembershipDiscount());
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ return calculateOrders();
+ }
+ }
+
+ private boolean wantMorePurchase() {
+ try {
+ return inputView.askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ return wantMorePurchase();
+ }
+ }
+} | Java | 컨트롤러의 역할이 잘 맞는 것 같습니다. 저희가 사용했던 스프링처럼 각 요청에 따른 처리가 필요하다 생각해 Controller-Service-Repository의 경우 Controller에서의 역할이 순수 유효성검사만 있으며 책임이 너무 적다는 생각을 했는데 흐름을 관리하고 IO와 비즈니스 로직 사이에서 조율하는 역할이 너무 좋은 것 같습니다. |
@@ -0,0 +1,31 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Order {
+ private final String name;
+ private int quantity;
+ private final LocalDate creationDate;
+
+ public Order(String name, int quantity, LocalDate creationDate) {
+ this.name = name;
+ this.quantity = quantity;
+ this.creationDate = creationDate;
+ }
+
+ public void updateQuantity(int quantityDelta) {
+ quantity += quantityDelta;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public LocalDate getCreationDate() {
+ return creationDate;
+ }
+} | Java | update라고 하면 수정에 가까운 느낌이라 addQuantity가 더 적합한 메서드 이름인 것 같습니다. |
@@ -0,0 +1,76 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.dto.ProductReceipt;
+import store.dto.Receipt;
+
+public class ReceiptConverter {
+ private static final int DISCOUNT_RATE = 30;
+ private static final int PERCENT_DIVISOR = 100;
+ private static final int MAX_DISCOUNT_AMOUNT = 8000;
+
+ public Receipt convertToReceipt(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ Receipt receipt = new Receipt();
+
+ receipt.setProducts(createProductList(orderResults));
+ receipt.setFreeProducts(createFreeProductList(orderResults));
+ receipt.setTotalOriginInfo(calculateTotalOriginInfo(orderResults));
+ receipt.setTotalFreePrice(calculateTotalFreePrice(orderResults));
+ receipt.setMembershipPrice(calculateMembershipDiscount(orderResults, isMembershipDiscount));
+ receipt.setFinalPayment(receipt.getTotalOriginInfo().price() -
+ receipt.getTotalFreePrice() - receipt.getMembershipPrice());
+ return receipt;
+ }
+
+ private List<ProductReceipt> createProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> products = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ int quantity = orderResult.promotionalQuantity() + orderResult.regularQuantity();
+ int price = quantity * orderResult.price();
+ products.add(new ProductReceipt(orderResult.productName(), quantity, price));
+ }
+ return products;
+ }
+
+ private List<ProductReceipt> createFreeProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> freeProducts = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ if (orderResult.freeQuantity() > 0) {
+ freeProducts.add(new ProductReceipt(orderResult.productName(),
+ orderResult.freeQuantity(), 0));
+ }
+ }
+ return freeProducts;
+ }
+
+ private ProductReceipt calculateTotalOriginInfo(List<OrderResult> orderResults) {
+ int totalQuantity = orderResults.stream()
+ .mapToInt(order -> order.promotionalQuantity() + order.regularQuantity())
+ .sum();
+ int totalPrice = orderResults.stream()
+ .mapToInt(order -> (order.promotionalQuantity() + order.regularQuantity()) * order.price())
+ .sum();
+
+ return new ProductReceipt(null, totalQuantity, totalPrice);
+ }
+
+ private int calculateTotalFreePrice(List<OrderResult> orderResults) {
+ return orderResults.stream()
+ .mapToInt(order -> order.freeQuantity() * order.price())
+ .sum();
+ }
+
+ private int calculateMembershipDiscount(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ if (!isMembershipDiscount) {
+ return 0;
+ }
+ int totalRegularPrice = orderResults.stream()
+ .mapToInt(order -> order.regularQuantity() * order.price())
+ .sum();
+
+ return Math.min(totalRegularPrice * DISCOUNT_RATE / PERCENT_DIVISOR, MAX_DISCOUNT_AMOUNT);
+ }
+} | Java | ReceiptConverter인데 비즈니스 로직에 해당하는 부분이 들어가 있습니다. 해당 계산하는 부분을 따로 뽑아내는 것도 좋은 생각일 것 같다는 생각을 하는데 이에대해 어떻게 생각하시나요? |
@@ -0,0 +1,76 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.dto.ProductReceipt;
+import store.dto.Receipt;
+
+public class ReceiptConverter {
+ private static final int DISCOUNT_RATE = 30;
+ private static final int PERCENT_DIVISOR = 100;
+ private static final int MAX_DISCOUNT_AMOUNT = 8000;
+
+ public Receipt convertToReceipt(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ Receipt receipt = new Receipt();
+
+ receipt.setProducts(createProductList(orderResults));
+ receipt.setFreeProducts(createFreeProductList(orderResults));
+ receipt.setTotalOriginInfo(calculateTotalOriginInfo(orderResults));
+ receipt.setTotalFreePrice(calculateTotalFreePrice(orderResults));
+ receipt.setMembershipPrice(calculateMembershipDiscount(orderResults, isMembershipDiscount));
+ receipt.setFinalPayment(receipt.getTotalOriginInfo().price() -
+ receipt.getTotalFreePrice() - receipt.getMembershipPrice());
+ return receipt;
+ }
+
+ private List<ProductReceipt> createProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> products = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ int quantity = orderResult.promotionalQuantity() + orderResult.regularQuantity();
+ int price = quantity * orderResult.price();
+ products.add(new ProductReceipt(orderResult.productName(), quantity, price));
+ }
+ return products;
+ }
+
+ private List<ProductReceipt> createFreeProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> freeProducts = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ if (orderResult.freeQuantity() > 0) {
+ freeProducts.add(new ProductReceipt(orderResult.productName(),
+ orderResult.freeQuantity(), 0));
+ }
+ }
+ return freeProducts;
+ }
+
+ private ProductReceipt calculateTotalOriginInfo(List<OrderResult> orderResults) {
+ int totalQuantity = orderResults.stream()
+ .mapToInt(order -> order.promotionalQuantity() + order.regularQuantity())
+ .sum();
+ int totalPrice = orderResults.stream()
+ .mapToInt(order -> (order.promotionalQuantity() + order.regularQuantity()) * order.price())
+ .sum();
+
+ return new ProductReceipt(null, totalQuantity, totalPrice);
+ }
+
+ private int calculateTotalFreePrice(List<OrderResult> orderResults) {
+ return orderResults.stream()
+ .mapToInt(order -> order.freeQuantity() * order.price())
+ .sum();
+ }
+
+ private int calculateMembershipDiscount(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ if (!isMembershipDiscount) {
+ return 0;
+ }
+ int totalRegularPrice = orderResults.stream()
+ .mapToInt(order -> order.regularQuantity() * order.price())
+ .sum();
+
+ return Math.min(totalRegularPrice * DISCOUNT_RATE / PERCENT_DIVISOR, MAX_DISCOUNT_AMOUNT);
+ }
+} | Java | 처음에 컨버터가 왜 필요할까라는 생각을 했는데 한번 분리할 필요가 있을만큼의 로직이 들어가 있군요. 하지만 반대로 모든 계산을 컨버터에서 진행시키니 비즈니스 로직이 util에 들어간 느낌이라 느낌이 오묘합니다. |
@@ -0,0 +1,76 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.dto.ProductReceipt;
+import store.dto.Receipt;
+
+public class ReceiptConverter {
+ private static final int DISCOUNT_RATE = 30;
+ private static final int PERCENT_DIVISOR = 100;
+ private static final int MAX_DISCOUNT_AMOUNT = 8000;
+
+ public Receipt convertToReceipt(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ Receipt receipt = new Receipt();
+
+ receipt.setProducts(createProductList(orderResults));
+ receipt.setFreeProducts(createFreeProductList(orderResults));
+ receipt.setTotalOriginInfo(calculateTotalOriginInfo(orderResults));
+ receipt.setTotalFreePrice(calculateTotalFreePrice(orderResults));
+ receipt.setMembershipPrice(calculateMembershipDiscount(orderResults, isMembershipDiscount));
+ receipt.setFinalPayment(receipt.getTotalOriginInfo().price() -
+ receipt.getTotalFreePrice() - receipt.getMembershipPrice());
+ return receipt;
+ }
+
+ private List<ProductReceipt> createProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> products = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ int quantity = orderResult.promotionalQuantity() + orderResult.regularQuantity();
+ int price = quantity * orderResult.price();
+ products.add(new ProductReceipt(orderResult.productName(), quantity, price));
+ }
+ return products;
+ }
+
+ private List<ProductReceipt> createFreeProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> freeProducts = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ if (orderResult.freeQuantity() > 0) {
+ freeProducts.add(new ProductReceipt(orderResult.productName(),
+ orderResult.freeQuantity(), 0));
+ }
+ }
+ return freeProducts;
+ }
+
+ private ProductReceipt calculateTotalOriginInfo(List<OrderResult> orderResults) {
+ int totalQuantity = orderResults.stream()
+ .mapToInt(order -> order.promotionalQuantity() + order.regularQuantity())
+ .sum();
+ int totalPrice = orderResults.stream()
+ .mapToInt(order -> (order.promotionalQuantity() + order.regularQuantity()) * order.price())
+ .sum();
+
+ return new ProductReceipt(null, totalQuantity, totalPrice);
+ }
+
+ private int calculateTotalFreePrice(List<OrderResult> orderResults) {
+ return orderResults.stream()
+ .mapToInt(order -> order.freeQuantity() * order.price())
+ .sum();
+ }
+
+ private int calculateMembershipDiscount(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ if (!isMembershipDiscount) {
+ return 0;
+ }
+ int totalRegularPrice = orderResults.stream()
+ .mapToInt(order -> order.regularQuantity() * order.price())
+ .sum();
+
+ return Math.min(totalRegularPrice * DISCOUNT_RATE / PERCENT_DIVISOR, MAX_DISCOUNT_AMOUNT);
+ }
+} | Java | public이 하나고 static을 사용하지 않을 이유를 찾지 못하겠는데 혹시 static을 사용하지 않은 이유가 있을까요? |
@@ -0,0 +1,76 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.dto.ProductReceipt;
+import store.dto.Receipt;
+
+public class ReceiptConverter {
+ private static final int DISCOUNT_RATE = 30;
+ private static final int PERCENT_DIVISOR = 100;
+ private static final int MAX_DISCOUNT_AMOUNT = 8000;
+
+ public Receipt convertToReceipt(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ Receipt receipt = new Receipt();
+
+ receipt.setProducts(createProductList(orderResults));
+ receipt.setFreeProducts(createFreeProductList(orderResults));
+ receipt.setTotalOriginInfo(calculateTotalOriginInfo(orderResults));
+ receipt.setTotalFreePrice(calculateTotalFreePrice(orderResults));
+ receipt.setMembershipPrice(calculateMembershipDiscount(orderResults, isMembershipDiscount));
+ receipt.setFinalPayment(receipt.getTotalOriginInfo().price() -
+ receipt.getTotalFreePrice() - receipt.getMembershipPrice());
+ return receipt;
+ }
+
+ private List<ProductReceipt> createProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> products = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ int quantity = orderResult.promotionalQuantity() + orderResult.regularQuantity();
+ int price = quantity * orderResult.price();
+ products.add(new ProductReceipt(orderResult.productName(), quantity, price));
+ }
+ return products;
+ }
+
+ private List<ProductReceipt> createFreeProductList(List<OrderResult> orderResults) {
+ List<ProductReceipt> freeProducts = new ArrayList<>();
+
+ for (OrderResult orderResult : orderResults) {
+ if (orderResult.freeQuantity() > 0) {
+ freeProducts.add(new ProductReceipt(orderResult.productName(),
+ orderResult.freeQuantity(), 0));
+ }
+ }
+ return freeProducts;
+ }
+
+ private ProductReceipt calculateTotalOriginInfo(List<OrderResult> orderResults) {
+ int totalQuantity = orderResults.stream()
+ .mapToInt(order -> order.promotionalQuantity() + order.regularQuantity())
+ .sum();
+ int totalPrice = orderResults.stream()
+ .mapToInt(order -> (order.promotionalQuantity() + order.regularQuantity()) * order.price())
+ .sum();
+
+ return new ProductReceipt(null, totalQuantity, totalPrice);
+ }
+
+ private int calculateTotalFreePrice(List<OrderResult> orderResults) {
+ return orderResults.stream()
+ .mapToInt(order -> order.freeQuantity() * order.price())
+ .sum();
+ }
+
+ private int calculateMembershipDiscount(List<OrderResult> orderResults, boolean isMembershipDiscount) {
+ if (!isMembershipDiscount) {
+ return 0;
+ }
+ int totalRegularPrice = orderResults.stream()
+ .mapToInt(order -> order.regularQuantity() * order.price())
+ .sum();
+
+ return Math.min(totalRegularPrice * DISCOUNT_RATE / PERCENT_DIVISOR, MAX_DISCOUNT_AMOUNT);
+ }
+} | Java | 계산을 하는 부분의 느낌이 강하고 멤버십의 책임까지 있어 Membership을 분리시켜 클래스로 만들어주고 Recipt에서 추가적으로 계산하는 것은 어떤가요? |
@@ -0,0 +1,166 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.dto.PurchaseInfo;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+
+import static store.constant.ErrorMessages.NOT_EXIST_PRODUCT_MESSAGE;
+import static store.constant.ErrorMessages.QUANTITY_EXCEED_MESSAGE;
+
+public class StoreManager {
+ private final ProductRepository productRepository;
+ private final PromotionRepository promotionRepository;
+
+ public StoreManager(ProductRepository productRepository,
+ PromotionRepository promotionRepository
+ ) {
+ this.productRepository = productRepository;
+ this.promotionRepository = promotionRepository;
+ }
+
+ public List<ProductDto> getProductDtos() {
+ List<ProductDto> productDtos = new ArrayList<>();
+ List<Product> products = productRepository.findAll();
+
+ for (Product product : products) {
+ productDtos.add(convertToProductDto(product));
+ }
+ return productDtos;
+ }
+
+ public void validatePurchaseInfo(PurchaseInfo purchaseInfo) {
+ Optional<Product> promotionalProduct = productRepository.findPromotionalProduct(purchaseInfo.name());
+ Optional<Product> regularProduct = productRepository.findRegularProduct(purchaseInfo.name());
+
+ validateProductExist(promotionalProduct.orElse(null), regularProduct.orElse(null));
+ validateProductQuantity(
+ promotionalProduct.map(Product::getQuantity).orElse(0),
+ regularProduct.map(Product::getQuantity).orElse(0),
+ purchaseInfo.quantity()
+ );
+ }
+
+ public Integer isValidForAdditionalProduct(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ assert product != null;
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+ if (!canApplyPromotion(product, promotion, order)) {
+ return 0;
+ }
+ return getAdditionalProductQuantity(
+ product.getQuantity(),
+ promotion,
+ order
+ );
+ }
+
+ public Integer isStockInsufficient(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ assert product != null;
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+ if (!canApplyPromotion(product, promotion, order)) {
+ return 0;
+ }
+ int promotionalQuantity = product.getQuantity();
+ return order.getQuantity() -
+ (promotionalQuantity - (promotionalQuantity % (promotion.buy() + promotion.get())));
+ }
+
+ public List<Integer> calculateOrder(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElseThrow();
+ List<Integer> result = new ArrayList<>();
+
+ calculatePromotionalAndFreeProduct(product, order, result);
+ result.add(calculateRegularProduct(order));
+ result.add(product.getPrice());
+ return result;
+ }
+
+ private ProductDto convertToProductDto(Product product) {
+ return new ProductDto(
+ product.getName(),
+ product.getPrice(),
+ product.getQuantity(),
+ product.getPromotion()
+ );
+ }
+
+ private void validateProductExist(Product promotionalProduct, Product regularProduct) {
+ if (promotionalProduct == null && regularProduct == null) {
+ throw new IllegalArgumentException(NOT_EXIST_PRODUCT_MESSAGE);
+ }
+ }
+
+ private void validateProductQuantity(int promotionalQuantity, int regularQuantity, int purchaseQuantity) {
+ if (promotionalQuantity + regularQuantity < purchaseQuantity) {
+ throw new IllegalArgumentException(QUANTITY_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean canApplyPromotion(Product promotionalProduct, Promotion promotion, Order order) {
+ if (promotionalProduct == null || promotion == null) {
+ return false;
+ }
+ return !order.getCreationDate().isBefore(promotion.startDate()) &&
+ !order.getCreationDate().isAfter(promotion.endDate());
+ }
+
+ private Integer getAdditionalProductQuantity(int promotionalQuantity, Promotion promotion, Order order) {
+ if (promotionalQuantity >= order.getQuantity() + promotion.get() &&
+ order.getQuantity() % (promotion.buy() + promotion.get()) == promotion.buy()) {
+ return promotion.get();
+ }
+ return 0;
+ }
+
+ private void calculatePromotionalAndFreeProduct(Product product, Order order, List<Integer> result) {
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+
+ if (canApplyPromotion(product, promotion, order)) {
+ result.add(comparePromotionalProductAndOrder(product, promotion, order));
+ result.add(result.getFirst() / (promotion.buy() + promotion.get()));
+ return;
+ }
+ result.add(0);
+ result.add(0);
+ }
+
+ private Integer calculateRegularProduct(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ if (order.getQuantity() == 0 || product == null) {
+ return 0;
+ }
+ if (product.getPromotion().isEmpty()) {
+ return compareRegularProductAndOrder(product, order);
+ }
+ Product regularProduct = productRepository.findRegularProduct(order.getName()).orElse(null);
+ assert regularProduct != null;
+ return compareRegularProductAndOrder(product, order) + compareRegularProductAndOrder(regularProduct, order);
+ }
+
+ private Integer comparePromotionalProductAndOrder(Product product, Promotion promotion, Order order) {
+ if (product.getQuantity() >= order.getQuantity()) {
+ return updateProductAndOrder(product, order,
+ order.getQuantity() - (order.getQuantity() % (promotion.buy() + promotion.get())));
+ }
+ return updateProductAndOrder(product, order,
+ product.getQuantity() - (product.getQuantity() % (promotion.buy() + promotion.get())));
+ }
+
+ private Integer compareRegularProductAndOrder(Product product, Order order) {
+ if (product.getQuantity() >= order.getQuantity()) {
+ return updateProductAndOrder(product, order, order.getQuantity());
+ }
+ return updateProductAndOrder(product, order, product.getQuantity());
+ }
+
+ private Integer updateProductAndOrder(Product product, Order order, int quantityDelta) {
+ product.soldQuantity(quantityDelta);
+ order.updateQuantity(-quantityDelta);
+ return quantityDelta;
+ }
+} | Java | service 레이어의 역할을 추가적으로 StoreManager가 진행하고 있는 것 같은데 StoreManager를 추가적으로 Domain패키지에 만든 이유가 있을까요? 차라리 ProductService와 PromotionService를 만들고 상위로 StoreService를 만드는 것은 어떨까요>? |
@@ -0,0 +1,166 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.dto.PurchaseInfo;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+
+import static store.constant.ErrorMessages.NOT_EXIST_PRODUCT_MESSAGE;
+import static store.constant.ErrorMessages.QUANTITY_EXCEED_MESSAGE;
+
+public class StoreManager {
+ private final ProductRepository productRepository;
+ private final PromotionRepository promotionRepository;
+
+ public StoreManager(ProductRepository productRepository,
+ PromotionRepository promotionRepository
+ ) {
+ this.productRepository = productRepository;
+ this.promotionRepository = promotionRepository;
+ }
+
+ public List<ProductDto> getProductDtos() {
+ List<ProductDto> productDtos = new ArrayList<>();
+ List<Product> products = productRepository.findAll();
+
+ for (Product product : products) {
+ productDtos.add(convertToProductDto(product));
+ }
+ return productDtos;
+ }
+
+ public void validatePurchaseInfo(PurchaseInfo purchaseInfo) {
+ Optional<Product> promotionalProduct = productRepository.findPromotionalProduct(purchaseInfo.name());
+ Optional<Product> regularProduct = productRepository.findRegularProduct(purchaseInfo.name());
+
+ validateProductExist(promotionalProduct.orElse(null), regularProduct.orElse(null));
+ validateProductQuantity(
+ promotionalProduct.map(Product::getQuantity).orElse(0),
+ regularProduct.map(Product::getQuantity).orElse(0),
+ purchaseInfo.quantity()
+ );
+ }
+
+ public Integer isValidForAdditionalProduct(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ assert product != null;
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+ if (!canApplyPromotion(product, promotion, order)) {
+ return 0;
+ }
+ return getAdditionalProductQuantity(
+ product.getQuantity(),
+ promotion,
+ order
+ );
+ }
+
+ public Integer isStockInsufficient(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ assert product != null;
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+ if (!canApplyPromotion(product, promotion, order)) {
+ return 0;
+ }
+ int promotionalQuantity = product.getQuantity();
+ return order.getQuantity() -
+ (promotionalQuantity - (promotionalQuantity % (promotion.buy() + promotion.get())));
+ }
+
+ public List<Integer> calculateOrder(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElseThrow();
+ List<Integer> result = new ArrayList<>();
+
+ calculatePromotionalAndFreeProduct(product, order, result);
+ result.add(calculateRegularProduct(order));
+ result.add(product.getPrice());
+ return result;
+ }
+
+ private ProductDto convertToProductDto(Product product) {
+ return new ProductDto(
+ product.getName(),
+ product.getPrice(),
+ product.getQuantity(),
+ product.getPromotion()
+ );
+ }
+
+ private void validateProductExist(Product promotionalProduct, Product regularProduct) {
+ if (promotionalProduct == null && regularProduct == null) {
+ throw new IllegalArgumentException(NOT_EXIST_PRODUCT_MESSAGE);
+ }
+ }
+
+ private void validateProductQuantity(int promotionalQuantity, int regularQuantity, int purchaseQuantity) {
+ if (promotionalQuantity + regularQuantity < purchaseQuantity) {
+ throw new IllegalArgumentException(QUANTITY_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean canApplyPromotion(Product promotionalProduct, Promotion promotion, Order order) {
+ if (promotionalProduct == null || promotion == null) {
+ return false;
+ }
+ return !order.getCreationDate().isBefore(promotion.startDate()) &&
+ !order.getCreationDate().isAfter(promotion.endDate());
+ }
+
+ private Integer getAdditionalProductQuantity(int promotionalQuantity, Promotion promotion, Order order) {
+ if (promotionalQuantity >= order.getQuantity() + promotion.get() &&
+ order.getQuantity() % (promotion.buy() + promotion.get()) == promotion.buy()) {
+ return promotion.get();
+ }
+ return 0;
+ }
+
+ private void calculatePromotionalAndFreeProduct(Product product, Order order, List<Integer> result) {
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+
+ if (canApplyPromotion(product, promotion, order)) {
+ result.add(comparePromotionalProductAndOrder(product, promotion, order));
+ result.add(result.getFirst() / (promotion.buy() + promotion.get()));
+ return;
+ }
+ result.add(0);
+ result.add(0);
+ }
+
+ private Integer calculateRegularProduct(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ if (order.getQuantity() == 0 || product == null) {
+ return 0;
+ }
+ if (product.getPromotion().isEmpty()) {
+ return compareRegularProductAndOrder(product, order);
+ }
+ Product regularProduct = productRepository.findRegularProduct(order.getName()).orElse(null);
+ assert regularProduct != null;
+ return compareRegularProductAndOrder(product, order) + compareRegularProductAndOrder(regularProduct, order);
+ }
+
+ private Integer comparePromotionalProductAndOrder(Product product, Promotion promotion, Order order) {
+ if (product.getQuantity() >= order.getQuantity()) {
+ return updateProductAndOrder(product, order,
+ order.getQuantity() - (order.getQuantity() % (promotion.buy() + promotion.get())));
+ }
+ return updateProductAndOrder(product, order,
+ product.getQuantity() - (product.getQuantity() % (promotion.buy() + promotion.get())));
+ }
+
+ private Integer compareRegularProductAndOrder(Product product, Order order) {
+ if (product.getQuantity() >= order.getQuantity()) {
+ return updateProductAndOrder(product, order, order.getQuantity());
+ }
+ return updateProductAndOrder(product, order, product.getQuantity());
+ }
+
+ private Integer updateProductAndOrder(Product product, Order order, int quantityDelta) {
+ product.soldQuantity(quantityDelta);
+ order.updateQuantity(-quantityDelta);
+ return quantityDelta;
+ }
+} | Java | assert를 사용한 이유가 있나요? if와 throw를 사용하지 않은 이유가 궁금합니다! |
@@ -0,0 +1,166 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import store.dto.ProductDto;
+import store.dto.PurchaseInfo;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+
+import static store.constant.ErrorMessages.NOT_EXIST_PRODUCT_MESSAGE;
+import static store.constant.ErrorMessages.QUANTITY_EXCEED_MESSAGE;
+
+public class StoreManager {
+ private final ProductRepository productRepository;
+ private final PromotionRepository promotionRepository;
+
+ public StoreManager(ProductRepository productRepository,
+ PromotionRepository promotionRepository
+ ) {
+ this.productRepository = productRepository;
+ this.promotionRepository = promotionRepository;
+ }
+
+ public List<ProductDto> getProductDtos() {
+ List<ProductDto> productDtos = new ArrayList<>();
+ List<Product> products = productRepository.findAll();
+
+ for (Product product : products) {
+ productDtos.add(convertToProductDto(product));
+ }
+ return productDtos;
+ }
+
+ public void validatePurchaseInfo(PurchaseInfo purchaseInfo) {
+ Optional<Product> promotionalProduct = productRepository.findPromotionalProduct(purchaseInfo.name());
+ Optional<Product> regularProduct = productRepository.findRegularProduct(purchaseInfo.name());
+
+ validateProductExist(promotionalProduct.orElse(null), regularProduct.orElse(null));
+ validateProductQuantity(
+ promotionalProduct.map(Product::getQuantity).orElse(0),
+ regularProduct.map(Product::getQuantity).orElse(0),
+ purchaseInfo.quantity()
+ );
+ }
+
+ public Integer isValidForAdditionalProduct(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ assert product != null;
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+ if (!canApplyPromotion(product, promotion, order)) {
+ return 0;
+ }
+ return getAdditionalProductQuantity(
+ product.getQuantity(),
+ promotion,
+ order
+ );
+ }
+
+ public Integer isStockInsufficient(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ assert product != null;
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+ if (!canApplyPromotion(product, promotion, order)) {
+ return 0;
+ }
+ int promotionalQuantity = product.getQuantity();
+ return order.getQuantity() -
+ (promotionalQuantity - (promotionalQuantity % (promotion.buy() + promotion.get())));
+ }
+
+ public List<Integer> calculateOrder(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElseThrow();
+ List<Integer> result = new ArrayList<>();
+
+ calculatePromotionalAndFreeProduct(product, order, result);
+ result.add(calculateRegularProduct(order));
+ result.add(product.getPrice());
+ return result;
+ }
+
+ private ProductDto convertToProductDto(Product product) {
+ return new ProductDto(
+ product.getName(),
+ product.getPrice(),
+ product.getQuantity(),
+ product.getPromotion()
+ );
+ }
+
+ private void validateProductExist(Product promotionalProduct, Product regularProduct) {
+ if (promotionalProduct == null && regularProduct == null) {
+ throw new IllegalArgumentException(NOT_EXIST_PRODUCT_MESSAGE);
+ }
+ }
+
+ private void validateProductQuantity(int promotionalQuantity, int regularQuantity, int purchaseQuantity) {
+ if (promotionalQuantity + regularQuantity < purchaseQuantity) {
+ throw new IllegalArgumentException(QUANTITY_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean canApplyPromotion(Product promotionalProduct, Promotion promotion, Order order) {
+ if (promotionalProduct == null || promotion == null) {
+ return false;
+ }
+ return !order.getCreationDate().isBefore(promotion.startDate()) &&
+ !order.getCreationDate().isAfter(promotion.endDate());
+ }
+
+ private Integer getAdditionalProductQuantity(int promotionalQuantity, Promotion promotion, Order order) {
+ if (promotionalQuantity >= order.getQuantity() + promotion.get() &&
+ order.getQuantity() % (promotion.buy() + promotion.get()) == promotion.buy()) {
+ return promotion.get();
+ }
+ return 0;
+ }
+
+ private void calculatePromotionalAndFreeProduct(Product product, Order order, List<Integer> result) {
+ Promotion promotion = promotionRepository.find(product.getPromotion()).orElse(null);
+
+ if (canApplyPromotion(product, promotion, order)) {
+ result.add(comparePromotionalProductAndOrder(product, promotion, order));
+ result.add(result.getFirst() / (promotion.buy() + promotion.get()));
+ return;
+ }
+ result.add(0);
+ result.add(0);
+ }
+
+ private Integer calculateRegularProduct(Order order) {
+ Product product = productRepository.findProduct(order.getName()).orElse(null);
+ if (order.getQuantity() == 0 || product == null) {
+ return 0;
+ }
+ if (product.getPromotion().isEmpty()) {
+ return compareRegularProductAndOrder(product, order);
+ }
+ Product regularProduct = productRepository.findRegularProduct(order.getName()).orElse(null);
+ assert regularProduct != null;
+ return compareRegularProductAndOrder(product, order) + compareRegularProductAndOrder(regularProduct, order);
+ }
+
+ private Integer comparePromotionalProductAndOrder(Product product, Promotion promotion, Order order) {
+ if (product.getQuantity() >= order.getQuantity()) {
+ return updateProductAndOrder(product, order,
+ order.getQuantity() - (order.getQuantity() % (promotion.buy() + promotion.get())));
+ }
+ return updateProductAndOrder(product, order,
+ product.getQuantity() - (product.getQuantity() % (promotion.buy() + promotion.get())));
+ }
+
+ private Integer compareRegularProductAndOrder(Product product, Order order) {
+ if (product.getQuantity() >= order.getQuantity()) {
+ return updateProductAndOrder(product, order, order.getQuantity());
+ }
+ return updateProductAndOrder(product, order, product.getQuantity());
+ }
+
+ private Integer updateProductAndOrder(Product product, Order order, int quantityDelta) {
+ product.soldQuantity(quantityDelta);
+ order.updateQuantity(-quantityDelta);
+ return quantityDelta;
+ }
+} | Java | 이렇게 조건이 길어지는 경우 해당 조건을 따로 메서드로 빼내어 어떤 조건인지 메서드명으로 명시해주는 것이 좋다고 생각합니다. 2가지의 로직이라면 &&을 통해 각각의 로직을 나타내는 메서드를 작성하는 것도 좋을 것 같습니다. |
@@ -0,0 +1,69 @@
+package store.dto;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Receipt {
+ private List<ProductReceipt> products;
+ private List<ProductReceipt> freeProducts;
+ private ProductReceipt totalOriginInfo;
+ private int totalFreePrice;
+ private int membershipPrice;
+ private int finalPayment;
+
+ public Receipt() {
+ this.products = new ArrayList<>();
+ this.freeProducts = new ArrayList<>();
+ this.totalFreePrice = 0;
+ this.membershipPrice = 0;
+ this.finalPayment = 0;
+ }
+
+ public List<ProductReceipt> getProducts() {
+ return products;
+ }
+
+ public List<ProductReceipt> getFreeProducts() {
+ return freeProducts;
+ }
+
+ public ProductReceipt getTotalOriginInfo() {
+ return totalOriginInfo;
+ }
+
+ public int getTotalFreePrice() {
+ return totalFreePrice;
+ }
+
+ public int getMembershipPrice() {
+ return membershipPrice;
+ }
+
+ public int getFinalPayment() {
+ return finalPayment;
+ }
+
+ public void setProducts(List<ProductReceipt> products) {
+ this.products = products;
+ }
+
+ public void setFreeProducts(List<ProductReceipt> freeProducts) {
+ this.freeProducts = freeProducts;
+ }
+
+ public void setTotalOriginInfo(ProductReceipt totalOriginInfo) {
+ this.totalOriginInfo = totalOriginInfo;
+ }
+
+ public void setTotalFreePrice(int totalFreePrice) {
+ this.totalFreePrice = totalFreePrice;
+ }
+
+ public void setMembershipPrice(int membershipPrice) {
+ this.membershipPrice = membershipPrice;
+ }
+
+ public void setFinalPayment(int finalPayment) {
+ this.finalPayment = finalPayment;
+ }
+} | Java | Convertor에서 있었던 일들이 Receipt에 addOrder를 사용해서 주문을 추가하는 것도 좋을 것 같습니다. |
@@ -0,0 +1,47 @@
+package store.repository;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import store.domain.Product;
+
+public class ProductRepository {
+ private static final String EMPTY_STRING = "";
+
+ private final List<Product> products;
+
+ public ProductRepository(List<Product> products) {
+ this.products = new ArrayList<>(products);
+ setUp();
+ }
+
+ public List<Product> findAll() {
+ return new ArrayList<>(products);
+ }
+
+ public Optional<Product> findPromotionalProduct(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equals(name) && !product.getPromotion().isEmpty())
+ .findFirst();
+ }
+
+ public Optional<Product> findRegularProduct(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equals(name) && product.getPromotion().isEmpty())
+ .findFirst();
+ }
+
+ public Optional<Product> findProduct(String name) {
+ return findPromotionalProduct(name).or(() -> findRegularProduct(name));
+ }
+
+ private void setUp() {
+ for (int i = 0; i < products.size(); i++) {
+ Product product = products.get(i);
+
+ if (!product.getPromotion().isEmpty() && findRegularProduct(product.getName()).isEmpty()) {
+ products.add(++i, new Product(product.getName(), product.getPrice(), 0, EMPTY_STRING));
+ }
+ }
+ }
+} | Java | LinkedHashMap을 사용하면 탐색이 몹시 편해질 것 같습니다. |
@@ -0,0 +1,87 @@
+package store.service;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import store.constant.OrderStatus;
+import store.util.LocalDateGenerator;
+import store.domain.Order;
+import store.domain.ReceiptConverter;
+import store.domain.StoreManager;
+import store.dto.OrderNotice;
+import store.domain.OrderResult;
+import store.dto.ProductDto;
+import store.dto.PurchaseInfo;
+import store.dto.Receipt;
+
+public class StoreService {
+ private final StoreManager storeManager;
+ private final LocalDateGenerator timeGenerator;
+ private final List<Order> orders;
+ private Iterator<Order> orderIterator;
+ private Order currentOrder;
+
+ public StoreService(StoreManager storeManager, LocalDateGenerator timeGenerator) {
+ this.storeManager = storeManager;
+ this.timeGenerator = timeGenerator;
+ this.orders = new ArrayList<>();
+ }
+
+ public List<ProductDto> getProducts() {
+ return storeManager.getProductDtos();
+ }
+
+ public void resetOrders() {
+ orders.clear();
+ }
+
+ public void applyPurchaseInfo(List<PurchaseInfo> purchases) {
+ for (PurchaseInfo purchaseInfo : purchases) {
+ storeManager.validatePurchaseInfo(purchaseInfo);
+ orders.add(new Order(
+ purchaseInfo.name(),
+ purchaseInfo.quantity(),
+ timeGenerator.today()
+ ));
+ }
+ orderIterator = orders.iterator();
+ }
+
+ public boolean hasNextOrder() {
+ return orderIterator.hasNext();
+ }
+
+ public OrderNotice checkOrder() {
+ currentOrder = orderIterator.next();
+ return determineOrderNotice(currentOrder);
+ }
+
+ public void modifyOrder(int quantityDelta) {
+ currentOrder.updateQuantity(quantityDelta);
+ }
+
+ public Receipt calculateOrders(boolean isMembershipDiscount) {
+ List<OrderResult> orderResults = new ArrayList<>();
+ ReceiptConverter converter = new ReceiptConverter();
+
+ for (Order order : orders) {
+ List<Integer> result = storeManager.calculateOrder(order);
+ orderResults.add(new OrderResult(order.getName(), result.getFirst(),
+ result.get(1), result.get(2), result.getLast()));
+ }
+ return converter.convertToReceipt(orderResults, isMembershipDiscount);
+ }
+
+ private OrderNotice determineOrderNotice(Order order) {
+ if (storeManager.isValidForAdditionalProduct(order) != 0) {
+ return new OrderNotice(OrderStatus.PROMOTION_AVAILABLE_ADDITIONAL_PRODUCT, order.getName(),
+ storeManager.isValidForAdditionalProduct(order));
+ }
+ if (storeManager.isStockInsufficient(order) > 0) {
+ return new OrderNotice(OrderStatus.PROMOTION_STOCK_INSUFFICIENT, order.getName(),
+ storeManager.isStockInsufficient(order));
+ }
+ return new OrderNotice(OrderStatus.NOT_APPLICABLE, order.getName(),
+ storeManager.isStockInsufficient(order));
+ }
+} | Java | 클래스를 초기화하고 재사용하는 것도 좋아보입니다. 하지만 혹시 모를 예외를 위해 orderIterator와 currentOrder도 지우는 것이 좋을 것 같습니다. |
@@ -0,0 +1,87 @@
+package store.service;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import store.constant.OrderStatus;
+import store.util.LocalDateGenerator;
+import store.domain.Order;
+import store.domain.ReceiptConverter;
+import store.domain.StoreManager;
+import store.dto.OrderNotice;
+import store.domain.OrderResult;
+import store.dto.ProductDto;
+import store.dto.PurchaseInfo;
+import store.dto.Receipt;
+
+public class StoreService {
+ private final StoreManager storeManager;
+ private final LocalDateGenerator timeGenerator;
+ private final List<Order> orders;
+ private Iterator<Order> orderIterator;
+ private Order currentOrder;
+
+ public StoreService(StoreManager storeManager, LocalDateGenerator timeGenerator) {
+ this.storeManager = storeManager;
+ this.timeGenerator = timeGenerator;
+ this.orders = new ArrayList<>();
+ }
+
+ public List<ProductDto> getProducts() {
+ return storeManager.getProductDtos();
+ }
+
+ public void resetOrders() {
+ orders.clear();
+ }
+
+ public void applyPurchaseInfo(List<PurchaseInfo> purchases) {
+ for (PurchaseInfo purchaseInfo : purchases) {
+ storeManager.validatePurchaseInfo(purchaseInfo);
+ orders.add(new Order(
+ purchaseInfo.name(),
+ purchaseInfo.quantity(),
+ timeGenerator.today()
+ ));
+ }
+ orderIterator = orders.iterator();
+ }
+
+ public boolean hasNextOrder() {
+ return orderIterator.hasNext();
+ }
+
+ public OrderNotice checkOrder() {
+ currentOrder = orderIterator.next();
+ return determineOrderNotice(currentOrder);
+ }
+
+ public void modifyOrder(int quantityDelta) {
+ currentOrder.updateQuantity(quantityDelta);
+ }
+
+ public Receipt calculateOrders(boolean isMembershipDiscount) {
+ List<OrderResult> orderResults = new ArrayList<>();
+ ReceiptConverter converter = new ReceiptConverter();
+
+ for (Order order : orders) {
+ List<Integer> result = storeManager.calculateOrder(order);
+ orderResults.add(new OrderResult(order.getName(), result.getFirst(),
+ result.get(1), result.get(2), result.getLast()));
+ }
+ return converter.convertToReceipt(orderResults, isMembershipDiscount);
+ }
+
+ private OrderNotice determineOrderNotice(Order order) {
+ if (storeManager.isValidForAdditionalProduct(order) != 0) {
+ return new OrderNotice(OrderStatus.PROMOTION_AVAILABLE_ADDITIONAL_PRODUCT, order.getName(),
+ storeManager.isValidForAdditionalProduct(order));
+ }
+ if (storeManager.isStockInsufficient(order) > 0) {
+ return new OrderNotice(OrderStatus.PROMOTION_STOCK_INSUFFICIENT, order.getName(),
+ storeManager.isStockInsufficient(order));
+ }
+ return new OrderNotice(OrderStatus.NOT_APPLICABLE, order.getName(),
+ storeManager.isStockInsufficient(order));
+ }
+} | Java | 직접 Iterator를 보내지 않고 메서드와 연결해서 사용하신 모습이 생각하지 못한 부분이라 좋은 것 같습니다. |
@@ -0,0 +1,7 @@
+package store.util;
+
+import java.time.LocalDate;
+
+public interface LocalDateGenerator {
+ LocalDate today();
+} | Java | today보다는 getToday와 같이 앞에 동사가 들어가면 더 좋을 것 같습니다. |
@@ -0,0 +1,82 @@
+package store.util;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.Function;
+import store.domain.Product;
+import store.domain.Promotion;
+
+public class ResourceFileReader {
+ private static final int HEADER_LINE = 1;
+ private static final int PRICE_INDEX = 1;
+ private static final int QUANTITY_INDEX = 2;
+ private static final int PROMOTION_INDEX = 3;
+ private static final int BUY_INDEX = 1;
+ private static final int GET_INDEX = 2;
+ private static final int START_DATE_INDEX = 3;
+ private static final int END_DATE_INDEX = 4;
+ private static final String DELIMITER = ",";
+ private static final String NULL_STRING = "null";
+ private static final String EMPTY_STRING = "";
+
+ private final Path productFilePath;
+ private final Path promotionFilePath;
+
+ public ResourceFileReader(String productFilePath, String promotionFilePath) {
+ this.productFilePath = Paths.get(productFilePath);
+ this.promotionFilePath = Paths.get(promotionFilePath);
+ }
+
+ public List<Product> readProducts() throws IOException {
+ return readFile(productFilePath, this::parseProduct);
+ }
+
+ public List<Promotion> readPromotions() throws IOException {
+ return readFile(promotionFilePath, this::parsePromotion);
+ }
+
+ private <T> List<T> readFile(Path filePath, Function<String, T> parser) throws IOException {
+ try (BufferedReader reader = new BufferedReader(new FileReader(filePath.toFile()))) {
+ return reader.lines()
+ .skip(HEADER_LINE)
+ .map(parser)
+ .toList();
+ }
+ }
+
+ private Product parseProduct(String line) {
+ List<String> data = splitLine(line);
+ String name = data.getFirst();
+ int price = Integer.parseInt(data.get(PRICE_INDEX));
+ int quantity = Integer.parseInt(data.get(QUANTITY_INDEX));
+ String promotion = getPromotion(data.get(PROMOTION_INDEX));
+ return new Product(name, price, quantity, promotion);
+ }
+
+ private Promotion parsePromotion(String line) {
+ List<String> data = splitLine(line);
+ String name = data.getFirst();
+ int buy = Integer.parseInt(data.get(BUY_INDEX));
+ int get = Integer.parseInt(data.get(GET_INDEX));
+ LocalDate startDate = LocalDate.parse(data.get(START_DATE_INDEX));
+ LocalDate endDate = LocalDate.parse(data.get(END_DATE_INDEX));
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+
+ private List<String> splitLine(String line) {
+ return Arrays.stream(line.split(DELIMITER)).toList();
+ }
+
+ private String getPromotion(String promotion) {
+ if (promotion.equals(NULL_STRING)) {
+ return EMPTY_STRING;
+ }
+ return promotion;
+ }
+}
| Java | 스트림을 사용하여 편하게 넘긴 것이 저의 readLine()을 한번 쓰고 넘어간 것보다 더 깔끔한 코드인 것 같습니다 |
@@ -0,0 +1,142 @@
+package store.view;
+
+import java.util.List;
+import store.dto.ProductDto;
+import store.dto.ProductReceipt;
+import store.dto.Receipt;
+
+public class OutputView {
+ private static final String ERROR_PREFIX = "[ERROR] ";
+ private static final String WELCOME_MESSAGE = "안녕하세요. W편의점입니다.\n현재 보유하고 있는 상품입니다.";
+ private static final String PRODUCT_FORMAT = "- %s %s원 %d개 %s";
+ private static final String EMPTY_PRODUCT_FORMAT = "- %s %s원 재고 없음 %s";
+ private static final String AMOUNT_FORMAT = "%,d";
+
+ private static final String STORE_HEADER = "==============W 편의점================";
+ private static final String PROMOTION_SECTION = "=============증 정===============";
+ private static final String TOTAL_SECTION = "====================================";
+ private static final String PRODUCT_NAME_HEADER = "상품명";
+ private static final String QUANTITY_HEADER = "수량";
+ private static final String PRICE_HEADER = "금액";
+ private static final String COLUMN_TITLES = "%-16s%-10s%s";
+ private static final String PURCHASED_PRODUCT_FORMAT = "%-16s%-10d%-10s";
+ private static final String FREE_PRODUCT_FORMAT = "%-16s%-10d";
+ private static final String TOTAL_PRICE_FORMAT = "%-16s%-10d%-10s";
+ private static final String DISCOUNT_PRICE_FORMAT = "%-26s-%-10s";
+ private static final String FINAL_PAYMENT_FORMAT = "%-27s%-10s";
+
+ private static final String TOTAL_PURCHASE_LABEL = "총구매액";
+ private static final String PROMOTION_DISCOUNT_LABEL = "행사할인";
+ private static final String MEMBERSHIP_DISCOUNT_LABEL = "멤버십할인";
+ private static final String FINAL_PAYMENT_LABEL = "내실돈";
+
+ public void printWelcomeMessage() {
+ System.out.println(WELCOME_MESSAGE);
+ }
+
+ public void printErrorMessage(String errorMessage) {
+ System.out.println(ERROR_PREFIX + errorMessage);
+ }
+
+ public void printProductInventory(List<ProductDto> products) {
+ for (ProductDto product : products) {
+ System.out.println(formatProduct(product).trim());
+ }
+ }
+
+ public void printReceipt(Receipt receipt) {
+ printHeader();
+ printPurchasedProducts(receipt);
+ printFreeProducts(receipt);
+ printTotals(receipt);
+ }
+
+ private String formatProduct(ProductDto product) {
+ if (product.quantity() == 0) {
+ return String.format(EMPTY_PRODUCT_FORMAT, product.name(),
+ formatAmount(product.price()), product.promotion());
+ }
+ return String.format(PRODUCT_FORMAT, product.name(),
+ formatAmount(product.price()), product.quantity(), product.promotion());
+ }
+
+ private String formatAmount(int amount) {
+ return String.format(AMOUNT_FORMAT, amount);
+ }
+
+ private void printHeader() {
+ System.out.println(STORE_HEADER);
+ System.out.println(String.format(
+ COLUMN_TITLES,
+ PRODUCT_NAME_HEADER,
+ QUANTITY_HEADER,
+ PRICE_HEADER)
+ .trim()
+ );
+ }
+
+ private void printPurchasedProducts(Receipt receipt) {
+ for (ProductReceipt product : receipt.getProducts()) {
+ System.out.println(String.format(
+ PURCHASED_PRODUCT_FORMAT,
+ product.name(),
+ product.quantity(),
+ formatAmount(product.price()))
+ .trim()
+ );
+ }
+ }
+
+ private void printFreeProducts(Receipt receipt) {
+ System.out.println(PROMOTION_SECTION);
+ for (ProductReceipt freeProduct : receipt.getFreeProducts()) {
+ System.out.println(String.format(FREE_PRODUCT_FORMAT, freeProduct.name(),
+ freeProduct.quantity()).trim());
+ }
+ }
+
+ private void printTotals(Receipt receipt) {
+ System.out.println(TOTAL_SECTION);
+ printTotalPrice(receipt);
+ printPromotionDiscount(receipt);
+ printMembershipDiscount(receipt);
+ printFinalPayment(receipt);
+ }
+
+ private void printTotalPrice(Receipt receipt) {
+ System.out.println(String.format(
+ TOTAL_PRICE_FORMAT,
+ TOTAL_PURCHASE_LABEL,
+ receipt.getTotalOriginInfo().quantity(),
+ formatAmount(receipt.getTotalOriginInfo().price()))
+ .trim()
+ );
+ }
+
+ private void printPromotionDiscount(Receipt receipt) {
+ System.out.println(String.format(
+ DISCOUNT_PRICE_FORMAT,
+ PROMOTION_DISCOUNT_LABEL,
+ formatAmount(receipt.getTotalFreePrice()))
+ .trim()
+ );
+ }
+
+ private void printMembershipDiscount(Receipt receipt) {
+ System.out.println(String.format(
+ DISCOUNT_PRICE_FORMAT,
+ MEMBERSHIP_DISCOUNT_LABEL,
+ formatAmount(receipt.getMembershipPrice()))
+ .trim()
+ );
+ }
+
+ private void printFinalPayment(Receipt receipt) {
+ System.out.println(String.format(
+ FINAL_PAYMENT_FORMAT,
+ FINAL_PAYMENT_LABEL,
+ formatAmount(receipt.getFinalPayment()))
+ .trim()
+ );
+ }
+} | Java | 도메인을 직접 넘긴다고 봤으나 Receipt가 dto더군요. 리뷰를 하면서 Receipt가 저는 domain으로 만들었지만 사실 dto의 성향이 더 강하다고 생각하였는데 굉장히 좋은 시점인 것 같습니👍 |
@@ -1,7 +1,18 @@
package store;
+import java.io.IOException;
+import store.config.ApplicationConfig;
+import store.controller.StoreController;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ try {
+ ApplicationConfig config = new ApplicationConfig();
+ StoreController storeController = config.storeController();
+
+ storeController.run();
+ } catch (IOException e) {
+ System.out.println("resources 파일 오류 발생: " + e.getMessage());
+ }
}
} | Java | 초기 설정값인 상품, 프로모션에서 생긴 오류는 요구사항에 해당하지 않는다고 생각해 다르게 출력했습니다.
다시 생각해보면 일관된 포멧으로 오류 메시지를 출력하는게 더 깔끔할 것 같네요..!
try catch를 통해 초기 설정 오류의 경우 프로그램 자체가 종료되도록 구현하다 보니 main문에 작성하게 되었습니다! |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.io.IOException;
+import store.controller.StoreController;
+import store.util.LocalDateGenerator;
+import store.util.RealLocalDateGenerator;
+import store.domain.StoreManager;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.StoreService;
+import store.util.ResourceFileReader;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ApplicationConfig {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ private final ResourceFileReader resourceFileReader;
+
+ public ApplicationConfig() throws IOException {
+ this.resourceFileReader = new ResourceFileReader(PRODUCT_FILE_PATH, PROMOTION_FILE_PATH);
+ }
+
+ public StoreController storeController() throws IOException {
+ return new StoreController(inputView(), outputView(), storeService());
+ }
+
+ public StoreService storeService() throws IOException {
+ return new StoreService(storeManager(), realLocalTimeGenerator());
+ }
+
+ public InputView inputView() {
+ return new InputView();
+ }
+
+ public OutputView outputView() {
+ return new OutputView();
+ }
+
+ public StoreManager storeManager() throws IOException {
+ return new StoreManager(productRepository(), promotionRepository());
+ }
+
+ public ProductRepository productRepository() throws IOException {
+ return new ProductRepository(resourceFileReader.readProducts());
+ }
+
+ public PromotionRepository promotionRepository() throws IOException {
+ return new PromotionRepository(resourceFileReader.readPromotions());
+ }
+
+ public LocalDateGenerator realLocalTimeGenerator() {
+ return new RealLocalDateGenerator();
+ }
+} | Java | 놓친 부분이 있었네요. 지적해주셔서 감사합니다!
상위 메서드 호출로 전체적인 설정을 해주는 클래스라서 말씀해주신대로 private으로 사용하는 것이 더 적절한 것 같아요. |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.io.IOException;
+import store.controller.StoreController;
+import store.util.LocalDateGenerator;
+import store.util.RealLocalDateGenerator;
+import store.domain.StoreManager;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.StoreService;
+import store.util.ResourceFileReader;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ApplicationConfig {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ private final ResourceFileReader resourceFileReader;
+
+ public ApplicationConfig() throws IOException {
+ this.resourceFileReader = new ResourceFileReader(PRODUCT_FILE_PATH, PROMOTION_FILE_PATH);
+ }
+
+ public StoreController storeController() throws IOException {
+ return new StoreController(inputView(), outputView(), storeService());
+ }
+
+ public StoreService storeService() throws IOException {
+ return new StoreService(storeManager(), realLocalTimeGenerator());
+ }
+
+ public InputView inputView() {
+ return new InputView();
+ }
+
+ public OutputView outputView() {
+ return new OutputView();
+ }
+
+ public StoreManager storeManager() throws IOException {
+ return new StoreManager(productRepository(), promotionRepository());
+ }
+
+ public ProductRepository productRepository() throws IOException {
+ return new ProductRepository(resourceFileReader.readProducts());
+ }
+
+ public PromotionRepository promotionRepository() throws IOException {
+ return new PromotionRepository(resourceFileReader.readPromotions());
+ }
+
+ public LocalDateGenerator realLocalTimeGenerator() {
+ return new RealLocalDateGenerator();
+ }
+} | Java | 자바 컴파일러가 throws를 사용하지 않는 경우 컴파일 에러를 띄워 명시적으로 사용했습니다!
다시 생각해보니 파일 입력에 관한 것을 main에서 따로 처리하면 덕지덕지 throws를 사용하지 않았어도 될 문제였던 것 같아요. |
@@ -0,0 +1,50 @@
+package baseball.controller;
+
+import baseball.config.Score;
+import baseball.dto.SubmitAnswerDto.SubmitAnswerInputDto;
+import baseball.dto.SubmitAnswerDto.SubmitAnswerOutputDto;
+import baseball.service.GameService;
+import baseball.view.OutputView;
+import java.util.List;
+import java.util.Map;
+
+public class GameController {
+ private final GameService gameService;
+
+ public GameController(GameService gameService) {
+ this.gameService = gameService;
+ }
+
+ public void run() {
+ do {
+ this.startGame();
+ } while (RetryInputUtil.getCommand() != 2);
+ }
+
+ private void startGame() {
+ OutputView.printStartMessage();
+ while (true) {
+ if (this.startTurn()) {
+ break;
+ }
+ }
+ OutputView.printEndMessage();
+ }
+
+ private boolean startTurn() {
+ try {
+ List<Integer> userNumbers = RetryInputUtil.getUserNumbers();
+ SubmitAnswerOutputDto submitAnswerOutputDto = this.gameService.submitAnswer(
+ new SubmitAnswerInputDto(userNumbers));
+
+ Map<Score, Integer> score = submitAnswerOutputDto.score();
+ OutputView.printResult(score);
+
+ return score.get(Score.STRIKE) == 3;
+
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ return false;
+ }
+ }
+}
\ No newline at end of file | Java | 의미가 있는 숫자이니 상수로 관리해도 좋을 것 같습니다. |
@@ -0,0 +1,50 @@
+package baseball.controller;
+
+import baseball.config.Score;
+import baseball.dto.SubmitAnswerDto.SubmitAnswerInputDto;
+import baseball.dto.SubmitAnswerDto.SubmitAnswerOutputDto;
+import baseball.service.GameService;
+import baseball.view.OutputView;
+import java.util.List;
+import java.util.Map;
+
+public class GameController {
+ private final GameService gameService;
+
+ public GameController(GameService gameService) {
+ this.gameService = gameService;
+ }
+
+ public void run() {
+ do {
+ this.startGame();
+ } while (RetryInputUtil.getCommand() != 2);
+ }
+
+ private void startGame() {
+ OutputView.printStartMessage();
+ while (true) {
+ if (this.startTurn()) {
+ break;
+ }
+ }
+ OutputView.printEndMessage();
+ }
+
+ private boolean startTurn() {
+ try {
+ List<Integer> userNumbers = RetryInputUtil.getUserNumbers();
+ SubmitAnswerOutputDto submitAnswerOutputDto = this.gameService.submitAnswer(
+ new SubmitAnswerInputDto(userNumbers));
+
+ Map<Score, Integer> score = submitAnswerOutputDto.score();
+ OutputView.printResult(score);
+
+ return score.get(Score.STRIKE) == 3;
+
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ return false;
+ }
+ }
+}
\ No newline at end of file | Java | 반복 로직을 잘 짜시는 것 같습니다 👍 |
@@ -0,0 +1,21 @@
+package baseball.config;
+
+public enum Config {
+ MIN_RANDOM_NUMBER(1),
+ MAX_RANDOM_NUMBER(9),
+ NUMBER_OF_RANDOM_NUMBER(3);
+
+ private final Object value;
+
+ Config(Object value) {
+ this.value = value;
+ }
+
+ public int getInt() {
+ return (int) value;
+ }
+
+ public String getString() {
+ return (String) value;
+ }
+} | Java | Object 대신 제네릭을 사용하면 안정성을 더욱 높일 수 있을 것 같습니다. |
@@ -0,0 +1,25 @@
+package baseball.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class InputParser {
+
+ public static int parseInt(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("문자를 입력할 수 없습니다.", e);
+ }
+ }
+
+ public static List<Integer> parseIntList(String input) {
+ List<Integer> list = new ArrayList<>();
+ for (int i = 0; i < input.length(); i++) {
+ list.add(parseInt(input.substring(i, i + 1)));
+ }
+
+ return list;
+ }
+
+} | Java | 원천 예외를 넘기신 것 좋아요 🙂 |
@@ -0,0 +1,25 @@
+package baseball.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class InputParser {
+
+ public static int parseInt(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("문자를 입력할 수 없습니다.", e);
+ }
+ }
+
+ public static List<Integer> parseIntList(String input) {
+ List<Integer> list = new ArrayList<>();
+ for (int i = 0; i < input.length(); i++) {
+ list.add(parseInt(input.substring(i, i + 1)));
+ }
+
+ return list;
+ }
+
+} | Java | 프리코스 피드백에도 나와있듯, 변수명으로 자료형을 쓰는 것은 지양하는 것이 어떨까요? |
@@ -0,0 +1,50 @@
+package baseball.controller;
+
+import baseball.config.Score;
+import baseball.dto.SubmitAnswerDto.SubmitAnswerInputDto;
+import baseball.dto.SubmitAnswerDto.SubmitAnswerOutputDto;
+import baseball.service.GameService;
+import baseball.view.OutputView;
+import java.util.List;
+import java.util.Map;
+
+public class GameController {
+ private final GameService gameService;
+
+ public GameController(GameService gameService) {
+ this.gameService = gameService;
+ }
+
+ public void run() {
+ do {
+ this.startGame();
+ } while (RetryInputUtil.getCommand() != 2);
+ }
+
+ private void startGame() {
+ OutputView.printStartMessage();
+ while (true) {
+ if (this.startTurn()) {
+ break;
+ }
+ }
+ OutputView.printEndMessage();
+ }
+
+ private boolean startTurn() {
+ try {
+ List<Integer> userNumbers = RetryInputUtil.getUserNumbers();
+ SubmitAnswerOutputDto submitAnswerOutputDto = this.gameService.submitAnswer(
+ new SubmitAnswerInputDto(userNumbers));
+
+ Map<Score, Integer> score = submitAnswerOutputDto.score();
+ OutputView.printResult(score);
+
+ return score.get(Score.STRIKE) == 3;
+
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ return false;
+ }
+ }
+}
\ No newline at end of file | Java | 피드백 감사합니다! |
@@ -0,0 +1,21 @@
+package baseball.config;
+
+public enum Config {
+ MIN_RANDOM_NUMBER(1),
+ MAX_RANDOM_NUMBER(9),
+ NUMBER_OF_RANDOM_NUMBER(3);
+
+ private final Object value;
+
+ Config(Object value) {
+ this.value = value;
+ }
+
+ public int getInt() {
+ return (int) value;
+ }
+
+ public String getString() {
+ return (String) value;
+ }
+} | Java | 오..! 다음부터 제네릭을 사용하는편이 더 좋을 것 같습니다! 감사합니다!!! |
@@ -0,0 +1,25 @@
+package baseball.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class InputParser {
+
+ public static int parseInt(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("문자를 입력할 수 없습니다.", e);
+ }
+ }
+
+ public static List<Integer> parseIntList(String input) {
+ List<Integer> list = new ArrayList<>();
+ for (int i = 0; i < input.length(); i++) {
+ list.add(parseInt(input.substring(i, i + 1)));
+ }
+
+ return list;
+ }
+
+} | Java | 으앗...!! 무의식적으로 사용한 것 같습니다.. 반성하겠습니다. 감사합니다! |
@@ -0,0 +1,21 @@
+package baseball.config;
+
+public enum Config {
+ MIN_RANDOM_NUMBER(1),
+ MAX_RANDOM_NUMBER(9),
+ NUMBER_OF_RANDOM_NUMBER(3);
+
+ private final Object value;
+
+ Config(Object value) {
+ this.value = value;
+ }
+
+ public int getInt() {
+ return (int) value;
+ }
+
+ public String getString() {
+ return (String) value;
+ }
+} | Java | 그런데 제네릭을 어떻게 사용해야 할까요? 방법이 있을까요? |
@@ -7,6 +7,7 @@ export interface ReviewInfo {
userprofile?: string;
date: Date;
isMyReview?: boolean;
+ isMyWritten?: boolean;
eventId?: number;
eventType?: string;
} | TypeScript | 내가 작성한 리뷰 탭에서 샤용할 때는 <Review reviewInfo={{...data, isMyWritten: true}}> 이렇게 isMyWritten를 true로 추가해주시면 됩니다. |
@@ -4,12 +4,23 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import ReviewContent from "./ReviewContent";
import ArrowDown from "@/assets/images/icons/arrow_down.svg";
+import MenuCircle from "@/assets/images/icons/menu-circle.svg";
+import Dropdown from "@/components/common/Dropdown";
import { type ReviewInfoProps } from "@/types/review";
+import { type RatingStyle } from "@/types/review";
export default function Review({ reviewInfo }: ReviewInfoProps) {
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
+ const reviewTextStyle: RatingStyle = {
+ 0: "text-purple-200",
+ 1: "text-blue-200",
+ 2: "text-orange-200",
+ };
+
+ const ratingArr = ["그냥그래요", "괜찮아요", "추천해요"];
+
//클릭 시 모임 상세로 이동
const handleClickReview = () => {
if (reviewInfo.isMyReview) {
@@ -19,18 +30,58 @@ export default function Review({ reviewInfo }: ReviewInfoProps) {
return;
};
+ const handleClickModify = () => {
+ alert("리뷰 수정입니다.");
+ };
+
+ const handleClickDelete = () => {
+ alert("리뷰 삭제입니다.");
+ };
+
const handleClickDetail = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
setIsOpen((prev) => !prev);
};
return (
<div className='rounded-[12px] bg-gray-900 p-4' onClick={handleClickReview}>
<div className='relative'>
- <button onClick={handleClickDetail} className='absolute right-0 top-0'>
- <ArrowDown
- className={`size-6 text-gray-200 ${isOpen ? "rotate-180" : ""}`}
- />
- </button>
+ <div className='flex justify-between'>
+ <span
+ className={`inline-block px-2 py-[3px] text-caption-normal ${reviewTextStyle[reviewInfo.rating]} rounded-[20px] bg-gray-700`}
+ >
+ {ratingArr[reviewInfo.rating]}
+ </span>
+ {reviewInfo.isMyWritten ? (
+ <Dropdown
+ content={[
+ {
+ label: "수정하기",
+ value: "modify",
+ onClick: () => handleClickModify(),
+ },
+ {
+ label: "삭제하기",
+ value: "delete",
+ onClick: () => handleClickDelete(),
+ },
+ ]}
+ isReview={true}
+ >
+ <div className='z-10 cursor-pointer'>
+ <MenuCircle />
+ </div>
+ </Dropdown>
+ ) : (
+ <button
+ onClick={handleClickDetail}
+ className='absolute right-0 top-0'
+ >
+ <ArrowDown
+ className={`size-6 text-gray-200 ${isOpen ? "rotate-180" : ""}`}
+ />
+ </button>
+ )}
+ </div>
<ReviewContent reviewContent={reviewInfo} isOpen={isOpen} />
</div>
</div> | Unknown | 수정, 삭제는 일단 임시로 alert을 띄워놨습니다 |
@@ -4,12 +4,23 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import ReviewContent from "./ReviewContent";
import ArrowDown from "@/assets/images/icons/arrow_down.svg";
+import MenuCircle from "@/assets/images/icons/menu-circle.svg";
+import Dropdown from "@/components/common/Dropdown";
import { type ReviewInfoProps } from "@/types/review";
+import { type RatingStyle } from "@/types/review";
export default function Review({ reviewInfo }: ReviewInfoProps) {
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
+ const reviewTextStyle: RatingStyle = {
+ 0: "text-purple-200",
+ 1: "text-blue-200",
+ 2: "text-orange-200",
+ };
+
+ const ratingArr = ["그냥그래요", "괜찮아요", "추천해요"];
+
//클릭 시 모임 상세로 이동
const handleClickReview = () => {
if (reviewInfo.isMyReview) {
@@ -19,18 +30,58 @@ export default function Review({ reviewInfo }: ReviewInfoProps) {
return;
};
+ const handleClickModify = () => {
+ alert("리뷰 수정입니다.");
+ };
+
+ const handleClickDelete = () => {
+ alert("리뷰 삭제입니다.");
+ };
+
const handleClickDetail = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
setIsOpen((prev) => !prev);
};
return (
<div className='rounded-[12px] bg-gray-900 p-4' onClick={handleClickReview}>
<div className='relative'>
- <button onClick={handleClickDetail} className='absolute right-0 top-0'>
- <ArrowDown
- className={`size-6 text-gray-200 ${isOpen ? "rotate-180" : ""}`}
- />
- </button>
+ <div className='flex justify-between'>
+ <span
+ className={`inline-block px-2 py-[3px] text-caption-normal ${reviewTextStyle[reviewInfo.rating]} rounded-[20px] bg-gray-700`}
+ >
+ {ratingArr[reviewInfo.rating]}
+ </span>
+ {reviewInfo.isMyWritten ? (
+ <Dropdown
+ content={[
+ {
+ label: "수정하기",
+ value: "modify",
+ onClick: () => handleClickModify(),
+ },
+ {
+ label: "삭제하기",
+ value: "delete",
+ onClick: () => handleClickDelete(),
+ },
+ ]}
+ isReview={true}
+ >
+ <div className='z-10 cursor-pointer'>
+ <MenuCircle />
+ </div>
+ </Dropdown>
+ ) : (
+ <button
+ onClick={handleClickDetail}
+ className='absolute right-0 top-0'
+ >
+ <ArrowDown
+ className={`size-6 text-gray-200 ${isOpen ? "rotate-180" : ""}`}
+ />
+ </button>
+ )}
+ </div>
<ReviewContent reviewContent={reviewInfo} isOpen={isOpen} />
</div>
</div> | Unknown | 적용해보니 드롭다운이 열리면서 이벤트버블링으로 `handleClickReview`이 실행되고 바로 상세페이지로 넘어가는 것 같아요.
이 부분 처리가 필요할 것 같습니당
(`Dropdown`을 `div`로 한 번 감싸서 `e.stopPropagation()`등으로 막는다거나..) |
@@ -0,0 +1,18 @@
+package store;
+
+import store.controller.ProductController;
+import store.controller.PromotionController;
+
+public class StoreApplication {
+ private final ProductController productController;
+ private final PromotionController promotionController;
+
+ public StoreApplication(ProductController productController, PromotionController promotionController) {
+ this.productController = productController;
+ this.promotionController = promotionController;
+ }
+
+ public void run() {
+ productController.handlePurchase();
+ }
+} | Java | promotionController가 주입되었지만 사용하지 않고 있습니다! |
@@ -0,0 +1,58 @@
+package store.config;
+
+import store.StoreApplication;
+import store.controller.ProductController;
+import store.controller.PromotionController;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Promotions;
+import store.service.ProductService;
+import store.service.PromotionService;
+import store.utils.ProductLoader;
+import store.utils.PromotionLoader;
+import store.validator.InputConfirmValidator;
+import store.validator.InputConfirmValidatorImpl;
+import store.validator.InputPurchaseValidator;
+import store.validator.InputPurchaseValidatorImpl;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.util.List;
+
+public class AppConfig {
+ public ProductController productController() {
+ return new ProductController(productService(), outputView(), inputView(), inputPurchaseValidator(),promotionController(),inputConfirmValidator());
+ }
+ public ProductService productService() {
+ return new ProductService(productList());
+ }
+ public StoreApplication storeApplication() {
+ return new StoreApplication(productController(),promotionController());
+ }
+ public List<Product> productList() {
+ return ProductLoader.loadProductsFromFile("src/main/resources/products.md");
+ }
+
+ public List<Promotion> promotionsList() {
+ return PromotionLoader.loadPromotionsFromFile("src/main/resources/promotions.md");
+ }
+ public PromotionController promotionController() {
+ return new PromotionController(promotionService(), outputView(), inputView(),inputConfirmValidator());
+ }
+ public PromotionService promotionService() {
+ return new PromotionService(new Promotions(promotionsList()));
+ }
+
+ public OutputView outputView() {
+ return new OutputView();
+ }
+ public InputView inputView() {
+ return new InputView();
+ }
+ public InputPurchaseValidator inputPurchaseValidator() {
+ return new InputPurchaseValidatorImpl();
+ }
+ public InputConfirmValidator inputConfirmValidator(){
+ return new InputConfirmValidatorImpl();
+ }
+} | Java | StoreApplication을 Appconfig에 넣었어도 되지 않을까 생각이 듭니다! |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | 들여쓰기 depth가 3이라서 함수로 분리하는게 좋을 거 같습니다! |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | item을 하나씩 처리하지않고 서비스에서 위임하여 처리 후에 예외가 나면 재처리하는 방식이 좋았을 거 같습니다! |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | 들여쓰기가 잘못됐네요! |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | stock은 product 객체가 처리되도록 하는 방식을 고려하는게 좋을 거 같습니다! |
@@ -0,0 +1,71 @@
+package store.controller;
+
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.service.PromotionService;
+import store.validator.InputConfirmValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+
+public class PromotionController {
+ private final PromotionService promotionService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public PromotionController(PromotionService promotionService, OutputView outputView, InputView inputView, InputConfirmValidator inputConfirmValidator) {
+ this.promotionService = promotionService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+ Promotion validatePromotionDate(String promotionName) {
+ return promotionService.validatePromotionDate(promotionName);
+ }
+
+ public PromotionResult applyPromotionLogic(String productName, int quantity, String promotionName, BigDecimal productPrice, int promoStock) {
+ Promotion applicablePromotion = promotionService.findPromotionName(promotionName);
+ if (applicablePromotion == null) {
+ return new PromotionResult(quantity, 0, BigDecimal.ZERO, BigDecimal.ZERO); // 유효하지 않은 경우, 수량 그대로 반환
+ }
+
+ int buyQuantity = applicablePromotion.getBuyQuantity();
+ int getQuantity = applicablePromotion.getGetQuantity();
+ int freeQuantity = 0;
+ int promotionQuantity = quantity;
+
+ if(promoStock<=quantity){
+ promotionQuantity = promoStock;
+ }
+
+ BigDecimal discountAmount = BigDecimal.ZERO;
+ if (shouldOfferFreeProduct(buyQuantity, quantity) && promoStock>quantity) {
+ String confirmInput = inputView.confirmPromotionAdditionMessage(productName,getQuantity);
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ quantity=++promotionQuantity;
+ }
+ }
+ if(buyQuantity==2){
+ freeQuantity = promotionQuantity/3;
+ }
+ if (buyQuantity==1){
+ freeQuantity = promotionQuantity/2;
+ }
+ discountAmount=productPrice.multiply(BigDecimal.valueOf(freeQuantity));
+ return new PromotionResult(quantity, freeQuantity, discountAmount, discountAmount.multiply(BigDecimal.valueOf(++buyQuantity)));
+ }
+
+
+ private boolean shouldOfferFreeProduct(int buyQuantity, int quantity) {
+ if (buyQuantity == 2 && (quantity % 3) == 2) {
+ return true; // 탄산 2+1의 경우
+ }
+ if (buyQuantity == 1 && (quantity % 2) == 1) {
+ return true; // MD추천 상품, 반짝할인의 경우
+ }
+ return false;
+ }
+} | Java | output view가 사용되지 않는데 제거해도 좋을 거 같습니다! |
@@ -0,0 +1,23 @@
+package store.validator;
+
+import store.utils.ErrorMessages;
+
+public class InputPurchaseValidatorImpl implements InputPurchaseValidator{
+
+ private static final String PRODUCT_INPUT_REGEX = "\\[.*-\\d+\\]";
+
+ @Override
+ public void validateProductInput(String input) {
+ if (!input.matches(PRODUCT_INPUT_REGEX)) {
+ throw new IllegalArgumentException(ErrorMessages.INVALID_INPUT_MESSAGE);
+ }
+ }
+
+ @Override
+ public void validateQuantity(int quantity) {
+ if (quantity <= 0) {
+ throw new IllegalArgumentException(ErrorMessages.INVALID_QUANTITY_MESSAGE);
+ }
+ }
+}
+ | Java | 정규표현식 이렇게 작성했으면 되는군요.. 배워갑니다 |
@@ -0,0 +1,41 @@
+package store.service;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import store.domain.Promotion;
+import store.domain.Promotions;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+
+public class PromotionService {
+ private final Promotions promotions;
+
+ public PromotionService(Promotions promotions) {
+ this.promotions = promotions;
+ }
+
+ public Promotion validatePromotionDate(String promotionName) {
+ LocalDateTime currentDate = DateTimes.now();
+
+ Promotion promotion = promotions.getPromotions().stream()
+ .filter(p -> p.getPromotionName().equals(promotionName))
+ .findFirst()
+ .orElse(null);
+ if (promotion!=null) {
+ LocalDate startDate = LocalDate.parse(promotion.getStartDate());
+ LocalDate endDate = LocalDate.parse(promotion.getEndDate());
+ if (currentDate.isBefore(startDate.atStartOfDay()) || currentDate.isAfter(endDate.atStartOfDay())) {
+ return null;
+ }
+ }
+ return promotion;
+ }
+
+ public Promotion findPromotionName(String promotionName) {
+ return promotions.getPromotions().stream()
+ .filter(promotion -> promotion.getPromotionName().equals(promotionName))
+ .findFirst()
+ .orElse(null);
+ }
+} | Java | null 가능성이 있다면 Optional을 활용하는 것도 좋은 방법일 것 같아용 :) |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | ProductController에서 PromotionController를 호출한다면, 컨트롤러 간에 계층이 존재하는 걸까요?
그런 것이 아니라면, 전체적인 코드의 흐름?은 StoreApplication이 제어하도록 하고, 거기에서 두 컨트롤러를 호출하는 방법도 좋을 것 같아요.
어떻게 생각하시나요? |
@@ -0,0 +1,71 @@
+package store.controller;
+
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.service.PromotionService;
+import store.validator.InputConfirmValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+
+public class PromotionController {
+ private final PromotionService promotionService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public PromotionController(PromotionService promotionService, OutputView outputView, InputView inputView, InputConfirmValidator inputConfirmValidator) {
+ this.promotionService = promotionService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+ Promotion validatePromotionDate(String promotionName) {
+ return promotionService.validatePromotionDate(promotionName);
+ }
+
+ public PromotionResult applyPromotionLogic(String productName, int quantity, String promotionName, BigDecimal productPrice, int promoStock) {
+ Promotion applicablePromotion = promotionService.findPromotionName(promotionName);
+ if (applicablePromotion == null) {
+ return new PromotionResult(quantity, 0, BigDecimal.ZERO, BigDecimal.ZERO); // 유효하지 않은 경우, 수량 그대로 반환
+ }
+
+ int buyQuantity = applicablePromotion.getBuyQuantity();
+ int getQuantity = applicablePromotion.getGetQuantity();
+ int freeQuantity = 0;
+ int promotionQuantity = quantity;
+
+ if(promoStock<=quantity){
+ promotionQuantity = promoStock;
+ }
+
+ BigDecimal discountAmount = BigDecimal.ZERO;
+ if (shouldOfferFreeProduct(buyQuantity, quantity) && promoStock>quantity) {
+ String confirmInput = inputView.confirmPromotionAdditionMessage(productName,getQuantity);
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ quantity=++promotionQuantity;
+ }
+ }
+ if(buyQuantity==2){
+ freeQuantity = promotionQuantity/3;
+ }
+ if (buyQuantity==1){
+ freeQuantity = promotionQuantity/2;
+ }
+ discountAmount=productPrice.multiply(BigDecimal.valueOf(freeQuantity));
+ return new PromotionResult(quantity, freeQuantity, discountAmount, discountAmount.multiply(BigDecimal.valueOf(++buyQuantity)));
+ }
+
+
+ private boolean shouldOfferFreeProduct(int buyQuantity, int quantity) {
+ if (buyQuantity == 2 && (quantity % 3) == 2) {
+ return true; // 탄산 2+1의 경우
+ }
+ if (buyQuantity == 1 && (quantity % 2) == 1) {
+ return true; // MD추천 상품, 반짝할인의 경우
+ }
+ return false;
+ }
+} | Java | 이 메서드의 로직들이 굉장히 도메인에 많이 닿아있는 것 같아요. 복잡하기도 하고요!
도메인 객체로 따로 빼는건 어떻게 생각하세요? |
@@ -0,0 +1,39 @@
+package store.domain;
+
+public class Promotion {
+ private String promotionName;
+ private int buyQuantity;
+ private int getQuantity;
+ private String startDate;
+ private String endDate;
+
+ public Promotion(String promotionName, int buyQuantity, int getQuantity, String startDate, String endDate) {
+ this.promotionName = promotionName;
+ this.buyQuantity = buyQuantity;
+ this.getQuantity = getQuantity;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+
+ public String getPromotionName() {
+ return promotionName;
+ }
+
+ public int getBuyQuantity() {
+ return buyQuantity;
+ }
+
+ public int getGetQuantity() {
+ return getQuantity;
+ }
+
+ public String getStartDate() {
+ return startDate;
+ }
+
+ public String getEndDate() {
+ return endDate;
+ }
+
+} | Java | date타입이라면 LocalDate를 활용해도 좋았을 것 같은데, String으로 가져가신 이유가 있나요? |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | 컨트롤러 간에 계층관계를 완화하기 위해 파사드 패턴을 알아보시는것도 좋을것 같습니다. |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | 재귀호출 스택 오버플로우 방지를 위해 재시도 횟수에 제한을 두면 더 좋겠네요. |
@@ -0,0 +1,276 @@
+package store.controller;
+
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.PromotionResult;
+import store.domain.PurchaseRecord;
+import store.service.ProductService;
+import store.utils.ErrorMessages;
+import store.utils.ProductInputParser;
+import store.validator.InputConfirmValidator;
+import store.validator.InputPurchaseValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductController {
+ private final ProductService productService;
+ private final OutputView outputView;
+ private final InputView inputView;
+ private final InputPurchaseValidator inputPurchaseValidator;
+ private final PromotionController promotionController;
+ private final InputConfirmValidator inputConfirmValidator;
+
+ public ProductController(ProductService productService, OutputView outputView, InputView inputView, InputPurchaseValidator inputPurchaseValidator, PromotionController promotionController, InputConfirmValidator inputConfirmValidator) {
+ this.productService = productService;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ this.inputPurchaseValidator = inputPurchaseValidator;
+ this.promotionController = promotionController;
+ this.inputConfirmValidator = inputConfirmValidator;
+ }
+
+ public void printWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ public void printProductList() {
+ List<Product> products = productService.getAllProducts();
+ outputView.printProductList(products);
+ }
+
+ public void handleInitialDisplay() {
+ this.printWelcomeMessage();
+ this.printProductList();
+ }
+
+ public void handlePurchase() {
+ boolean validInput = true;
+ while (validInput) {
+ handleInitialDisplay();
+ String input = inputView.getProductInput();
+ try {
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ List<PurchaseRecord> purchaseRecords = new ArrayList<>();
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+
+ BigDecimal membershipDiscount = applyMembershipDiscount(purchaseRecords);
+ updateInventory(purchaseRecords);
+ printReceipt(purchaseRecords, membershipDiscount);
+ validInput = askForAdditionalPurchase();
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean askForAdditionalPurchase() {
+ String confirmInput = inputView.askForAdditionalPurchase();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return askForAdditionalPurchase();
+ }
+ return confirmInput.equalsIgnoreCase("Y");
+ }
+
+ private void printReceipt(List<PurchaseRecord> purchaseRecords, BigDecimal membershipDiscount) {
+ outputView.printReceipt(purchaseRecords, membershipDiscount);
+ }
+
+ private Map<String, Integer> getValidatedPurchaseItems(String input) {
+ Map<String, Integer> purchaseItems = new HashMap<>();
+ String[] items = input.split(",");
+ for (String item : items) {
+ boolean validItem = false;
+ while (!validItem) {
+ try {
+ inputPurchaseValidator.validateProductInput(item);
+ String productName = ProductInputParser.extractProductName(item);
+ int quantity = ProductInputParser.extractQuantity(item);
+ inputPurchaseValidator.validateQuantity(quantity);
+ purchaseItems.put(productName, quantity);
+ validItem = true;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ return getValidatedPurchaseItems(input); // 전체 입력을 재검증하기 위해 재귀 호출
+ }
+ }
+ }
+ return purchaseItems;
+ }
+
+ private void handleSingleProductPurchase(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ int promoStock;
+ while (true) {
+ try {
+ promoStock = adjustStockAndCheckForSingleProduct(productName, quantity);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ String input = inputView.getProductInput(); // 전체 입력을 다시 받기
+ Map<String, Integer> purchaseItems = getValidatedPurchaseItems(input);
+ purchaseRecords.clear(); // 기존의 잘못된 purchaseRecords 초기화
+
+ for (Map.Entry<String, Integer> entry : purchaseItems.entrySet()) {
+ handleSingleProductPurchase(entry.getKey(), entry.getValue(), purchaseRecords);
+ }
+ return;
+ }
+ }
+
+ Product product = productService.getProductByName(productName);
+ if (product == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ if (product.getPromotion() == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ String promotionName = product.getPromotion();
+ Promotion applicablePromotion = promotionController.validatePromotionDate(promotionName);
+ if (applicablePromotion == null) {
+ nonApplyPromotion(productName, quantity, purchaseRecords);
+ return;
+ }
+
+ PromotionResult promotionResult = promotionController.applyPromotionLogic(productName, quantity, promotionName, product.getPrice(), promoStock);
+ applyPromotion(productName, quantity, purchaseRecords, promotionResult);
+ }
+
+ private void applyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords, PromotionResult promotionResult) {
+ Product product = productService.getProductByName(productName);
+ BigDecimal productPrice = product.getPrice();
+ int updatedQuantity = promotionResult.getUpdatedQuantity();
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ updatedQuantity,
+ promotionResult.getFreeQuantity(),
+ promotionResult.getDiscountAmount(),
+ productPrice.multiply(BigDecimal.valueOf(updatedQuantity)),
+ promotionResult.getPromotionalAmount()
+ );
+ purchaseRecords.add(record);
+ }
+
+ private void nonApplyPromotion(String productName, int quantity, List<PurchaseRecord> purchaseRecords) {
+ Product product = productService.getProductByName(productName);
+ PurchaseRecord record = new PurchaseRecord(
+ productName,
+ quantity,
+ 0,
+ BigDecimal.ZERO,
+ product.getPrice().multiply(BigDecimal.valueOf(quantity)),
+ BigDecimal.ZERO
+ );
+ purchaseRecords.add(record);
+ }
+
+ private BigDecimal applyMembershipDiscount(List<PurchaseRecord> purchaseRecords) {
+ BigDecimal totalDiscountableAmount = BigDecimal.ZERO;
+
+ for (PurchaseRecord record : purchaseRecords) {
+ totalDiscountableAmount = totalDiscountableAmount.add(record.getTotalCost().subtract(record.getPromotionalAmount()));
+ }
+
+
+ String confirmInput = inputView.isMembershipInvalid();
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return applyMembershipDiscount(purchaseRecords);
+ }
+ if (!confirmInput.equalsIgnoreCase("Y")) {
+ return BigDecimal.ZERO;
+ }
+
+
+ BigDecimal membershipDiscount = totalDiscountableAmount.multiply(BigDecimal.valueOf(0.3));
+ BigDecimal maxMembershipDiscount = BigDecimal.valueOf(8000);
+ if (membershipDiscount.compareTo(maxMembershipDiscount) > 0) {
+ return maxMembershipDiscount;
+ }
+
+ return membershipDiscount;
+ }
+
+ private int adjustStockAndCheckForSingleProduct(String productName, int quantity) {
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int promoStock = getPromoStock(promoProduct);
+ int normalStock = getNormalStock(normalProduct);
+
+ if (quantity > promoStock + normalStock) {
+ throw new IllegalArgumentException(ErrorMessages.INSUFFICIENT_STOCK_MESSAGE);
+ }
+ if (quantity > promoStock && promoProduct != null) {
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ return promoStock;
+ }
+
+ private int confirmPartialFullPricePayment(int quantity, int promoStock, String productName) {
+ String confirmInput = inputView.isPromotionInvalid((quantity - promoStock), productName);
+ try {
+ inputConfirmValidator.validateConfirmation(confirmInput);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return confirmPartialFullPricePayment(quantity, promoStock, productName);
+ }
+ if (confirmInput.equalsIgnoreCase("Y")) {
+ return promoStock;
+ }
+ return -1;
+ }
+
+ private int getPromoStock(Product promoProduct) {
+ if (promoProduct == null) {
+ return 0;
+ }
+ return promoProduct.getStockQuantity();
+ }
+
+ private int getNormalStock(Product normalProduct) {
+ if (normalProduct == null) {
+ return 0;
+ }
+ return normalProduct.getStockQuantity();
+ }
+
+ private void updateInventory(List<PurchaseRecord> purchaseItems) {
+ for (PurchaseRecord record : purchaseItems) {
+ String productName = record.getProductName();
+ int totalQuantity = record.getPurchasedQuantity();
+
+ Product promoProduct = productService.getProductByNameAndPromotion(productName, true);
+ Product normalProduct = productService.getProductByNameAndPromotion(productName, false);
+
+ int remainingQuantity = totalQuantity;
+
+ if (promoProduct != null && promoProduct.getStockQuantity() > 0) {
+ int promoUsed = Math.min(promoProduct.getStockQuantity(), remainingQuantity);
+ promoProduct.decreaseStock(promoUsed);
+ remainingQuantity -= promoUsed;
+ }
+
+ if (remainingQuantity > 0 && normalProduct != null && normalProduct.getStockQuantity() >= remainingQuantity) {
+ normalProduct.decreaseStock(remainingQuantity);
+ }
+ }
+ }
+} | Java | 들여쓰기 줄이기 위해 이 부분을 메서드로 빼도 될것 같아요. |
@@ -1 +1,111 @@
-# java-convenience-store-precourse
+# 편의점 서비스
+
+## ✅ 서비스 소개
+편의점에서 상품을 구매할 때 재고 및 프로모션 할인, 멤버십 혜택 등을 고려하여 결제하는 과정을 안내하고 처리하는 시스템
+
+## ✅ 기능 목록
+
+### 재고 안내
+
+- [X] 시작 안내 문구를 보여준다.
+ - [X] 안내 문구는 “`안녕하세요. W편의점입니다.`”이다.
+- [X] 재고 안내 문구와 재고를 보여준다.
+ - [X] 안내 문구는 “`현재 보유하고 있는 상품입니다.`”이다.
+ - [X] 재고는 “`- {상품명} {가격}원 {수량}개 {행사이름}`” 형태로 보여준다.
+ - [X] 오늘 날짜가 프로모션 기간 내에 포함된 경우 행사 상품을 보여준다.
+ - [X] 가격은 천원 단위로 쉼표(,)를 찍어 보여준다.
+ - [X] 만약 재고가 없을 시, “`재고 없음`”을 보여준다.
+ - [X] 1+1 또는 2+1 프로모션에 맞지 않는 형태일 경우 예외가 발생한다.
+ - [X] 동일 상품에 여러 프로모션이 적용될 경우 예외가 발생한다.
+ - [X] 재고 예외의 경우 "`[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.`" 안내 문구를 출력한다.
+
+### 구매
+
+- [X] 구매 상품 및 수량 입력 안내 문구를 보여준다.
+ - [X] 안내 문구는 “`구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])`”이다.
+- [X] 구매 상품과 수량을 입력받는다.
+ - [X] 상품명, 수량은 하이픈(-)으로, 개별 상품은 대괄호([])로 묶어 쉼표(,)로 구분하는 입력 형식을 가진다.
+ - [X] 상품명에 알파벳과 한글 이외의 입력이 들어올 경우 예외가 발생한다.
+ - [X] 수량이 0 이하일 경우 예외가 발생한다.
+ - [X] 수량이 1000개를 초과할 경우 예외가 발생한다.
+ - [X] 입력 형식에 맞지 않게 입력될 경우 예외가 발생한다.
+ - [X] 입력 형식에 대한 예외 문구는 "`[ERROR] 올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.`"이다.
+ - [X] 아무것도 입력되지 않을 경우(””) 예외가 발생한다.
+ - [X] null이 입력될 경우 예외가 발생한다.
+ - [X] 입력한 상품이 없을 경우 예외가 발생한다.
+ - [X] 존재하지 않는 상품에 대한 예외 문구는 "`[ERROR] 존재하지 않는 상품입니다. 다시 입력해 주세요.`"이다.
+ - [X] 입력한 상품의 재고가 부족한 경우 예외가 발생한다.
+ - [X] 재고가 부족한 경우에 대한 예외 문구는 "`[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.`"이다.
+ - [X] 예외 문구 출력 후 사용자로부터 다시 입력을 받는다.
+
+### 일반 결제
+
+- [X] 프로모션 할인이 적용되지 않는 상품을 구매할 때마다, 결제된 수량만큼 해당 상품의 일반 재고에서 차감한다.
+
+### 프로모션 할인
+
+- [X] 오늘 날짜가 프로모션 기간 내에 포함된 경우의 상품에 적용한다.
+- [X] 고객이 상품을 구매할 때마다, 결제된 수량만큼 해당 상품을 프로모션 재고에서 우선 차감한다.
+- [X] 고객에게 상품이 증정될 때마다, 증정 수량 만큼 프로모션 재고에서 차감한다.
+- [X] 프로모션 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, 그 수량만큼의 추가 여부 안내 문구를 보여준다.
+ - [X] 안내 문구는 “`현재 {상품명}은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)`”이다.
+ - [X] 증정 상품 추가 여부를 입력받는다.
+ - [X] “Y” 입력 시 해당 수량만큼 증정 상품으로 추가하고, 프로모션 재고에서 차감한다.
+ - [X] “N” 입력 시 증정 상품을 추가하지 않는다.
+ - [X] Y와 N 이외의 문자 입력 시 예외가 발생한다.
+ - [X] 아무것도 입력되지 않을 경우(””) 예외가 발생한다.
+ - [X] null이 입력될 경우 예외가 발생한다.
+ - [X] 입력 예외가 발생한 경우 "`[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.`" 안내 문구를 출력한다.
+ - [X] 예외 문구 출력 후 사용자로부터 다시 입력을 받는다.
+- [X] 프로모션 재고가 부족한 경우 일반 재고에서 차감한다.
+ - [X] 이 경우 일부 수량에 대한 정가 결제 여부 안내 문구를 보여준다.
+ - [X] 안내 문구는 “`현재 {상품명} {수량}개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)`”이다.
+ - [X] 일부 수량 정가 결제 여부를 입력받는다.
+ - [X] “Y” 입력 시 해당 수량만큼 프로모션 없이 결제하고, 일반 재고에서 차감한다.
+ - [X] “N” 입력 시 해당 수량만큼의 상품을 결제 내역에서 제외한다.
+ - [X] Y와 N 이외의 문자 입력 시 예외가 발생한다.
+ - [X] 아무것도 입력되지 않을 경우(””) 예외가 발생한다.
+ - [X] null이 입력될 경우 예외가 발생한다.
+ - [X] 입력 예외가 발생한 경우 "`[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.`" 안내 문구를 출력한다.
+ - [X] 예외 문구 출력 후 사용자로부터 다시 입력을 받는다.
+
+### 멤버십 할인
+
+- [X] 멤버십 할인 안내 문구를 보여준다.
+ - [X] 안내 문구는 “`멤버십 할인을 받으시겠습니까? (Y/N)`”이다.
+- [X] 멤버십 할인 유무를 입력받는다.
+ - [X] “Y” 입력 시 멤버십 할인을 적용한다.
+ - [X] “N” 입력 시 멤버십 할인을 적용하지 않는다.
+ - [X] Y와 N 이외의 문자 입력 시 예외가 발생한다.
+ - [X] 아무것도 입력되지 않을 경우(””) 예외가 발생한다.
+ - [X] null이 입력될 경우 예외가 발생한다.
+ - [X] 입력 예외가 발생한 경우 "`[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.`" 안내 문구를 출력한다.
+ - [X] 예외 문구 출력 후 사용자로부터 다시 입력을 받는다.
+- [X] 멤버십 할인을 받을 경우 할인을 적용한다.
+ - [X] 멤버십 회원은 프로모션 미적용 금액의 30%를 할인받는다.
+ - [X] 멤버십 할인의 최대 한도는 8,000원이다.
+
+### 영수증 출력
+
+- [X] 영수증을 보여준다.
+ - [X] 영수증 항목은 아래와 같다.
+ - [X] 구매 상품 내역: 구매한 상품명, 수량, 가격
+ - [X] 증정 상품 내역: 프로모션에 의해 무료로 제공된 상품명, 수량
+ - [X] 금액 정보
+ - [X] 총구매액: 구매상품별 가격과 수량을 곱하여 계산
+ - [X] 행사할인: 프로모션에 의해 할인된 금액
+ - [X] 멤버십할인: 멤버십에 의해 추가로 할인된 금액
+ - [X] 내실돈: 총구매액에서 행사 및 멤버십 할인 금액을 제외한 최종 결제 금액
+ - [X] 영수증의 구성 요소를 보기 좋게 정렬한다.
+
+### 추가 구매
+- [X] 추가 구매 진행 안내 문구를 보여준다.
+ - [X] 안내 문구는 “`감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)`”이다.
+- [X] 추가 구매 진행 여부를 입력받는다.
+ - [X] “Y” 입력 시 시작 안내 문구 출력부터 다시 시작한다.
+ - [X] “N” 입력 시 프로그램을 종료한다.
+ - [X] Y와 N 이외의 문자 입력 시 예외가 발생한다.
+ - [X] 아무것도 입력되지 않을 경우(””) 예외가 발생한다.
+ - [X] null이 입력될 경우 예외가 발생한다.
+ - [X] 입력 예외가 발생한 경우 "`[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.`" 안내 문구를 출력한다.
+ - [X] 예외 문구 출력 후 사용자로부터 다시 입력을 받는다. | Unknown | 리드미 볼 때마다 느끼는데, 꼼꼼하게 정리하셔서 좋은 것 같습니다! |
@@ -0,0 +1,59 @@
+package store.inventory;
+
+import java.util.Collections;
+import java.util.List;
+import store.inventory.product.Product;
+import store.inventory.product.ProductProcessor;
+import store.inventory.promotion.PromotionType;
+
+public class Stock {
+ private static final int MAX_PROMOTION_COUNT = 1;
+
+ private final List<Product> products;
+
+ public Stock(ProductProcessor productProcessor) {
+ this.products = productProcessor.getProducts();
+ }
+
+ public List<Product> get() {
+ return Collections.unmodifiableList(products);
+ }
+
+ public boolean isContained(String productName) {
+ return products.stream()
+ .anyMatch(product -> product.getName().equals(productName));
+ }
+
+ public boolean hasPromotion(String productName) {
+ return products.stream()
+ .filter(product -> product.getName().equals(productName))
+ .count() > MAX_PROMOTION_COUNT;
+ }
+
+ public boolean isPromotionStockNotEnough(String productName, int desiredQuantity) {
+ return getPromotionProduct(productName).getQuantity() < desiredQuantity;
+ }
+
+ public Product getGeneralProduct(String productName) {
+ return products.stream()
+ .filter(product -> product.getName().equals(productName)
+ && product.getPromotionType().equals(PromotionType.NONE))
+ .findAny()
+ .get();
+ }
+
+ public Product getPromotionProduct(String productName) {
+ return products.stream()
+ .filter(product -> product.getName().equals(productName)
+ && !product.getPromotionType().equals(PromotionType.NONE))
+ .findAny()
+ .get();
+ }
+
+ public int getAvailableQuantity(String productName) {
+ return products.stream()
+ .filter(product -> product.getName().equals(productName))
+ .mapToInt(Product::getQuantity)
+ .sum();
+ }
+} | Java | 저번에도 느꼈지만 `stream()`을 정말 잘 사용하시는 것 같아요! `stream()`을 사용하니 코드가 깔끔하니 좋은 것 같아요! |
@@ -0,0 +1,48 @@
+package store.inventory.product;
+
+import store.inventory.promotion.PromotionResult;
+import store.inventory.promotion.PromotionType;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int quantity;
+ private final PromotionType promotionType;
+ private final String promotionName;
+
+ public Product(String name, int price, int quantity, PromotionType promotionType, String promotionName) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotionType = promotionType;
+ this.promotionName = promotionName;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getPrice() {
+ return this.price;
+ }
+
+ public int getQuantity() {
+ return this.quantity;
+ }
+
+ public PromotionType getPromotionType() {
+ return this.promotionType;
+ }
+
+ public PromotionResult getPromotionDetails(int desiredQuantity) {
+ return this.promotionType.getDetails(desiredQuantity);
+ }
+
+ public String getPromotionName() {
+ return this.promotionName;
+ }
+
+ public void deduct(int minusQuantity) {
+ this.quantity -= minusQuantity;
+ }
+} | Java | Promotion 대신 PromotionType을 사용하신 이유가 궁금합니다! |
@@ -0,0 +1,78 @@
+package store.inventory.promotion;
+
+import static store.common.Constants.EXCEPT_LINE_COUNT;
+import static store.common.Constants.INVALID_INPUT_ERROR;
+import static store.common.Constants.WORD_DELIMITER;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+import store.inventory.product.Product;
+
+public class PromotionProcessor {
+ private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md";
+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ private static final String NOT_PRODUCTION = "null";
+ private static final int PROMOTION_NAME_INDEX = 0;
+ private static final int PROMOTION_BUY_INDEX = 1;
+ private static final int PROMOTION_GET_INDEX = 2;
+ private static final int PROMOTION_START_DATE_INDEX = 3;
+ private static final int PROMOTION_END_DATE_INDEX = 4;
+
+ private final Map<String, PromotionType> promotions = new HashMap<>();
+ private final Set<String> promotionProducts = new HashSet<>();
+
+ public PromotionProcessor() {
+ load();
+ }
+
+ public boolean isCurrentPromotion(String promotionName) {
+ return (promotions.containsKey(promotionName)
+ && promotions.get(promotionName) != PromotionType.NOT_NOW)
+ || promotionName.equals(NOT_PRODUCTION);
+ }
+
+ public PromotionType getPromotionType(String promotionName) {
+ PromotionType promotionType = promotions.get(promotionName);
+ if(promotionName.equals(NOT_PRODUCTION)) {
+ promotionType = PromotionType.NONE;
+ }
+ return promotionType;
+ }
+
+ public void validateDuplicated(Product product) {
+ if (product.getPromotionType() != PromotionType.NONE
+ && !promotionProducts.add(product.getName())) {
+ throw new IllegalStateException(INVALID_INPUT_ERROR);
+ }
+ }
+
+ private void load() {
+ try (Stream<String> lines = Files.lines(Paths.get(PROMOTIONS_FILE_PATH))) {
+ lines.skip(EXCEPT_LINE_COUNT)
+ .map(this::parse)
+ .forEach(promotion ->
+ promotions.put(promotion.getName(), PromotionType.from(promotion))
+ );
+ }
+ catch (IOException e) {
+ throw new IllegalArgumentException(INVALID_INPUT_ERROR);
+ }
+ }
+
+ private Promotion parse(String line) {
+ String[] promotionInfo = line.split(WORD_DELIMITER);
+ return new Promotion(promotionInfo[PROMOTION_NAME_INDEX],
+ Integer.parseInt(promotionInfo[PROMOTION_BUY_INDEX]),
+ Integer.parseInt(promotionInfo[PROMOTION_GET_INDEX]),
+ LocalDate.parse(promotionInfo[PROMOTION_START_DATE_INDEX], FORMATTER),
+ LocalDate.parse(promotionInfo[PROMOTION_END_DATE_INDEX], FORMATTER));
+ }
+} | Java | 저는 ProductProcessor, PromotionProcessor 등의 내용들을 각각 Product와 Promotion 안에서 처리하여서, 이를 따로 분리하시게 된 과정이 궁금합니다! |
@@ -0,0 +1,48 @@
+package store.inventory.product;
+
+import store.inventory.promotion.PromotionResult;
+import store.inventory.promotion.PromotionType;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int quantity;
+ private final PromotionType promotionType;
+ private final String promotionName;
+
+ public Product(String name, int price, int quantity, PromotionType promotionType, String promotionName) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotionType = promotionType;
+ this.promotionName = promotionName;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getPrice() {
+ return this.price;
+ }
+
+ public int getQuantity() {
+ return this.quantity;
+ }
+
+ public PromotionType getPromotionType() {
+ return this.promotionType;
+ }
+
+ public PromotionResult getPromotionDetails(int desiredQuantity) {
+ return this.promotionType.getDetails(desiredQuantity);
+ }
+
+ public String getPromotionName() {
+ return this.promotionName;
+ }
+
+ public void deduct(int minusQuantity) {
+ this.quantity -= minusQuantity;
+ }
+} | Java | 프로모션은 파일에서 읽어와 프로모션 이름과 프로모션 타입을 매칭한 이후에는, 즉 실제 비즈니스 로직에서는 1+1, 2+1와 같이 프로모션 타입 정보만 필요하다고 생각했기 때문입니다! |
@@ -0,0 +1,78 @@
+package store.inventory.promotion;
+
+import static store.common.Constants.EXCEPT_LINE_COUNT;
+import static store.common.Constants.INVALID_INPUT_ERROR;
+import static store.common.Constants.WORD_DELIMITER;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+import store.inventory.product.Product;
+
+public class PromotionProcessor {
+ private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md";
+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ private static final String NOT_PRODUCTION = "null";
+ private static final int PROMOTION_NAME_INDEX = 0;
+ private static final int PROMOTION_BUY_INDEX = 1;
+ private static final int PROMOTION_GET_INDEX = 2;
+ private static final int PROMOTION_START_DATE_INDEX = 3;
+ private static final int PROMOTION_END_DATE_INDEX = 4;
+
+ private final Map<String, PromotionType> promotions = new HashMap<>();
+ private final Set<String> promotionProducts = new HashSet<>();
+
+ public PromotionProcessor() {
+ load();
+ }
+
+ public boolean isCurrentPromotion(String promotionName) {
+ return (promotions.containsKey(promotionName)
+ && promotions.get(promotionName) != PromotionType.NOT_NOW)
+ || promotionName.equals(NOT_PRODUCTION);
+ }
+
+ public PromotionType getPromotionType(String promotionName) {
+ PromotionType promotionType = promotions.get(promotionName);
+ if(promotionName.equals(NOT_PRODUCTION)) {
+ promotionType = PromotionType.NONE;
+ }
+ return promotionType;
+ }
+
+ public void validateDuplicated(Product product) {
+ if (product.getPromotionType() != PromotionType.NONE
+ && !promotionProducts.add(product.getName())) {
+ throw new IllegalStateException(INVALID_INPUT_ERROR);
+ }
+ }
+
+ private void load() {
+ try (Stream<String> lines = Files.lines(Paths.get(PROMOTIONS_FILE_PATH))) {
+ lines.skip(EXCEPT_LINE_COUNT)
+ .map(this::parse)
+ .forEach(promotion ->
+ promotions.put(promotion.getName(), PromotionType.from(promotion))
+ );
+ }
+ catch (IOException e) {
+ throw new IllegalArgumentException(INVALID_INPUT_ERROR);
+ }
+ }
+
+ private Promotion parse(String line) {
+ String[] promotionInfo = line.split(WORD_DELIMITER);
+ return new Promotion(promotionInfo[PROMOTION_NAME_INDEX],
+ Integer.parseInt(promotionInfo[PROMOTION_BUY_INDEX]),
+ Integer.parseInt(promotionInfo[PROMOTION_GET_INDEX]),
+ LocalDate.parse(promotionInfo[PROMOTION_START_DATE_INDEX], FORMATTER),
+ LocalDate.parse(promotionInfo[PROMOTION_END_DATE_INDEX], FORMATTER));
+ }
+} | Java | 처음 코드를 짤 때는 프로모션 정보를 파일에서 읽어오고(PromotionProcessor), 파싱해온 정보를 임시로 처리하기 위한 구조(Promotion)를 만들면서 클래스가 나뉘었던 것 같아요!
그런데 프로모션을 단순히 읽어오는 것뿐만 아니라, (지금 클래스 내 메서드로 존재하는) 다른 로직들이 필요해지면서 프로모션 관련 처리를 담당하던 PromotionProcessor에 추가 코드가 생겼습니다.
말씀을 듣고 생각해보니, 완성된 코드를 보는 입장에서 책임이 모호하단 느낌이 드네요!
이 부분을 Promotion으로 합치는 것이 좋은 방안이 될 수 있단 생각이 들어요:)
언급해주셔서 감사합니다! |
@@ -1,32 +1,47 @@
# AIFFEL Campus Online Code Peer Review Templete
-- 코더 : 코더의 이름을 작성하세요.
-- 리뷰어 : 리뷰어의 이름을 작성하세요.
+- 코더 : 이종현 님
+- 리뷰어 : 김태훈
# PRT(Peer Review Template)
-- [ ] **1. 주어진 문제를 해결하는 완성된 코드가 제출되었나요?**
- - 문제에서 요구하는 최종 결과물이 첨부되었는지 확인
- - 중요! 해당 조건을 만족하는 부분을 캡쳐해 근거로 첨부
+- [ㅇ ] **1. 주어진 문제를 해결하는 완성된 코드가 제출되었나요?**
+***
+ 
+
+ 코드가 잘 작동됩니다.
+
+***
- [ ] **2. 전체 코드에서 가장 핵심적이거나 가장 복잡하고 이해하기 어려운 부분에 작성된
- 주석 또는 doc string을 보고 해당 코드가 잘 이해되었나요?** - 해당 코드 블럭을 왜 핵심적이라고 생각하는지 확인 - 해당 코드 블럭에 doc string/annotation이 달려 있는지 확인 - 해당 코드의 기능, 존재 이유, 작동 원리 등을 기술했는지 확인 - 주석을 보고 코드 이해가 잘 되었는지 확인 - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+ 주석 또는 doc string을 보고 해당 코드가 잘 이해되었나요?** -
+***
+ 
+
+ 주석을 남겨주셔서 해당 코드를 보는 사람이 조금 더 이해하기 쉽게 해 주시면 좋을듯 해요
+***
+
+
+
+
+
+
- [ ] **3. 에러가 난 부분을 디버깅하여 문제를 해결한 기록을 남겼거나
- 새로운 시도 또는 추가 실험을 수행해봤나요?** - 문제 원인 및 해결 과정을 잘 기록하였는지 확인 - 프로젝트 평가 기준에 더해 추가적으로 수행한 나만의 시도,
- 실험이 기록되어 있는지 확인 - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+ 새로운 시도 또는 추가 실험을 수행해봤나요?**
+***
+해당 내역들도 남겨 두시면 좋을듯 해요
+***
- [ ] **4. 회고를 잘 작성했나요?**
- - 주어진 문제를 해결하는 완성된 코드 내지 프로젝트 결과물에 대해
- 배운점과 아쉬운점, 느낀점 등이 기록되어 있는지 확인
- - 전체 코드 실행 플로우를 그래프로 그려서 이해를 돕고 있는지 확인
- - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
-- [ ] **5. 코드가 간결하고 효율적인가요?**
- - 파이썬 스타일 가이드 (PEP8) 를 준수하였는지 확인
- - 코드 중복을 최소화하고 범용적으로 사용할 수 있도록 함수화/모듈화했는지 확인
- - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+***
+회고도 남겨 두시면 추후 보실때 좋지않을까 합니다.
+***
+- [ㅇ] **5. 코드가 간결하고 효율적인가요?**
+***
+간결하고 효율적인것 같습니다.
+***
# 회고(참고 링크 및 코드 개선)
```
-# 리뷰어의 회고를 작성합니다.
-# 코드 리뷰 시 참고한 링크가 있다면 링크와 간략한 설명을 첨부합니다.
-# 코드 리뷰를 통해 개선한 코드가 있다면 코드와 간략한 설명을 첨부합니다.
+코드와 설명하시는 것을 들으니 실력이 좋으신 분 같으세요 ^^
+제가 코드에 대해 좀더 잘 이해하고, 다양한 피드백을 드릴수 있으면 좋을텐데 그러지 못해 아쉽습니다.
``` | Unknown | 다음 번 부터 참고해서 적용해보겠습니다! |
@@ -1,32 +1,47 @@
# AIFFEL Campus Online Code Peer Review Templete
-- 코더 : 코더의 이름을 작성하세요.
-- 리뷰어 : 리뷰어의 이름을 작성하세요.
+- 코더 : 이종현 님
+- 리뷰어 : 김태훈
# PRT(Peer Review Template)
-- [ ] **1. 주어진 문제를 해결하는 완성된 코드가 제출되었나요?**
- - 문제에서 요구하는 최종 결과물이 첨부되었는지 확인
- - 중요! 해당 조건을 만족하는 부분을 캡쳐해 근거로 첨부
+- [ㅇ ] **1. 주어진 문제를 해결하는 완성된 코드가 제출되었나요?**
+***
+ 
+
+ 코드가 잘 작동됩니다.
+
+***
- [ ] **2. 전체 코드에서 가장 핵심적이거나 가장 복잡하고 이해하기 어려운 부분에 작성된
- 주석 또는 doc string을 보고 해당 코드가 잘 이해되었나요?** - 해당 코드 블럭을 왜 핵심적이라고 생각하는지 확인 - 해당 코드 블럭에 doc string/annotation이 달려 있는지 확인 - 해당 코드의 기능, 존재 이유, 작동 원리 등을 기술했는지 확인 - 주석을 보고 코드 이해가 잘 되었는지 확인 - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+ 주석 또는 doc string을 보고 해당 코드가 잘 이해되었나요?** -
+***
+ 
+
+ 주석을 남겨주셔서 해당 코드를 보는 사람이 조금 더 이해하기 쉽게 해 주시면 좋을듯 해요
+***
+
+
+
+
+
+
- [ ] **3. 에러가 난 부분을 디버깅하여 문제를 해결한 기록을 남겼거나
- 새로운 시도 또는 추가 실험을 수행해봤나요?** - 문제 원인 및 해결 과정을 잘 기록하였는지 확인 - 프로젝트 평가 기준에 더해 추가적으로 수행한 나만의 시도,
- 실험이 기록되어 있는지 확인 - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+ 새로운 시도 또는 추가 실험을 수행해봤나요?**
+***
+해당 내역들도 남겨 두시면 좋을듯 해요
+***
- [ ] **4. 회고를 잘 작성했나요?**
- - 주어진 문제를 해결하는 완성된 코드 내지 프로젝트 결과물에 대해
- 배운점과 아쉬운점, 느낀점 등이 기록되어 있는지 확인
- - 전체 코드 실행 플로우를 그래프로 그려서 이해를 돕고 있는지 확인
- - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
-- [ ] **5. 코드가 간결하고 효율적인가요?**
- - 파이썬 스타일 가이드 (PEP8) 를 준수하였는지 확인
- - 코드 중복을 최소화하고 범용적으로 사용할 수 있도록 함수화/모듈화했는지 확인
- - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+***
+회고도 남겨 두시면 추후 보실때 좋지않을까 합니다.
+***
+- [ㅇ] **5. 코드가 간결하고 효율적인가요?**
+***
+간결하고 효율적인것 같습니다.
+***
# 회고(참고 링크 및 코드 개선)
```
-# 리뷰어의 회고를 작성합니다.
-# 코드 리뷰 시 참고한 링크가 있다면 링크와 간략한 설명을 첨부합니다.
-# 코드 리뷰를 통해 개선한 코드가 있다면 코드와 간략한 설명을 첨부합니다.
+코드와 설명하시는 것을 들으니 실력이 좋으신 분 같으세요 ^^
+제가 코드에 대해 좀더 잘 이해하고, 다양한 피드백을 드릴수 있으면 좋을텐데 그러지 못해 아쉽습니다.
``` | Unknown | 크게 디버깅 해야 할 부분이 있지는 않았지만 사소한 부분이라도 일단 문제 해결에 대한 기록을 남겨볼께요. |
@@ -1,32 +1,47 @@
# AIFFEL Campus Online Code Peer Review Templete
-- 코더 : 코더의 이름을 작성하세요.
-- 리뷰어 : 리뷰어의 이름을 작성하세요.
+- 코더 : 이종현 님
+- 리뷰어 : 김태훈
# PRT(Peer Review Template)
-- [ ] **1. 주어진 문제를 해결하는 완성된 코드가 제출되었나요?**
- - 문제에서 요구하는 최종 결과물이 첨부되었는지 확인
- - 중요! 해당 조건을 만족하는 부분을 캡쳐해 근거로 첨부
+- [ㅇ ] **1. 주어진 문제를 해결하는 완성된 코드가 제출되었나요?**
+***
+ 
+
+ 코드가 잘 작동됩니다.
+
+***
- [ ] **2. 전체 코드에서 가장 핵심적이거나 가장 복잡하고 이해하기 어려운 부분에 작성된
- 주석 또는 doc string을 보고 해당 코드가 잘 이해되었나요?** - 해당 코드 블럭을 왜 핵심적이라고 생각하는지 확인 - 해당 코드 블럭에 doc string/annotation이 달려 있는지 확인 - 해당 코드의 기능, 존재 이유, 작동 원리 등을 기술했는지 확인 - 주석을 보고 코드 이해가 잘 되었는지 확인 - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+ 주석 또는 doc string을 보고 해당 코드가 잘 이해되었나요?** -
+***
+ 
+
+ 주석을 남겨주셔서 해당 코드를 보는 사람이 조금 더 이해하기 쉽게 해 주시면 좋을듯 해요
+***
+
+
+
+
+
+
- [ ] **3. 에러가 난 부분을 디버깅하여 문제를 해결한 기록을 남겼거나
- 새로운 시도 또는 추가 실험을 수행해봤나요?** - 문제 원인 및 해결 과정을 잘 기록하였는지 확인 - 프로젝트 평가 기준에 더해 추가적으로 수행한 나만의 시도,
- 실험이 기록되어 있는지 확인 - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+ 새로운 시도 또는 추가 실험을 수행해봤나요?**
+***
+해당 내역들도 남겨 두시면 좋을듯 해요
+***
- [ ] **4. 회고를 잘 작성했나요?**
- - 주어진 문제를 해결하는 완성된 코드 내지 프로젝트 결과물에 대해
- 배운점과 아쉬운점, 느낀점 등이 기록되어 있는지 확인
- - 전체 코드 실행 플로우를 그래프로 그려서 이해를 돕고 있는지 확인
- - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
-- [ ] **5. 코드가 간결하고 효율적인가요?**
- - 파이썬 스타일 가이드 (PEP8) 를 준수하였는지 확인
- - 코드 중복을 최소화하고 범용적으로 사용할 수 있도록 함수화/모듈화했는지 확인
- - 중요! 잘 작성되었다고 생각되는 부분을 캡쳐해 근거로 첨부
+***
+회고도 남겨 두시면 추후 보실때 좋지않을까 합니다.
+***
+- [ㅇ] **5. 코드가 간결하고 효율적인가요?**
+***
+간결하고 효율적인것 같습니다.
+***
# 회고(참고 링크 및 코드 개선)
```
-# 리뷰어의 회고를 작성합니다.
-# 코드 리뷰 시 참고한 링크가 있다면 링크와 간략한 설명을 첨부합니다.
-# 코드 리뷰를 통해 개선한 코드가 있다면 코드와 간략한 설명을 첨부합니다.
+코드와 설명하시는 것을 들으니 실력이 좋으신 분 같으세요 ^^
+제가 코드에 대해 좀더 잘 이해하고, 다양한 피드백을 드릴수 있으면 좋을텐데 그러지 못해 아쉽습니다.
``` | Unknown | 매번 회고 적는 것을 까먹는 데.. 회고가 중요한 만큼 이 부분도 챙기겠습니다. |
@@ -0,0 +1,24 @@
+package store.constant;
+
+public enum CompareContext {
+ NULL_STRING(""),
+ SQUARE_BRACKET("[\\[\\]]"),
+ ORDER("^(\\[)[^\\[^\\]]+\\-[0-9]+(\\])$"),
+ ORDER_SEPARATOR("-"),
+ YES_OR_NO("^[Y|N]{1}$"),
+ YES("Y"),
+ NO("N"),
+ COMMA(","),
+ NO_STOCK("재고 없음")
+ ;
+
+ final private String context;
+
+ CompareContext(String context){
+ this.context = context;
+ }
+
+ public String getContext(){
+ return context;
+ }
+} | Java | 해당 `;`는 왜 따로 구분되어 있을까요? |
@@ -0,0 +1,27 @@
+package store.constant;
+
+public enum StoreGuide {
+ START_STORE("안녕하세요. W편의점입니다.\n현재 보유하고 있는 상품입니다."),
+ PRODUCT("- %s %,d원 %s %s\n"),
+ GET_ORDER("구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])"),
+ ASK_MEMBERSHIP("멤버십 할인을 받으시겠습니까? (Y/N)"),
+ ASK_MORE("감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)"),
+ ASK_NOT_APPLY_PROMOTION("현재 %s %,d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)\n"),
+ ASK_FREE("현재 %s은(는) %,d개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)\n"),
+ CANCEL_ORDER("주문을 취소했습니다."),
+ RESULT("총구매액\t\t%d\t%,d\n" +
+ "행사할인\t\t\t-%,d\n" +
+ "멤버십할인\t\t\t-%,d\n" +
+ "내실돈\t\t\t %,d");
+
+
+ final private String context;
+
+ StoreGuide(String context){
+ this.context = context;
+ }
+
+ public String getContext(){
+ return context;
+ }
+} | Java | 들여쓰기가 2줄이네요. 한 줄은 삭제하셔도 좋을 것 같아요! |
@@ -0,0 +1,100 @@
+package store.controller;
+
+import store.model.Order;
+import store.model.Product;
+import store.model.PromotionRepository;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.*;
+
+public class StoreOperationController {
+ public void run() {
+ final String productTextPath = "C:\\WoowaCourse\\java-convenience-store-7-33jyu33\\src\\main\\resources\\products.md";
+ final String promotionTextPath = "C:\\WoowaCourse\\java-convenience-store-7-33jyu33\\src\\main\\resources\\promotions.md";
+ // 재고, 프로모션 등록
+ PromotionRepository promotionRepository = new PromotionRepository(getScanner(promotionTextPath));
+ Store store = new Store(getScanner(productTextPath), promotionRepository);
+
+ saleProduct(store);
+ }
+
+ private Scanner getScanner(String path) {
+ try {
+ return new Scanner(new File(path));
+ } catch (IOException e) {
+ throw new IllegalArgumentException("스캐너 사용할 수 없다 욘석아");
+ }
+ }
+
+ private void saleProduct(Store store) {
+ while (true) {
+ printProductInformation(store);
+ Order order = getOrder(store);
+ order.setMembership(InputView.askMembership());
+ OutputView.receipt(order.getProducts(), order.getPromotionalProducts(), order.getResult());
+ if (!InputView.askAdditionalPurchase()) break;
+ }
+ }
+
+ private void printProductInformation(Store store) {
+ OutputView.productInformation(store);
+ }
+
+ private Order getOrder(Store store) {
+ while (true) {
+ try {
+ Map<String, Integer> orderMap = InputView.getOrder();
+ store.validateOrderProductName(orderMap.keySet());
+ return setOrder(orderMap, store);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private Order setOrder(Map<String, Integer> orderMap, Store store) throws IllegalArgumentException {
+ Order order = new Order();
+ orderMap.forEach((name, count) -> {
+ Product saleProduct = store.getSaleProduct(name, count);
+ Product soldProduct = getSoldProduct(saleProduct, name, count);
+ order.addProduct(soldProduct);
+ saleProduct.sold(count);
+ });
+ return order;
+ }
+
+ private Product getSoldProduct(Product saleProduct, String name, Integer count) {
+ Product soldProduct = saleProduct.getSoldProduct(count);
+ soldProduct.checkPromotionPeriod();
+ checkPromotionalProductCount(soldProduct, saleProduct, count, name);
+ return soldProduct;
+ }
+
+ private void checkPromotionalProductCount(Product soldProduct, Product saleProduct, Integer count, String name) throws IllegalArgumentException {
+ Integer promotionProductQuantity = soldProduct.availableProductQuantity(count);
+ if (checkAdditionalCount(promotionProductQuantity, soldProduct, saleProduct, count, name)) return;
+ checkNotApplyPromotion(promotionProductQuantity, name, count);
+ }
+
+ private boolean checkAdditionalCount(Integer promotionProductQuantity, Product soldProduct, Product saleProduct, Integer count, String name){
+ Integer additionalCount = soldProduct.getAdditionalFreeProductCount(count);
+ if ((promotionProductQuantity != null) && (0 < additionalCount) && (saleProduct.validateAdditionalQuantity(additionalCount+count))) {
+ if (InputView.checkAdditionalFreeProduct(name, additionalCount)) {
+ soldProduct.updatePromotionalQuantity(additionalCount+count);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void checkNotApplyPromotion(Integer promotionProductQuantity, String name, Integer count){
+ if (promotionProductQuantity != null && !Objects.equals(promotionProductQuantity, count)) {
+ InputView.checkNotApplyPromotion(name, count - promotionProductQuantity);
+ }
+ }
+
+} | Java | 어라.. 이렇게 제출하셨나요..? 😄 |
@@ -0,0 +1,100 @@
+package store.controller;
+
+import store.model.Order;
+import store.model.Product;
+import store.model.PromotionRepository;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.*;
+
+public class StoreOperationController {
+ public void run() {
+ final String productTextPath = "C:\\WoowaCourse\\java-convenience-store-7-33jyu33\\src\\main\\resources\\products.md";
+ final String promotionTextPath = "C:\\WoowaCourse\\java-convenience-store-7-33jyu33\\src\\main\\resources\\promotions.md";
+ // 재고, 프로모션 등록
+ PromotionRepository promotionRepository = new PromotionRepository(getScanner(promotionTextPath));
+ Store store = new Store(getScanner(productTextPath), promotionRepository);
+
+ saleProduct(store);
+ }
+
+ private Scanner getScanner(String path) {
+ try {
+ return new Scanner(new File(path));
+ } catch (IOException e) {
+ throw new IllegalArgumentException("스캐너 사용할 수 없다 욘석아");
+ }
+ }
+
+ private void saleProduct(Store store) {
+ while (true) {
+ printProductInformation(store);
+ Order order = getOrder(store);
+ order.setMembership(InputView.askMembership());
+ OutputView.receipt(order.getProducts(), order.getPromotionalProducts(), order.getResult());
+ if (!InputView.askAdditionalPurchase()) break;
+ }
+ }
+
+ private void printProductInformation(Store store) {
+ OutputView.productInformation(store);
+ }
+
+ private Order getOrder(Store store) {
+ while (true) {
+ try {
+ Map<String, Integer> orderMap = InputView.getOrder();
+ store.validateOrderProductName(orderMap.keySet());
+ return setOrder(orderMap, store);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private Order setOrder(Map<String, Integer> orderMap, Store store) throws IllegalArgumentException {
+ Order order = new Order();
+ orderMap.forEach((name, count) -> {
+ Product saleProduct = store.getSaleProduct(name, count);
+ Product soldProduct = getSoldProduct(saleProduct, name, count);
+ order.addProduct(soldProduct);
+ saleProduct.sold(count);
+ });
+ return order;
+ }
+
+ private Product getSoldProduct(Product saleProduct, String name, Integer count) {
+ Product soldProduct = saleProduct.getSoldProduct(count);
+ soldProduct.checkPromotionPeriod();
+ checkPromotionalProductCount(soldProduct, saleProduct, count, name);
+ return soldProduct;
+ }
+
+ private void checkPromotionalProductCount(Product soldProduct, Product saleProduct, Integer count, String name) throws IllegalArgumentException {
+ Integer promotionProductQuantity = soldProduct.availableProductQuantity(count);
+ if (checkAdditionalCount(promotionProductQuantity, soldProduct, saleProduct, count, name)) return;
+ checkNotApplyPromotion(promotionProductQuantity, name, count);
+ }
+
+ private boolean checkAdditionalCount(Integer promotionProductQuantity, Product soldProduct, Product saleProduct, Integer count, String name){
+ Integer additionalCount = soldProduct.getAdditionalFreeProductCount(count);
+ if ((promotionProductQuantity != null) && (0 < additionalCount) && (saleProduct.validateAdditionalQuantity(additionalCount+count))) {
+ if (InputView.checkAdditionalFreeProduct(name, additionalCount)) {
+ soldProduct.updatePromotionalQuantity(additionalCount+count);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void checkNotApplyPromotion(Integer promotionProductQuantity, String name, Integer count){
+ if (promotionProductQuantity != null && !Objects.equals(promotionProductQuantity, count)) {
+ InputView.checkNotApplyPromotion(name, count - promotionProductQuantity);
+ }
+ }
+
+} | Java | if문을 사용하더라도 `{}`를 사용하시는 것을 권장합니다!
메서드 길이를 줄이기 위해서는 반복문 내 메서드들을 분리하시면 좋을 것 같네요 ! |
@@ -0,0 +1,59 @@
+package store.model;
+
+import store.constant.CompareContext;
+import store.constant.StoreGuide;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Order {
+ List<Product> soldProducts = new ArrayList<>();
+ boolean membership = false;
+
+ public void addProduct(Product product){
+ soldProducts.add(product);
+ }
+
+ public void setMembership(boolean member){
+ membership = member;
+ }
+
+ public String getProducts(){
+ ArrayList<String> productInformation = new ArrayList<>();
+ for(Product product: soldProducts){
+ productInformation.add(product.getProductReceipt());
+ }
+ return String.join("\n", productInformation);
+ }
+
+ public String getPromotionalProducts(){
+ ArrayList<String> promotionalProductInformation = new ArrayList<>();
+ for(Product product: soldProducts){
+ String promotionReceipt = product.getPromotionReceipt();
+ if(promotionReceipt != null) {
+ promotionalProductInformation.add(promotionReceipt);
+ }
+ }
+ return String.join("\n", promotionalProductInformation);
+ }
+
+ public String getResult(){
+ Integer total = 0;
+ Integer count = 0;
+ Integer promotionDiscount = 0;
+ Integer membershipDiscount = 0;
+
+ for(Product product : soldProducts){
+ total += product.getPrice()*product.getQuantity();
+ count += product.getQuantity();
+ promotionDiscount += product.getPromotionDiscount();
+ membershipDiscount += product.getMembershipDiscount();
+ }
+ membershipDiscount = membershipDiscount * 30/100;
+
+ if(!membership) membershipDiscount = 0;
+ if(8000 < membershipDiscount) membershipDiscount = 8000;
+ Integer price = total-promotionDiscount-membershipDiscount;
+ return String.format(StoreGuide.RESULT.getContext(), count, total, promotionDiscount, membershipDiscount, price);
+ }
+} | Java | 결과 계산 로직을 메서드로 따로 구현하면 어떨까요? |
@@ -0,0 +1,169 @@
+package store.model;
+
+import store.constant.CompareContext;
+import store.constant.ErrorMessage;
+import store.constant.StoreGuide;
+
+import java.util.List;
+import java.util.Objects;
+
+public class Product {
+ private final String name;
+ private final Integer price;
+
+ private Promotion promotion;
+ private Integer quantity;
+ private Integer promotionalQuantity;
+
+ public Product(List<String> productInfo, PromotionRepository promotionRepository) {
+ final int INDEX_NAME = 0;
+ final int INDEX_PRICE = 1;
+ final int INDEX_QUANTITY = 2;
+ final int INDEX_PROMOTION = 3;
+
+ this.name = productInfo.get(INDEX_NAME);
+ this.price = getPrice(productInfo.get(INDEX_PRICE));
+ this.quantity = getPrice(productInfo.get(INDEX_QUANTITY));
+ this.promotion = promotionRepository.getPromotion(productInfo.get(INDEX_PROMOTION));
+ this.promotionalQuantity = 0;
+ if (!Objects.equals(productInfo.get(INDEX_PROMOTION), "null")) {
+ this.promotionalQuantity = getPrice(productInfo.get(INDEX_QUANTITY));
+ }
+ }
+
+ public void update(String quantity, Promotion promotion) {
+ this.quantity += getPrice(quantity);
+ if (promotion != null) {
+ this.promotion = promotion;
+ this.promotionalQuantity = getPrice(quantity);
+ }
+ }
+
+ public void updatePromotionalQuantity(Integer promotionalQuantity){
+ this.quantity = promotionalQuantity;
+ this.promotionalQuantity = promotionalQuantity;
+ }
+
+ public Product(String name, Integer price, Integer quantity, Promotion promotion, Integer promotionalQuantity) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotion = promotion;
+ this.promotionalQuantity = promotionalQuantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Integer getPrice() {
+ return price;
+ }
+
+ public Integer getQuantity() {
+ return quantity;
+ }
+
+ public Integer getAdditionalFreeProductCount(Integer quantity) {
+ if (promotion != null){
+ return promotion.getAdditionalFreeProductCount(quantity);
+ }
+ return 0;
+ }
+
+ public boolean validateAdditionalQuantity(Integer quantity) {
+ return quantity <= this.promotionalQuantity;
+ }
+
+ public void validateOrderQuantity(Integer quantity) throws IllegalArgumentException {
+ if (this.quantity < quantity) {
+ throw new IllegalArgumentException(ErrorMessage.OVER_QUANTITY.getMessage());
+ }
+ }
+
+ // 프로모션 적용 가능한 수량
+ public Integer availableProductQuantity(Integer quantity) {
+ if (promotion == null) return null;
+ return promotion.getDiscountedProductCount(getPromotionalProductQuantity(quantity));
+ }
+
+ public void checkPromotionPeriod() {
+ if (promotion == null || !promotion.inPeriod()) {
+ promotionalQuantity = 0;
+ }
+ }
+
+ // 주문 받은 수량 중 프로모션 적용할 상품의 개수
+ private Integer getPromotionalProductQuantity(Integer quantity) {
+ if (promotionalQuantity < quantity) return promotionalQuantity;
+ return quantity;
+ }
+
+ public Integer getPromotionDiscount() {
+ if (promotion == null) return 0;
+ return promotion.getFreeProductCount(promotionalQuantity) * price;
+ }
+
+ public Integer getMembershipDiscount() {
+ if (promotion == null) return quantity * price;
+ return (quantity - promotion.getDiscountedProductCount(promotionalQuantity)) * price;
+ }
+
+ public String getProductReceipt() {
+ return String.format("%s\t\t%,d\t%,d", name, quantity, quantity * price);
+ }
+
+ public String getPromotionReceipt() {
+ if (promotion == null) return null;
+ Integer freeQuantity = promotion.getFreeProductCount(promotionalQuantity);
+ if (freeQuantity == 0) return null;
+ return String.format("%s\t\t%,d", name, freeQuantity);
+ }
+
+ public String getProductInformation() {
+ if (promotion != null) {
+ return getPromotionalProductInformation()+getGeneralProductInformation();
+ }
+ return getGeneralProductInformation();
+ }
+
+ private String getGeneralProductInformation(){
+ String quantityContext = CompareContext.NO_STOCK.getContext();
+ if (0 < quantity - promotionalQuantity){
+ quantityContext = Integer.toString(quantity - promotionalQuantity)+"개";
+ }
+ return String.format(StoreGuide.PRODUCT.getContext(), name, price, quantityContext, CompareContext.NULL_STRING.getContext());
+ }
+
+ private String getPromotionalProductInformation() {
+ String quantityContext = CompareContext.NO_STOCK.getContext();
+ if (0 < promotionalQuantity){
+ quantityContext = Integer.toString(promotionalQuantity)+"개";
+ }
+ return String.format(StoreGuide.PRODUCT.getContext(), name, price, quantityContext, promotion.getName());
+ }
+
+ public void sold(Integer count) {
+ if (promotion != null) {
+ promotionalQuantity -= availableProductQuantity(count);
+ }
+ quantity -= count;
+ }
+
+ public Product getSoldProduct(Integer count) {
+ Integer promotionProductQuantity = availableProductQuantity(count);
+ if (promotion == null) promotionProductQuantity = 0;
+ return new Product(name, price, count, promotion, promotionProductQuantity);
+ }
+
+ private Integer getPrice(String priceContext) {
+ validatePrice(priceContext);
+ return Integer.parseInt(priceContext);
+ }
+
+ private void validatePrice(String priceContext) {
+ if (!priceContext.matches("^[0-9]+$")) {
+ throw new IllegalArgumentException("product 재고 등록 가격은 숫자로만 구성해야 합니다");
+ }
+ }
+}
\ No newline at end of file | Java | 네이밍은 상수 네이밍을 하신 것 같은데, 상수로 선언하기 위해서는 `static final`을 사용해야 합니다! 그렇지 않고 변수로 사용하신다면 낙타 네이밍 규칙에 맞게 네이밍하시는 것이 좋습니다.
그리고 상수로 선언하는 것은 메서드 내가 아니라 클래스 내에서 선언해야 합니다. 상수에 대해 알아보시면 좋을 것 같아요 ! |
@@ -0,0 +1,38 @@
+package store.model;
+
+import java.util.*;
+
+public class PromotionRepository {
+ private final HashMap<String, Promotion> promotions = new HashMap<>();
+
+ public PromotionRepository(Scanner promotionScanner){
+ // 첫 줄 제외
+ promotionScanner.nextLine();
+
+ while(promotionScanner.hasNext()){
+ setPromotions(promotionScanner.nextLine());
+ }
+ }
+
+ public Promotion getPromotion(String name){
+ return promotions.get(name);
+ }
+
+ private void setPromotions(String promotionContext){
+ List<String> promotionInfo = new ArrayList<>(contextToList(promotionContext));
+ String promotionName = promotionInfo.getFirst();
+ this.promotions.put(promotionName, new Promotion(promotionInfo));
+ }
+
+ private List<String> contextToList(String context) {
+ List<String> promotionInfo = Arrays.asList(context.strip().split(","));
+ validateInfoSize(promotionInfo);
+ return promotionInfo;
+ }
+
+ private void validateInfoSize(List<String> promotionInfo) {
+ if (promotionInfo.size() != 5) {
+ throw new IllegalArgumentException("promotion 등록 형식에 문제 있음");
+ }
+ }
+} | Java | 이런 주석은 삭제하셔도 좋을 것 같아요!
의미 없는 주석을 지우는 것도 컨벤션입니다 ! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.