code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,77 @@
+package store.global.util;
+
+import static store.global.constant.ErrorMessage.INVALID_INPUT_PURCHASE;
+import static store.global.validation.CommonValidator.validateBlank;
+import static store.global.validation.CommonValidator.validateNotNumeric;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class PurchaseParser {
+
+ private static final Pattern PRODUCT_PATTERN = Pattern.compile("^\\[(.*?)-(\\d+)]$");
+ private static final Pattern INVALID_NAME_PATTERN = Pattern.compile(".*[-\\[\\]].*");
+
+ public static Map<String, Integer> parseInputProduct(String input) {
+ validateInput(input);
+
+ String[] splitProducts = splitInput(input);
+ LinkedHashMap<String, Integer> product = new LinkedHashMap<>();
+
+ for (String productString : splitProducts) {
+ processProductString(productString, product);
+ }
+ return product;
+ }
+
+ private static String[] splitInput(String input) {
+ return input.split(",");
+ }
+
+ private static void processProductString(String productString, Map<String, Integer> product) {
+ String name = extractProductName(productString);
+ String quantity = extractProductQuantity(productString);
+ addProductToMap(name, quantity, product);
+ }
+
+ private static String extractProductName(String productString) {
+ Matcher matcher = matchProductPattern(productString);
+ String name = matcher.group(1);
+ validateName(name);
+ return name;
+ }
+
+ private static String extractProductQuantity(String productString) {
+ Matcher matcher = matchProductPattern(productString);
+ String quantity = matcher.group(2);
+ validateNotNumeric(quantity, INVALID_INPUT_PURCHASE);
+ return quantity;
+ }
+
+ private static Matcher matchProductPattern(String productString) {
+ Matcher matcher = PRODUCT_PATTERN.matcher(productString);
+ if (!matcher.find()) {
+ throw new IllegalArgumentException(INVALID_INPUT_PURCHASE.getMessage());
+ }
+ return matcher;
+ }
+
+ private static void addProductToMap(String name, String quantity, Map<String, Integer> product) {
+ product.merge(name, Integer.parseInt(quantity), Integer::sum);
+ }
+
+ private static void validateName(String name) {
+ validateBlank(name, INVALID_INPUT_PURCHASE);
+ if (INVALID_NAME_PATTERN.matcher(name).matches()) {
+ throw new IllegalArgumentException(INVALID_INPUT_PURCHASE.getMessage());
+ }
+ }
+
+ private static void validateInput(String input) {
+ if (!input.matches("^\\[.*]$")) {
+ throw new IllegalArgumentException(INVALID_INPUT_PURCHASE.getMessage());
+ }
+ }
+} | Java | 공통 피드백에서 변수 이름에 자료형을 넣지 말라고 하더라구요! |
@@ -0,0 +1,15 @@
+package store.domain.product;
+
+public class Name {
+
+ private final String name;
+
+ public Name(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+} | Java | Name클래스의 용도가 궁금해요! |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | 개인적으로는 컨트롤러가 부담이 조금 큰 것 같아요!
비즈니스 로직을 위임하지않고 일부를 담당하고있다는 느낌이 들어요. 어떻게 생각하시나요?! |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "총구매액", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "행사할인", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "멤버십할인", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "내실돈", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | 최대 할인 금액이 넘어섰는지 확인하는 메서드로 따로 분리를 했으면 더 좋았을 것 같다는 생각이 들었어요! |
@@ -0,0 +1,46 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Promotions {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotions(String name, String buy, String get, String startDate, String endDate) {
+ this.name = name;
+ this.buy = Integer.parseInt(buy);
+ this.get = Integer.parseInt(get);
+ this.startDate = LocalDate.parse(startDate);
+ this.endDate = LocalDate.parse(endDate);
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ public boolean hasName(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionApplicable(int quantity) {
+ return calculateRemainingItems(quantity) >= get;
+ }
+
+ public int calculateRemainingItems(int quantity) {
+ return quantity % (buy + get);
+ }
+
+ public int calculatePromotionUnits(int quantity) {
+ return quantity / (buy + get);
+ }
+
+ public boolean isWithinPromotionPeriod(LocalDate date) {
+ return (date.isEqual(startDate) || date.isAfter(startDate)) &&
+ (date.isEqual(endDate) || date.isBefore(endDate));
+ }
+} | Java | 혹시, Name 타입으로 하지 않으신 이유가 있나용?? |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | 안녕하세요!
객체를 객체답게 활용하기 위해, 메시지를 전달해 객체가 스스로 작업을 수행하도록 하는 것이 좋다는 공통 피드백을 확인했습니다.
현재 메서드는 수량(quantity)을 1씩 증가시키는 단순한 로직을 가지고 있는데요,
이 경우 매번 호출할 때마다 수량을 1씩 증가시키는 대신, 파라미터로 증가할 수량을 전달하고 이를 반영하는 방법도 고려해볼 수 있을 것 같습니다.
```
public void increaseQuantity(int number) {
this.quantity += number;
}
```
하지만 이와 동시에 너무 단순한 로직에도 메시지를 통해 작업을 수행해야 하는지 고민이 되네요..
혹시 어떻게 생각하시는지 궁금합니다. |
@@ -0,0 +1,39 @@
+package store.domain.product;
+
+import static store.global.constant.ErrorMessage.INVALID_PRICE_NUMERIC;
+import static store.global.constant.ErrorMessage.INVALID_PRICE_OUT_OF_RANGE;
+import static store.global.validation.CommonValidator.validateNotNumeric;
+
+import java.text.DecimalFormat;
+
+public class Price {
+
+ private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###");
+ private static final int MINIMUM_PRICE = 1;
+ private static final int MAXIMUM_PRICE = 1_000_000;
+ private static final String UNIT = "원";
+
+ private final int price;
+
+ public Price(final String inputPrice) {
+ validateNotNumeric(inputPrice, INVALID_PRICE_NUMERIC);
+ int price = Integer.parseInt(inputPrice);
+ validateRange(price);
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ @Override
+ public String toString() {
+ return DECIMAL_FORMAT.format(price) + UNIT;
+ }
+
+ private void validateRange(final int price) {
+ if (price < MINIMUM_PRICE || price > MAXIMUM_PRICE) {
+ throw new IllegalArgumentException(INVALID_PRICE_OUT_OF_RANGE.getMessage());
+ }
+ }
+} | Java | 동일한 형식의 상수를 Quantity에서도 보았어요!
혹시, 공통적으로 사용하는 상수는 따로 분리를 하시는 것은 어떻게 생각하시나요? |
@@ -0,0 +1,58 @@
+package store.view;
+
+import static store.global.constant.MessageConstant.FORMAT;
+import static store.global.constant.MessageConstant.NEW_LINE;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_PROMOTION;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_SEPARATOR;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_STORE;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_INFO;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_PREFIX;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_ADD;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_NOT_APPLIED;
+import static store.global.constant.MessageConstant.OUTPUT_WELCOME;
+
+import java.util.List;
+
+public class OutputView {
+
+ public void printWelcomeMessage() {
+ System.out.println(OUTPUT_WELCOME.getMessage());
+ System.out.println(OUTPUT_PRODUCT_INFO.getMessage() + NEW_LINE.getMessage());
+ }
+
+ public void printProductsInfo(List<String> products) {
+ products.forEach(product ->
+ System.out.println(OUTPUT_PRODUCT_PREFIX.getMessage() + product)
+ );
+ }
+
+ public void printPromotionNotApplied(String name, int quantity) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_NOT_APPLIED.getMessage() + NEW_LINE.getMessage(),
+ name, quantity);
+ }
+
+ public void printPromotionAddition(String name) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_ADD.getMessage() + NEW_LINE.getMessage(), name);
+ }
+
+ public void printPaymentInfoResult(List<String> infos) {
+ System.out.printf(NEW_LINE.getMessage());
+ System.out.println(OUTPUT_HEADER_STORE.getMessage());
+ System.out.printf(FORMAT.getMessage() + NEW_LINE.getMessage(), "상품명", "수량", "금액");
+ infos.forEach(System.out::println);
+ }
+
+ public void printPromotionInfoResult(List<String> strings) {
+ System.out.println(OUTPUT_HEADER_PROMOTION.getMessage());
+ strings.forEach(System.out::println);
+ }
+
+ public void printFinalResult(List<String> result) {
+ System.out.println(OUTPUT_HEADER_SEPARATOR.getMessage());
+ result.forEach(System.out::println);
+ }
+
+ public void printErrorMessage(String message) {
+ System.out.println(message);
+ }
+} | Java | 안녕하세요!
혹시 아래와 같이 포맷을 설정하셨을 때, 띄어쓰기 때문에 출력이 올바르게 정렬이 가능하셨나요?
4주 차 진행하면서 영수증 출력 부분을 보기 좋게 정리하는 것이 요구사항이었어서 많이 찾아봤습니다!
그 과정에서 알게 된 점은, 한국어는 2글자로 취급되지만, 띄어쓰기와 영어는 1글자로 취급된다는 것입니다. 그래서 띄어쓰기를 한글처럼 2글자 역할을 할 수 있는 방법이 있을까 고민하다가, \u3000 (유니코드 공백)을 알게 되었습니다!
예를 들어, 아래와 같이 사용할 수 있습니다:
`String name = String.format("%-14s", "총구매액").replace(" ", "\u3000");`
이 방법을 사용하면 한글처럼 띄어쓰기를 2글자 취급할 수 있어서 정렬 문제를 해결할 수 있습니다! 😊 |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "총구매액", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "행사할인", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "멤버십할인", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "내실돈", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | 안녕하세요!
저도 공통 피드백에서 도메인 객체는 출력과 관련된 로직을 최대한 배제하고,
필요한 경우 toString을 오버라이드하는 정도로 제한하는 것이 좋다고 본 것 같습니다.
현재 해당 부분은 도메인에서 출력 로직을 처리하고 있는 것으로 보여요!
view에서 처리하는 방식이 더 좋은 것 같은데 어떻게 생각하시나요? |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | 저는 생각이 조금 다른 게, 저렇게 숫자를 통해 값을 조작할 수 있게 하면 단순히 +1 하는 것보다 조금 더 책임을 전가하는 것이라고 해석할 수도 있지 않나요? |
@@ -0,0 +1,58 @@
+package store.view;
+
+import static store.global.constant.MessageConstant.FORMAT;
+import static store.global.constant.MessageConstant.NEW_LINE;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_PROMOTION;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_SEPARATOR;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_STORE;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_INFO;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_PREFIX;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_ADD;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_NOT_APPLIED;
+import static store.global.constant.MessageConstant.OUTPUT_WELCOME;
+
+import java.util.List;
+
+public class OutputView {
+
+ public void printWelcomeMessage() {
+ System.out.println(OUTPUT_WELCOME.getMessage());
+ System.out.println(OUTPUT_PRODUCT_INFO.getMessage() + NEW_LINE.getMessage());
+ }
+
+ public void printProductsInfo(List<String> products) {
+ products.forEach(product ->
+ System.out.println(OUTPUT_PRODUCT_PREFIX.getMessage() + product)
+ );
+ }
+
+ public void printPromotionNotApplied(String name, int quantity) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_NOT_APPLIED.getMessage() + NEW_LINE.getMessage(),
+ name, quantity);
+ }
+
+ public void printPromotionAddition(String name) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_ADD.getMessage() + NEW_LINE.getMessage(), name);
+ }
+
+ public void printPaymentInfoResult(List<String> infos) {
+ System.out.printf(NEW_LINE.getMessage());
+ System.out.println(OUTPUT_HEADER_STORE.getMessage());
+ System.out.printf(FORMAT.getMessage() + NEW_LINE.getMessage(), "상품명", "수량", "금액");
+ infos.forEach(System.out::println);
+ }
+
+ public void printPromotionInfoResult(List<String> strings) {
+ System.out.println(OUTPUT_HEADER_PROMOTION.getMessage());
+ strings.forEach(System.out::println);
+ }
+
+ public void printFinalResult(List<String> result) {
+ System.out.println(OUTPUT_HEADER_SEPARATOR.getMessage());
+ result.forEach(System.out::println);
+ }
+
+ public void printErrorMessage(String message) {
+ System.out.println(message);
+ }
+} | Java | 헉 .. ! 너무나도 좋은 꿀팁 감사드립니다. |
@@ -0,0 +1,48 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+
+public class PaymentProduct {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private final String name;
+ private final int quantity;
+ private final int price;
+ private final int promotion;
+
+ public PaymentProduct(String name, int quantity, int price, int promotion) {
+ this.name = name;
+ this.quantity = quantity;
+ this.price = price;
+ this.promotion = promotion;
+ }
+
+ @Override
+ public String toString() {
+ String formattedPrice = PRICE_FORMAT.format(quantity * price);
+ return String.format(FORMAT.getMessage(), name, quantity, formattedPrice);
+ }
+
+ public boolean isPromotion() {
+ return promotion != 0;
+ }
+
+ public String buildPromotion() {
+ return String.format(FORMAT.getMessage(), name, promotion, "");
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getTotalPrice() {
+ return quantity * price;
+ }
+
+ public int getPromotionPrice() {
+ return promotion * price;
+ }
+} | Java | DecimalFormat이라는 클래스는 처음 보네요 ! 배워갑니다 |
@@ -0,0 +1,48 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+
+public class PaymentProduct {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private final String name;
+ private final int quantity;
+ private final int price;
+ private final int promotion;
+
+ public PaymentProduct(String name, int quantity, int price, int promotion) {
+ this.name = name;
+ this.quantity = quantity;
+ this.price = price;
+ this.promotion = promotion;
+ }
+
+ @Override
+ public String toString() {
+ String formattedPrice = PRICE_FORMAT.format(quantity * price);
+ return String.format(FORMAT.getMessage(), name, quantity, formattedPrice);
+ }
+
+ public boolean isPromotion() {
+ return promotion != 0;
+ }
+
+ public String buildPromotion() {
+ return String.format(FORMAT.getMessage(), name, promotion, "");
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getTotalPrice() {
+ return quantity * price;
+ }
+
+ public int getPromotionPrice() {
+ return promotion * price;
+ }
+} | Java | promotion 변수의 정확한 뜻이 무엇인가요?
프로모션 여부인가요? 프로모션 가격인가요? 굳이 int 타입으로 작성하신 이유가 궁금합니다! |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "총구매액", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "행사할인", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "멤버십할인", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "내실돈", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | 우아한테크코스의 공통 피드백에서 변수명에 자료형(List) 같은 걸 넣지 말라고 했는데, 이에 대해 변수는 아니지만 PaymentProductList 라는 클래스 명에 대해 어떻게 생각하시나요? |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "총구매액", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "행사할인", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "멤버십할인", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "내실돈", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | 여기서 - 같은 것은 상수로 처리하는 것이 나을 것 같은데 어떻게 생각하시나요? |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "총구매액", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "행사할인", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "멤버십할인", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "내실돈", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | 전체적으로 여기 8000 이라는 숫자도 그렇고, 상수화를 했으면 더 가독성이 좋았을 것 같아요! |
@@ -0,0 +1,83 @@
+package store.domain;
+
+import java.time.LocalDate;
+import store.domain.product.Name;
+import store.domain.product.Price;
+import store.domain.product.Quantity;
+
+public class Product {
+
+ private static final String INFO_DELIMITER = " ";
+
+ private final Name name;
+ private final Price price;
+ private final Quantity quantity;
+ private final Promotions promotions;
+
+ public Product(Name name, Price price, Quantity quantity, Promotions promotions) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotions = promotions;
+ }
+
+ @Override
+ public String toString() {
+ String info = buildInfo();
+
+ if (hasPromotion()) {
+ return String.join(INFO_DELIMITER,
+ info,
+ promotions.toString());
+ }
+ return info;
+ }
+
+ public int decreaseStock(int quantity) {
+ return this.quantity.decreaseStock(quantity);
+ }
+
+ public int calculateRemainingStock(int purchaseQuantity) {
+ return quantity.calculateDifference(purchaseQuantity);
+ }
+
+ public boolean hasSameName(String name) {
+ return this.name.toString().equals(name);
+ }
+
+ public boolean hasPromotion() {
+ return this.promotions != null;
+ }
+
+ private String buildInfo() {
+ return String.join(INFO_DELIMITER,
+ name.toString(),
+ price.toString(),
+ quantity.toString()
+ );
+ }
+
+ public int calculatePromotionRate(int quantity) {
+ return promotions.calculateRemainingItems(quantity);
+ }
+
+ public String getProductName() {
+ return name.toString();
+ }
+
+ public int getProductPrice() {
+ return price.getPrice();
+ }
+
+ public boolean isPromotionAdditionalProduct(int quantity) {
+ return promotions.isPromotionApplicable(quantity);
+ }
+
+ public int getPromotionUnits(int quantity) {
+ return promotions.calculatePromotionUnits(quantity);
+ }
+
+ public boolean isWithinPromotionPeriod(LocalDate date) {
+ return promotions.isWithinPromotionPeriod(date);
+ }
+} | Java | 모든 필드가 래핑되어 있는 것이 가독성과 로직 분리에 좋은 영향을 끼치는 것 같아요! 👍 |
@@ -0,0 +1,46 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Promotions {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotions(String name, String buy, String get, String startDate, String endDate) {
+ this.name = name;
+ this.buy = Integer.parseInt(buy);
+ this.get = Integer.parseInt(get);
+ this.startDate = LocalDate.parse(startDate);
+ this.endDate = LocalDate.parse(endDate);
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ public boolean hasName(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionApplicable(int quantity) {
+ return calculateRemainingItems(quantity) >= get;
+ }
+
+ public int calculateRemainingItems(int quantity) {
+ return quantity % (buy + get);
+ }
+
+ public int calculatePromotionUnits(int quantity) {
+ return quantity / (buy + get);
+ }
+
+ public boolean isWithinPromotionPeriod(LocalDate date) {
+ return (date.isEqual(startDate) || date.isAfter(startDate)) &&
+ (date.isEqual(endDate) || date.isBefore(endDate));
+ }
+} | Java | 저도 궁금합니다! |
@@ -0,0 +1,32 @@
+package store.global.constant;
+
+public enum ErrorMessage {
+ INVALID_INPUT_PURCHASE("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요."),
+ INVALID_INPUT("잘못된 입력입니다. 다시 입력해 주세요."),
+
+ INVALID_PRICE_NUMERIC("물품 가격은 숫자만 가능합니다. 다시 확인해 주세요."),
+ INVALID_PRICE_OUT_OF_RANGE("물품 가격은 범위내만 등록할 수 있습니다. 다시 확인해 주세요."),
+
+ INSUFFICIENT_STOCK("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."),
+ INVALID_QUANTITY_NUMERIC("물품 수량은 숫자만 가능합니다. 다시 확인해 주세요."),
+ INVALID_QUANTITY_OUT_OF_RANGE("물품 수량은 범위내만 등록할 수 있습니다. 다시 확인해 주세요."),
+
+ PRODUCT_NOT_FOUND("존재하지 않는 상품입니다. 다시 입력해 주세요."),
+ INVALID_PRODUCT_ELEMENT("상품 정보의 요소가 올바르지 않았습니다. 파일을 확인해 주세요."),
+
+ FILE_NOT_FOUND("%s 파일을 찾을 수 없습니다. 파일 이름을 확인해 주세요."),
+ FILE_CONTAINS_BLANK_CONTENT("파일의 내용 중 공백인 부분이 있습니다. 파일을 확인해 주세요."),
+ FILE_CONTENT_NULL("파일의 내용이 NULL 입니다. 파일을 확인해 주세요."),
+ FILE_CONTENT_INSUFFICIENT("파일의 정보가 부족합니다. 파일을 확인해 주세요.");
+
+ private static final String ERROR_PREFIX = "[ERROR] ";
+ private final String message;
+
+ ErrorMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return ERROR_PREFIX + message;
+ }
+} | Java | 이렇게 [ERROR]을 한번에 처리하는 방식 좋네요. |
@@ -0,0 +1,13 @@
+package store.global.exception;
+
+import store.global.constant.ErrorMessage;
+
+public class FileException extends RuntimeException {
+ public FileException(ErrorMessage error, String fileName) {
+ super(String.format(error.getMessage(), fileName));
+ }
+
+ public FileException(ErrorMessage errorMessage) {
+ super(errorMessage.getMessage());
+ }
+} | Java | FileExceiption을 따로 정의하신 이유가 있을까요? 궁금합니다. |
@@ -0,0 +1,61 @@
+package store.global.util;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.domain.Product;
+import store.domain.PromotionsList;
+import store.domain.product.Name;
+import store.domain.product.Price;
+import store.domain.product.Quantity;
+
+public class ProductParser {
+ private static final String DEFAULT_QUANTITY = "0";
+ private static final String NO_PROMOTION = "null";
+
+ private static PromotionsList promotionsList;
+
+ public static List<Product> parseToProducts(final List<List<String>> inputData,
+ final PromotionsList promotionsList) {
+ ProductParser.promotionsList = promotionsList;
+
+ List<Product> products = new ArrayList<>();
+ for (List<String> productData : inputData) {
+ Product product = createProduct(productData);
+ products.add(product);
+ addDefaultProductIfNecessary(products, inputData, productData, product);
+ }
+ return products;
+ }
+
+ private static void addDefaultProductIfNecessary(List<Product> products, List<List<String>> inputData,
+ List<String> productData, Product product) {
+ if (product.hasPromotion() && isSingleProductInInput(inputData, productData)) {
+ Product defaultProduct = createDefaultProduct(productData);
+ products.add(defaultProduct);
+ }
+ }
+
+ private static boolean isSingleProductInInput(List<List<String>> inputData, List<String> productData) {
+ return inputData.stream()
+ .filter(info -> info.contains(productData.get(0)))
+ .count() == 1;
+ }
+
+ private static Product createDefaultProduct(List<String> productData) {
+ return createProduct(List.of(
+ productData.get(0),
+ productData.get(1),
+ DEFAULT_QUANTITY,
+ NO_PROMOTION
+ ));
+ }
+
+ private static Product createProduct(List<String> productData) {
+ return new Product(
+ new Name(productData.get(0)),
+ new Price(productData.get(1)),
+ new Quantity(productData.get(2)),
+ promotionsList.findPromotion(productData.get(3))
+ );
+ }
+} | Java | 저는 FileUtil에서 사실 모든 파싱도 처리하도록 작성했는데, 이렇게 Parser을 따로 구분하는 것이 더 좋은 설계인 것 같습니다! 칭찬해요 :) |
@@ -0,0 +1,28 @@
+import { Country } from "../types/country";
+
+const CountryCard = ({
+ country,
+ handleToggleCountry,
+}: {
+ country: Country;
+ handleToggleCountry: (country: Country) => void;
+}) => {
+ return (
+ <div
+ className="flex flex-col border rounded gap-2 px-4"
+ onClick={() => handleToggleCountry(country)}
+ >
+ <div className="flex justify-center mb-2">
+ <img
+ src={country.flags.svg}
+ alt={`${country.name.common} flag`}
+ className="w-32 h-20"
+ />
+ </div>
+ <h2>{country.name.common}</h2>
+ <p>{country.capital}</p>
+ </div>
+ );
+};
+
+export default CountryCard; | Unknown | h2 태그를 사용하기엔 너무 많아 질 것 같은데, 전체적인 관점으로 봤을때 h2의 레벨을 가진 텍스트는 아닌 것 같아서요! strong 태그대신 h2를 쓰신 이유가 궁금합니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | early if pattern 추천두립니다 .. >_< |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | countryList 컴포넌트를 보니, 단순 UI만 제공하는 것이 아닌 핵심 로직들을 전부 다 가지고 있는 것으로 보입니다.
파일명으로만 보았을땐, UI 역할만 하고 있을 것으로 추측되었는데 재활용 가능한 컴포넌트는 아닌 것 같아서요~
개인적인 의견으로는 List에는 단순 내려준 데이터를 노출하게만 하고, 비즈니스 로직은 위에서 전달해주는 것이 어떤지 코멘트 드립니다! |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ return response.data;
+ } catch (error) {
+ throw new Error();
+ }
+}; | TypeScript | 별로 중요한 것은 아니지만 ㅎㅎ
throw new Error() 요기에 뭔가를 넣어주시면 좋아요
```javascript
throw new Error(error.response?.data.message);
```
이런식으로요 ㅎㅎ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 필터를 하기 위한 의도로 setCountries 를 만들어 값을 변경하고 있는 것으로 보입니다!
favoriteCountries 라는 상태를 따로 지니고 있기에 countries를 변경하는 것보다 아래에서 filter만 해주는 로직으로 변경하는 것이 어떨지 제안 드립니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 이것도 아주 사소한 거지만 ㅎㅎ
isDone 보다 isFavorite 이 알기 쉬울것 같아용ㅎㅎ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 동일합니다! |
@@ -0,0 +1,18 @@
+import CountryList from "../components/CountryList";
+
+const Home = () => {
+ return (
+ <>
+ <h1 className="flex justify-center items-center mt-8 mb-8 text-2xl font-bold">
+ Favorite Countries
+ </h1>
+ <CountryList isDone={true} />
+ <h1 className="flex justify-center items-center mb-8 text-3xl font-bold">
+ Countries
+ </h1>
+ <CountryList isDone={false} />
+ </>
+ );
+};
+
+export default Home; | Unknown | h1이 너무 많습니다! 페이지에 하나만 존재해야합니다.
하지만 코드에서도 혼란을 야기할 수 있는 헤딩태그를 지양하는 것을 제안드립니다 :) |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ return response.data;
+ } catch (error) {
+ throw new Error();
+ }
+}; | TypeScript | 제가 이번에 스스로 써본건 처음이라 잘 몰랐는데 은님 코드 보면서 깨달았습니다 감삼댜 |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 아마 공부를 위해서 하신 듯 합니다만..!
zustand 스토어에 countries 와 favoriteCountries 가 있고 실제로
```javascript
const isDoneCountries = isDone ? favoriteCountries : countries;
```
이런 부분에서도 useQuery 의 data 를 따로 쓰지는 않으니, 이런 경우라면 tanstack을 안쓰는 방향도 있을 것 같습니다~
물론 공부용이기 때문에 무시하셔도 됩니다 ^^;; |
@@ -0,0 +1,28 @@
+import { Country } from "../types/country";
+
+const CountryCard = ({
+ country,
+ handleToggleCountry,
+}: {
+ country: Country;
+ handleToggleCountry: (country: Country) => void;
+}) => {
+ return (
+ <div
+ className="flex flex-col border rounded gap-2 px-4"
+ onClick={() => handleToggleCountry(country)}
+ >
+ <div className="flex justify-center mb-2">
+ <img
+ src={country.flags.svg}
+ alt={`${country.name.common} flag`}
+ className="w-32 h-20"
+ />
+ </div>
+ <h2>{country.name.common}</h2>
+ <p>{country.capital}</p>
+ </div>
+ );
+};
+
+export default CountryCard; | Unknown | 아 그냥..h1밑에 하위로 있다 생각해서 아무 생각없이 h2를 쓴겁니다.. 그렇군여.. html css에 대해서 따로 공부를 안하고 필요할 때마다 그냥 그 때 그때 쓰다보니 이런 부분이 아직 많이 미흡한듯하네여 후... |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 오오 같은 생각입니다~~ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 맞는 말씀입니다 훨씬 좋겟군여 |
@@ -0,0 +1,18 @@
+import CountryList from "../components/CountryList";
+
+const Home = () => {
+ return (
+ <>
+ <h1 className="flex justify-center items-center mt-8 mb-8 text-2xl font-bold">
+ Favorite Countries
+ </h1>
+ <CountryList isDone={true} />
+ <h1 className="flex justify-center items-center mb-8 text-3xl font-bold">
+ Countries
+ </h1>
+ <CountryList isDone={false} />
+ </>
+ );
+};
+
+export default Home; | Unknown | h1태그는 페이지당 1개만 써야하는지 몰랐네여... 명심하겠습니당 |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ return response.data;
+ } catch (error) {
+ throw new Error();
+ }
+}; | TypeScript | 주의 :: 타입스크립트 잘 몰라서 이상한 소리일 수 있습니다 ㅠ
getCountires 함수의 반환값이 Promise<Country[]>임을 명시해주고 계시는 것 같습니다.
저는 이번 API 구조가 복잡해서인지 무슨 에러였는지 자세히 기억은 안 나지만 에러를 계속 겪었습니다~!
try문 안에서 get 요청 부분을 보면 응답값의 타입 지정이 안 되어 있는데, 저는 이 부분에서 문제를 해결할 수 있었던 것으로 기억합니다!
`const response = await countryApi.get<Country[]>("/all");`
예를 들어서 data.wonyoung.common 이라는 필드는 API 응답값에 있지도 않은데 입력해서 휴먼 에러가 발생한 경우,
함수의 반환값에만 타입을 지정해주면 그냥 이 문제를 스킵하는데, 통신의 응답값에도 타입을 지정해주면 컴파일 단계에서 에러에 막히는 것으로 이해했는데 제대로 이해한 건지는 잘 모르겠네요! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 홈페이지 관련해서 적어주신 것처럼 태그 이름을 바꾸는게 좋다는 말씀이신가요? |
@@ -0,0 +1,28 @@
+import { Country } from "../types/country";
+
+const CountryCard = ({
+ country,
+ handleToggleCountry,
+}: {
+ country: Country;
+ handleToggleCountry: (country: Country) => void;
+}) => {
+ return (
+ <div
+ className="flex flex-col border rounded gap-2 px-4"
+ onClick={() => handleToggleCountry(country)}
+ >
+ <div className="flex justify-center mb-2">
+ <img
+ src={country.flags.svg}
+ alt={`${country.name.common} flag`}
+ className="w-32 h-20"
+ />
+ </div>
+ <h2>{country.name.common}</h2>
+ <p>{country.capital}</p>
+ </div>
+ );
+};
+
+export default CountryCard; | Unknown | 참고:
- https://techblog.woowahan.com/15541/
- https://webactually.com/2020/03/03/%3Csection%3E%EC%9D%84-%EB%B2%84%EB%A6%AC%EA%B3%A0-HTML5-%3Carticle%3E%EC%9D%84-%EC%8D%A8%EC%95%BC-%ED%95%98%EB%8A%94-%EC%9D%B4%EC%9C%A0/ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 그 생각은 못해봤는데 동일한 결과가...나오는지 해보겠습니다 ㅎㅎ... 한번의 동작으로 아 조건문을 개선하면 되겠군여! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 이건 제가 뭐 말씀하시는지 잘 몰라서...학습하겠습니다 ㅠ.. |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 이 부분은 home.tsx에서는 전체적인 UI 및 페이지 관련만 나타내고 List에서 Card를 핸들링 할 수 있도록 생각을 해서 로직을 구현했는데 이런 핸들링 로직은 home.tsx가 더 적절하단 말씀이실까여?? |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ return response.data;
+ } catch (error) {
+ throw new Error();
+ }
+}; | TypeScript | 아 그렇군여! 저는 일단 js하듯이 작성 한 후에 strict모드가 설정 되어있으니 ts에서 새로 발생한 오류에 맞춰 수정했어가지고 반환값만 명시하고 오류가 사라졌길래 그 부분은 미처 생각을 못했습니다.
아무래도 모든 값에 정확한 타입을 명시하는건 저도 해야겠다 생각했는데 감사합니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | prop 타입을 인라인으로 정의한 이유가 있는지 궁금합니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 아...원래 data로 mpa을 돌렸었는데...;; 이게 isDone값을 꼭 써보려고 노력하다보니 어쩌다 그렇게 되었습니다 ㅠㅠ... 말씀대로 지금 쿼리가 초기값 넣어주는거말고 딱히 안쓰이긴합니다.. |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList = ({ isDone }: { isDone: boolean }) => {
+ const { countries, setCountries, favoriteCountries, setFavoriteCountries } =
+ useCountryStore();
+
+ const { data, error, isLoading } = useQuery({
+ queryKey: ["countries"],
+ queryFn: getCountries,
+ });
+
+ const handleToggleCountry = (country: Country) => {
+ if (isDone) {
+ setFavoriteCountries(
+ favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3)
+ );
+ setCountries([country, ...countries]);
+ } else {
+ setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3));
+ setFavoriteCountries([country, ...favoriteCountries]);
+ }
+ };
+
+ useEffect(() => {
+ if (data) {
+ setCountries(data);
+ }
+ }, [data, setCountries]);
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">로딩중입니다!!</h1>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex justify-center items-center">
+ <h1 className="text-4xl">에러가 발생했습니다!</h1>
+ </div>
+ );
+ }
+
+ const isDoneCountries = isDone ? favoriteCountries : countries;
+
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8">
+ {isDoneCountries.map((country) => (
+ <CountryCard
+ key={country.cca3}
+ country={country}
+ handleToggleCountry={handleToggleCountry}
+ />
+ ))}
+ </div>
+ );
+};
+
+export default CountryList; | Unknown | 저도 궁금합니다..!!! |
@@ -0,0 +1,84 @@
+export interface Country {
+ name: {
+ common: string;
+ official: string;
+ nativeName: {
+ [key: string]: {
+ official: string;
+ common: string;
+ };
+ };
+ };
+ tld: string[];
+ cca2: string;
+ ccn3: string;
+ cca3: string;
+ cioc: string;
+ independent: boolean;
+ status: string;
+ unMember: boolean;
+ currencies: {
+ [key: string]: {
+ name: string;
+ symbol: string;
+ };
+ };
+ idd: {
+ root: string;
+ suffixes: string[];
+ };
+ capital: string[];
+ altSpellings: string[];
+ region: string;
+ subregion: string;
+ languages: {
+ [key: string]: string;
+ };
+ translations: {
+ [key: string]: {
+ official: string;
+ common: string;
+ };
+ };
+ latlng: number[];
+ landlocked: boolean;
+ area: number;
+ demonyms: {
+ eng: {
+ f: string;
+ m: string;
+ };
+ };
+ flag: string;
+ maps: {
+ googleMaps: string;
+ openStreetMaps: string;
+ };
+ population: number;
+ gini: {
+ [key: string]: number;
+ };
+ fifa: string;
+ car: {
+ signs: string[];
+ side: string;
+ };
+ timezones: string[];
+ continents: string[];
+ flags: {
+ png: string;
+ svg: string;
+ };
+ coatOfArms: {
+ png?: string;
+ svg?: string;
+ };
+ startOfWeek: string;
+ capitalInfo: {
+ latlng: number[];
+ };
+ postalCode: {
+ format: string;
+ regex: string;
+ };
+} | TypeScript | 저도 사실 모든 데이터를 다 보지 않았지만, 몇몇 데이터는 선택적으로 들어오는 것 같더라구요..!! 그래서 모든 데이터에 다 들어오는 것이 아니라면 옵셔널을 붙여주면 좋을 것 같습니다..!! |
@@ -0,0 +1,185 @@
+package pairmatching.controller;
+
+import java.util.function.Function;
+import org.mockito.internal.util.Supplier;
+import pairmatching.enums.Course;
+import pairmatching.enums.Crew;
+import pairmatching.enums.Functions;
+import pairmatching.enums.Level;
+import pairmatching.enums.Missions;
+import pairmatching.enums.ShortAnswer;
+import pairmatching.model.MatchingRecord;
+import pairmatching.model.Pairs;
+import pairmatching.view.InputView;
+import pairmatching.view.OutputView;
+import pairmatching.view.error.ErrorException;
+
+public class PairMatchingController {
+
+ private static final String COMMA = "\\s*,\\s*";
+ private static final String EXIT = "exit";
+ public static final int MAX_TRY_COUNT = 3;
+
+ private InputView inputView;
+ private OutputView outputView;
+ private Crew backend;
+ private Crew frontend;
+ private MatchingRecord backendRecord;
+ private MatchingRecord frontendRecord;
+
+
+ public PairMatchingController(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.backend = new Crew(Course.BACKEND);
+ this.frontend = new Crew(Course.FRONTEND);
+ this.backendRecord = new MatchingRecord();
+ this.frontendRecord = new MatchingRecord();
+ }
+
+ public void matchingSystemRun() {
+ while (true) {
+ try {
+ String input = getValidInput(inputView::displayStartMessage, Functions::getValidFunction);
+ executeWithInput(input);
+ } catch (IllegalArgumentException e) {
+ if (e.getMessage().equals(EXIT)) {
+ return;
+ }
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private void executeWithInput(String input) throws IllegalArgumentException {
+ if (Functions.isEquals(input, Functions.QUIT)) {
+ performFunctions(input, inputView);
+ }
+ if (!Functions.isEquals(input, Functions.QUIT)) {
+ throw new IllegalArgumentException(EXIT);
+ }
+ }
+
+ private void performFunctions(String input, InputView inputView) throws ErrorException {
+ executePairMatching(input, inputView);
+ executePairInquiry(input, inputView);
+ executePairInitialization(input);
+ }
+
+ private void executePairMatching(String input, InputView inputView) throws ErrorException {
+ if (Functions.isEquals(input, Functions.MATCH_PAIRS)) {
+ String[] matchingCriteria = parseInput(inputView);
+ String course = Course.isCourse(matchingCriteria[0]);
+ Level level = Level.getLevel(matchingCriteria[1]);
+ Missions mission = Missions.getValidMission(level, matchingCriteria[2]);
+
+ matchDistinctPairs(course, mission);
+ }
+ }
+
+ private void executePairInquiry(String input, InputView inputView) throws ErrorException {
+ if (Functions.isEquals(input, Functions.PAIR_INQUIRY)) {
+ String[] matchingCriteria = parseInput(inputView);
+
+ String course = Course.isCourse(matchingCriteria[0]);
+ Level level = Level.getLevel(matchingCriteria[1]);
+ Missions mission = Missions.getValidMission(level, matchingCriteria[2]);
+ MatchingRecord record = getRecordThroughCourse(course);
+ Pairs matchedPairs = record.getRecordThroughMission(mission);
+ matchedPairs.display();
+ }
+ }
+
+ private void executePairInitialization(String input) {
+ if (Functions.isEquals(input, Functions.INITIALIZE_PAIR)) {
+ backendRecord.clear();
+ frontendRecord.clear();
+ outputView.displayReset();
+ }
+ }
+
+ private String[] parseInput(InputView inputView) {
+ String matchingCriteria = inputView.enteredChoices();
+ return matchingCriteria.split(COMMA);
+ }
+
+ private void matchDistinctPairs(String course, Missions mission) {
+ MatchingRecord record = getRecordThroughCourse(course);
+ if (record.containPreviousMatching(mission)) {
+ rematching(course, mission, record);
+ return;
+ }
+ handleNewMatching(course, mission, record);
+ }
+
+ private void rematching(String course, Missions mission, MatchingRecord record) {
+ String input = getValidInput(inputView::enteredRematching, ShortAnswer::getValidAnswer);
+ if (ShortAnswer.isEquals(input, ShortAnswer.YES)) {
+ Pairs matchedPairs = matchingPairs(course);
+ record.replace(mission, matchedPairs);
+ }
+ }
+
+ private void handleNewMatching(String course, Missions mission, MatchingRecord record) {
+ int count = 0;
+ while (true) {
+ Pairs matchedPairs = matchingPairs(course);
+ if (record.containTheSamePairInTheSameLevel(mission, matchedPairs)) {
+ count = handleRetry(count);
+ continue;
+ }
+ record.add(mission, matchedPairs);
+ break;
+ }
+ }
+
+ private int handleRetry(int count) {
+ count++;
+ overTryCount(count);
+ return count;
+ }
+
+ private void overTryCount(int count) throws ErrorException {
+ if (count >= MAX_TRY_COUNT) {
+ throw new ErrorException("매칭 시도 횟수가 3회를 초과했습니다.");
+ }
+ }
+
+ private Pairs matchingPairs(String course) {
+ Crew crew = getCrewThroughCourse(course);
+ Pairs matchedPairs = crew.matchPairs();
+ displayMatchedPairs(matchedPairs);
+ return matchedPairs;
+ }
+
+ private Crew getCrewThroughCourse(String course) {
+ if (Course.isEquals(course, Course.BACKEND)) {
+ return backend;
+ }
+ return frontend;
+ }
+
+ private MatchingRecord getRecordThroughCourse(String course) {
+ if (Course.isEquals(course, Course.BACKEND)) {
+ return backendRecord;
+ }
+ return frontendRecord;
+ }
+
+ private void displayMatchedPairs(Pairs matchedPairs) {
+ outputView.displayPairMatchingResult();
+ matchedPairs.display();
+ }
+
+ private <T> T getValidInput(Supplier<String> inputSupplier, Function<String, T> converter) {
+ while (true) {
+ String input = inputSupplier.get();
+ try {
+ return converter.apply(input);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+} | Java | ```suggestion
if (Functions.isEquals(input, Functions.QUIT)) {
performFunctions(input, inputView);
return
}
```
사소한거지만 return을 사용한다면 아래에 if문을 안만들고 처리할 수 있었을 거 같아요 |
@@ -0,0 +1,34 @@
+package pairmatching.model;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class Pairs {
+
+ private Map<String, List<String>> pairs;
+
+ public Pairs(Map<String, List<String>> pair){
+ this.pairs = pair;
+ }
+
+ public Set<Map.Entry<String, List<String>>> entrySet(){
+ return pairs.entrySet();
+ }
+
+ public void display() {
+ for (String key : pairs.keySet()) {
+ String value = null;
+ if(pairs.get(key).size() == 2){
+ value = pairs.get(key).get(0);
+ value += " : ";
+ value += pairs.get(key).get(1);
+ }
+ if(pairs.get(key).size() == 1){
+ value = String.valueOf(pairs.get(key).get(0));
+ }
+ System.out.println(key+" : "+ value);
+ }
+ }
+
+} | Java | for-each와 string Joiner를 써서 해결했어도 됐을거 같아요! |
@@ -54,11 +54,20 @@ export const REVIEW_GROUP_API_PARAMS = {
},
};
+export const WRITTEN_REVIEW_PARAMS = {
+ resource: 'reviews/authored',
+ queryString: {
+ lastReviewId: 'lastReviewId',
+ size: 'size',
+ },
+};
+
export const REVIEW_WRITING_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_WRITING_API_PARAMS.resource}`;
export const REVIEW_LIST_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_LIST_API_PARAMS.resource}`;
export const DETAILED_REVIEW_API_URL = `${serverUrl}/${VERSION2}/${DETAILED_REVIEW_API_PARAMS.resource}`;
export const REVIEW_GROUP_DATA_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_GROUP_DATA_API_PARAMS.resource}`;
export const REVIEW_GROUP_API_URL = `${serverUrl}/${VERSION2}/reviews/gather`;
+export const WRITTEN_REVIEW_LIST_API_URL = `${serverUrl}/${VERSION2}/${WRITTEN_REVIEW_PARAMS.resource}`;
const endPoint = {
postingReview: `${serverUrl}/${VERSION2}/reviews`,
@@ -80,6 +89,13 @@ const endPoint = {
gettingGroupedReviews: (sectionId: number) =>
`${REVIEW_GROUP_API_URL}?${REVIEW_GROUP_API_PARAMS.queryString.sectionId}=${sectionId}`,
postingHighlight: `${serverUrl}/${VERSION2}/highlight`,
+
+ gettingWrittenReviewList: (lastReviewId: number | null, size: number) => {
+ const defaultEndpoint = `${WRITTEN_REVIEW_LIST_API_URL}?${WRITTEN_REVIEW_PARAMS.queryString.size}=${size}`;
+
+ if (!lastReviewId) defaultEndpoint;
+ return defaultEndpoint + '&' + `${WRITTEN_REVIEW_PARAMS.queryString.lastReviewId}=${lastReviewId}`;
+ },
};
export default endPoint; | TypeScript | ```suggestion
if (!lastReviewId) return defaultEndpoint;
return defaultEndpoint + '&' + `${WRITTEN_REVIEW_PARAMS.queryString.lastReviewId}=${lastReviewId}`;
},
```
이런 구조로 바꾸면 lastReviewId가 없을 때 endpoint 값을 파악하는데 더 쉬울 것 같네요 |
@@ -6,11 +6,17 @@ import {
GroupedSection,
GroupedReviews,
ReviewInfoData,
+ WrittenReviewList,
} from '@/types';
import createApiErrorMessage from './apiErrorMessageCreator';
import endPoint from './endpoints';
+export interface GetInfiniteReviewListApiParams {
+ lastReviewId: number | null;
+ size: number;
+}
+
export const getDataToWriteReviewApi = async (reviewRequestCode: string) => {
const response = await fetch(endPoint.gettingDataToWriteReview(reviewRequestCode), {
method: 'GET',
@@ -58,11 +64,11 @@ export const getReviewInfoDataApi = async () => {
return data as ReviewInfoData;
};
-interface GetDetailedReviewApi {
+interface GetDetailedReviewApiParams {
reviewId: number;
}
// 상세 리뷰
-export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApi) => {
+export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApiParams) => {
const response = await fetch(endPoint.gettingDetailedReview(reviewId), {
method: 'GET',
headers: {
@@ -79,12 +85,7 @@ export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApi) =
return data as DetailReviewData;
};
-interface GetReviewListApi {
- lastReviewId: number | null;
- size: number;
-}
-
-export const getReviewListApi = async ({ lastReviewId, size }: GetReviewListApi) => {
+export const getReviewListApi = async ({ lastReviewId, size }: GetInfiniteReviewListApiParams) => {
const response = await fetch(endPoint.gettingReviewList(lastReviewId, size), {
method: 'GET',
headers: {
@@ -138,3 +139,20 @@ export const getGroupedReviews = async ({ sectionId }: GetGroupedReviewsProps) =
const data = await response.json();
return data as GroupedReviews;
};
+
+export const getWrittenReviewList = async ({ lastReviewId, size }: GetInfiniteReviewListApiParams) => {
+ const response = await fetch(endPoint.gettingWrittenReviewList(lastReviewId, size), {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'include',
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as WrittenReviewList;
+}; | TypeScript | 함수의 파라미터 타입이라서, 저는 이럴 때 타입명 뒤에 params를 추가하는 편이에요. |
@@ -0,0 +1,78 @@
+import { useMemo } from 'react';
+
+import { useGetDetailedReview, useReviewId } from '@/hooks';
+import { substituteString } from '@/utils';
+
+import QuestionAnswerSection from './QuestionAnswerSection';
+import ReviewDescription from './ReviewDescription';
+import * as S from './styles';
+
+interface DetailedReviewProps {
+ $layoutStyle?: React.CSSProperties;
+ selectedReviewId?: number;
+}
+
+const DetailedReview = ({ selectedReviewId, $layoutStyle }: DetailedReviewProps) => {
+ const reviewId = useReviewId(selectedReviewId);
+
+ const { data: detailedReview } = useGetDetailedReview({
+ reviewId: reviewId,
+ });
+
+ const parsedDetailedReview = useMemo(() => {
+ return {
+ ...detailedReview,
+ sections: detailedReview.sections.map((section) => {
+ const newHeader = substituteString({
+ content: section.header,
+ variables: { revieweeName: detailedReview.revieweeName, projectName: detailedReview.projectName },
+ });
+
+ const newQuestions = section.questions.map((question) => {
+ const newContent = substituteString({
+ content: question.content,
+ variables: { revieweeName: detailedReview.revieweeName, projectName: detailedReview.projectName },
+ });
+
+ return {
+ ...question,
+ content: newContent,
+ };
+ });
+
+ return {
+ ...section,
+ header: newHeader,
+ questions: newQuestions,
+ };
+ }),
+ };
+ }, [detailedReview]);
+
+ return (
+ <S.DetailedReview $layoutStyle={$layoutStyle}>
+ <ReviewDescription
+ projectName={parsedDetailedReview.projectName}
+ date={new Date(parsedDetailedReview.createdAt)}
+ revieweeName={parsedDetailedReview.revieweeName}
+ />
+ <S.Separator />
+ <S.DetailedReviewContainer>
+ {parsedDetailedReview.sections.map((section) =>
+ section.questions.map((question) => (
+ <S.ReviewContentContainer key={question.questionId}>
+ <QuestionAnswerSection
+ question={question.content}
+ questionType={question.questionType}
+ answer={question.answer}
+ options={question.optionGroup?.options}
+ />
+ </S.ReviewContentContainer>
+ )),
+ )}
+ </S.DetailedReviewContainer>
+ </S.DetailedReview>
+ );
+};
+
+export default DetailedReview; | Unknown | sections 관련된 부분 코드가 길어서, header와 questions를 분리하고 각각 useMemo를 사용하는 것은 어떨까요'? |
@@ -6,11 +6,17 @@ import {
GroupedSection,
GroupedReviews,
ReviewInfoData,
+ WrittenReviewList,
} from '@/types';
import createApiErrorMessage from './apiErrorMessageCreator';
import endPoint from './endpoints';
+export interface GetInfiniteReviewListApiParams {
+ lastReviewId: number | null;
+ size: number;
+}
+
export const getDataToWriteReviewApi = async (reviewRequestCode: string) => {
const response = await fetch(endPoint.gettingDataToWriteReview(reviewRequestCode), {
method: 'GET',
@@ -58,11 +64,11 @@ export const getReviewInfoDataApi = async () => {
return data as ReviewInfoData;
};
-interface GetDetailedReviewApi {
+interface GetDetailedReviewApiParams {
reviewId: number;
}
// 상세 리뷰
-export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApi) => {
+export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApiParams) => {
const response = await fetch(endPoint.gettingDetailedReview(reviewId), {
method: 'GET',
headers: {
@@ -79,12 +85,7 @@ export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApi) =
return data as DetailReviewData;
};
-interface GetReviewListApi {
- lastReviewId: number | null;
- size: number;
-}
-
-export const getReviewListApi = async ({ lastReviewId, size }: GetReviewListApi) => {
+export const getReviewListApi = async ({ lastReviewId, size }: GetInfiniteReviewListApiParams) => {
const response = await fetch(endPoint.gettingReviewList(lastReviewId, size), {
method: 'GET',
headers: {
@@ -138,3 +139,20 @@ export const getGroupedReviews = async ({ sectionId }: GetGroupedReviewsProps) =
const data = await response.json();
return data as GroupedReviews;
};
+
+export const getWrittenReviewList = async ({ lastReviewId, size }: GetInfiniteReviewListApiParams) => {
+ const response = await fetch(endPoint.gettingWrittenReviewList(lastReviewId, size), {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'include',
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as WrittenReviewList;
+}; | TypeScript | 아이고 놓쳤네요 😅 추가할게요! |
@@ -0,0 +1,78 @@
+import { useMemo } from 'react';
+
+import { useGetDetailedReview, useReviewId } from '@/hooks';
+import { substituteString } from '@/utils';
+
+import QuestionAnswerSection from './QuestionAnswerSection';
+import ReviewDescription from './ReviewDescription';
+import * as S from './styles';
+
+interface DetailedReviewProps {
+ $layoutStyle?: React.CSSProperties;
+ selectedReviewId?: number;
+}
+
+const DetailedReview = ({ selectedReviewId, $layoutStyle }: DetailedReviewProps) => {
+ const reviewId = useReviewId(selectedReviewId);
+
+ const { data: detailedReview } = useGetDetailedReview({
+ reviewId: reviewId,
+ });
+
+ const parsedDetailedReview = useMemo(() => {
+ return {
+ ...detailedReview,
+ sections: detailedReview.sections.map((section) => {
+ const newHeader = substituteString({
+ content: section.header,
+ variables: { revieweeName: detailedReview.revieweeName, projectName: detailedReview.projectName },
+ });
+
+ const newQuestions = section.questions.map((question) => {
+ const newContent = substituteString({
+ content: question.content,
+ variables: { revieweeName: detailedReview.revieweeName, projectName: detailedReview.projectName },
+ });
+
+ return {
+ ...question,
+ content: newContent,
+ };
+ });
+
+ return {
+ ...section,
+ header: newHeader,
+ questions: newQuestions,
+ };
+ }),
+ };
+ }, [detailedReview]);
+
+ return (
+ <S.DetailedReview $layoutStyle={$layoutStyle}>
+ <ReviewDescription
+ projectName={parsedDetailedReview.projectName}
+ date={new Date(parsedDetailedReview.createdAt)}
+ revieweeName={parsedDetailedReview.revieweeName}
+ />
+ <S.Separator />
+ <S.DetailedReviewContainer>
+ {parsedDetailedReview.sections.map((section) =>
+ section.questions.map((question) => (
+ <S.ReviewContentContainer key={question.questionId}>
+ <QuestionAnswerSection
+ question={question.content}
+ questionType={question.questionType}
+ answer={question.answer}
+ options={question.optionGroup?.options}
+ />
+ </S.ReviewContentContainer>
+ )),
+ )}
+ </S.DetailedReviewContainer>
+ </S.DetailedReview>
+ );
+};
+
+export default DetailedReview; | Unknown | 만약 이 컴포넌트를 리팩토링한다면 저는 useMemo를 아예 뺄 것 같아요. 이점에 비해 코드가 복잡해지는 단점이 큰 것 같아서요. 제거하는 방향에 대해서는 어떻게 생각하시나요?
1. 리뷰는 수정 불가능하므로 리뷰이 이름 문자열 치환도 1번만 일어남
2. `substituteString`은 useMemo를 사용할 만큼 비싼 동작이 아님
3. 1과 같은 맥락에서, 어차피 리뷰는 갱신되지 않기 때문에 유저도 리뷰 상세 페이지를 계속 새로고침해서 리렌더링을 추가로 트리거할 것 같지 않음 |
@@ -0,0 +1,89 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+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() {
+ List<Store> store = printProductList();
+ List<Promotion> promotions = loadPromotions();
+ Order order;
+
+ do {
+ order = purchaseProduct(store);
+ priceCalculator(store, order, promotions);
+
+ } while (!checkEnd(store, order));
+ }
+
+ private boolean checkEnd(List<Store> store, Order order) {
+ while (true) {
+ try {
+ if (!storeService.isAnswer(inputView.inputEndMessage())) {
+ return true;
+ }
+ updateStore(store, order);
+ return false;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void updateStore(List<Store> store, Order order) {
+ storeService.checkStock(store, order);
+ outputView.printProductList(store);
+ }
+
+ private void priceCalculator(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = storeService.parseReceipt(store, order, promotions);
+ storeService.checkTribeQuantity(receipts, store);
+ storeService.checkTribePromotion(receipts, store);
+ int discount = storeService.membershipDiscount(receipts);
+
+ outputView.printReceipt(receipts, discount);
+ }
+
+ private List<Store> printProductList() {
+ List<Store> store = new ArrayList<>();
+ storeService.loadProductsForm(store);
+ outputView.printProductList(store);
+ return store;
+ }
+
+ private List<Promotion> loadPromotions() {
+ List<Promotion> promotions = new ArrayList<>();
+ storeService.loadPromotionsForm(promotions);
+ return promotions;
+ }
+
+ private Order purchaseProduct(List<Store> store) {
+ while (true) {
+ try {
+ String inputOrder = inputView.inputPurchaseProduct();
+ Order order = new Order(inputOrder);
+ storeService.checkProduct(store, order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | order를 do 내부에서 선언하는 것이 더 깔끔하지 않을까 생각이 드네요..!
checkEnd() 내부의 updateStore() 를 do 구문 내부로 이동시킨다면 가능할 것 같습니다..! |
@@ -0,0 +1,59 @@
+package store.model;
+
+import static store.utils.ErrorMessage.INVALID_FORMAT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Order {
+ private List<Product> order;
+
+ public Order(String inputOrder) {
+ validateProductFormat(inputOrder);
+ this.order = generateProducts(inputOrder);
+ }
+
+ public List<Product> generateProducts(String inputOrder) {
+ List<Product> products = new ArrayList<>();
+ String[] orders = inputOrder.split("],\\[");
+
+ for (String order : orders) {
+ String formatOrder = order.replace("[", "").replace("]", "");
+ int quantityIndex = formatOrder.lastIndexOf('-') + 1;
+
+ String name = formatOrder.substring(0, quantityIndex - 1).trim();
+ String quantity = formatOrder.substring(quantityIndex).trim();
+
+ products.add(new Product(name, quantity));
+ }
+ return products;
+ }
+
+ private void validateProductFormat(String inputOrder) {
+ String[] orderList = inputOrder.split(",");
+
+ for (String order : orderList) {
+ if (!isValidProductEntry(order.trim())) {
+ throw new IllegalArgumentException(INVALID_FORMAT);
+ }
+ }
+ }
+
+ private boolean isValidProductEntry(String order) {
+ if (!order.startsWith("[") || !order.endsWith("]")) {
+ return false;
+ }
+
+ String part = order.substring(1, order.length() - 1);
+ String[] parts = part.split("-");
+ if (parts[0].isEmpty()) {
+ return false;
+ }
+
+ return parts.length == 2;
+ }
+
+ public List<Product> getOrder() {
+ return order;
+ }
+} | Java | replaceAll() 이라는 메서드로도 같은 기능을 구현할 수 있습니다!
이미 아실수도 있지만 혹시나 해서 말씀드립니다..! |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ private int get;
+ private String startDateStr;
+ private String endDateStr;
+
+ public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDateStr = startdateStr;
+ this.endDateStr = enddateStr;
+ }
+
+ public static Promotion parsePromotions(String line) {
+ List<String> promotion = Arrays.asList(line.split(","));
+
+ String name = promotion.get(0).trim();
+ int buy = Integer.parseInt(promotion.get(1).trim());
+ int get = Integer.parseInt(promotion.get(2).trim());
+ String start_date = promotion.get(3).trim();
+ String end_date = promotion.get(4).trim();
+
+ return new Promotion(name, buy, get, start_date, end_date);
+ }
+
+ public int checkPromotionDate() {
+ final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+
+ try {
+ Date startDate = DATE_FORMAT.parse(startDateStr);
+ Date endDate = DATE_FORMAT.parse(endDateStr);
+ Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now()));
+
+ if (!now.before(startDate) && !now.after(endDate)) {
+ return this.buy;
+ }
+ } catch (ParseException e) {
+ return 0;
+ }
+ return 0;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public String getStartDateStr() {
+ return startDateStr;
+ }
+
+ public String getEndDateStr() {
+ return endDateStr;
+ }
+} | Java | `now.after(startDate) && now.before(endDate)` 도 같은 의미인데
현재 코드처럼 작성하신 이유가 있으실까요?
궁금해서 질문드립니다..! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | 파일명을 상수로 사용한다면 더 좋을 것 같습니다! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | 리팩토링한다면 여기 상품의 수량을 구하는 부분을
하나의 메서드로 분리하시는 것도 좋겠네요 |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | 자바 파일 입출력에 여러 방법이 있는데 버퍼리드 형식을 사용하신 이유가 있으실까요?? |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | 해당 메서드는 서비스가 하는 기능 보다는 다른 클래스로 옮기는게 더 적합해보입니다..! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | 이 부분도 나중에 receiptservice로 분류하면 어떨까요..? |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | Math.min을 사용하시면 한줄로 만들수있을거같아요 |
@@ -0,0 +1,14 @@
+package store.utils;
+
+public class ErrorMessage {
+ public static final String ERROR = "[ERROR] ";
+ public static final String RETRY = " 다시 입력해 주세요.";
+ public static final String INVALID_FORMAT = " 올바르지 않은 형식으로 입력했습니다. ";
+ public static final String INVALID_NAME = " 존재하지 않는 상품입니다.";
+ public static final String INVALID_QUANTITY = "재고 수량을 초과하여 구매할 수 없습니다.";
+ public static final String INVALID_INPUT = "잘못된 입력입니다.";
+
+ private ErrorMessage() {
+
+ }
+} | Java | enum을 사용하지 않고 class로 분리한 이유가 궁금합니다 |
@@ -0,0 +1,89 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+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() {
+ List<Store> store = printProductList();
+ List<Promotion> promotions = loadPromotions();
+ Order order;
+
+ do {
+ order = purchaseProduct(store);
+ priceCalculator(store, order, promotions);
+
+ } while (!checkEnd(store, order));
+ }
+
+ private boolean checkEnd(List<Store> store, Order order) {
+ while (true) {
+ try {
+ if (!storeService.isAnswer(inputView.inputEndMessage())) {
+ return true;
+ }
+ updateStore(store, order);
+ return false;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void updateStore(List<Store> store, Order order) {
+ storeService.checkStock(store, order);
+ outputView.printProductList(store);
+ }
+
+ private void priceCalculator(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = storeService.parseReceipt(store, order, promotions);
+ storeService.checkTribeQuantity(receipts, store);
+ storeService.checkTribePromotion(receipts, store);
+ int discount = storeService.membershipDiscount(receipts);
+
+ outputView.printReceipt(receipts, discount);
+ }
+
+ private List<Store> printProductList() {
+ List<Store> store = new ArrayList<>();
+ storeService.loadProductsForm(store);
+ outputView.printProductList(store);
+ return store;
+ }
+
+ private List<Promotion> loadPromotions() {
+ List<Promotion> promotions = new ArrayList<>();
+ storeService.loadPromotionsForm(promotions);
+ return promotions;
+ }
+
+ private Order purchaseProduct(List<Store> store) {
+ while (true) {
+ try {
+ String inputOrder = inputView.inputPurchaseProduct();
+ Order order = new Order(inputOrder);
+ storeService.checkProduct(store, order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 함수명은 동사로 하는 건 어떨까요?? 예를 들어 `calculatePrice` 처럼 말이죠!! |
@@ -0,0 +1,91 @@
+package store.model;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class Store {
+ private final String name;
+ private int price;
+ private int quantity;
+ private String promotion;
+
+ public Store(String name, int price, int quantity, String promotion) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotion = promotion;
+ }
+
+ public static Store parseStore(String line) {
+ List<String> product = Arrays.asList(line.split(","));
+
+ String name = product.get(0).trim();
+ int price = Integer.parseInt(product.get(1).trim());
+ int quantity = Integer.parseInt(product.get(2).trim());
+ String promotion = checkPromotion(product.get(3));
+
+ return new Store(name, price, quantity, promotion);
+ }
+
+ private static String checkPromotion(String promotion) {
+ if (promotion.equals("null")) {
+ return "";
+ }
+ return promotion.trim();
+ }
+
+ public static void checkNotPromotionProduct(List<Store> store, String line) {
+ if (store.isEmpty()) {
+ return;
+ }
+
+ Store product = store.getLast();
+ if (!line.contains(product.getName()) && !product.getPromotion().isEmpty()) {
+ store.add(new Store(product.getName(), product.getPrice(), 0, ""));
+ }
+ }
+
+ public int deduction(int orderQuantity) {
+ int value = 0;
+ quantity -= orderQuantity;
+
+ if (quantity < 0) {
+ value = Math.abs(quantity);
+ quantity = 0;
+ }
+ return value;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPromotion() {
+ return promotion;
+ }
+
+ @Override
+ public String toString() {
+ String formatPrice = String.format("%,d", price);
+ if (quantity == 0) {
+ return "- " +
+ name + " " +
+ formatPrice + "원 " +
+ "재고 없음" +
+ promotion;
+ }
+ return "- " +
+ name + " " +
+ formatPrice + "원 " +
+ quantity + "개 " +
+ promotion;
+ }
+} | Java | 각각의 인덱스가 어떤 것을 의미하는지 상수화 했으면 더 좋았을 것 같습니다!!! |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ private int get;
+ private String startDateStr;
+ private String endDateStr;
+
+ public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDateStr = startdateStr;
+ this.endDateStr = enddateStr;
+ }
+
+ public static Promotion parsePromotions(String line) {
+ List<String> promotion = Arrays.asList(line.split(","));
+
+ String name = promotion.get(0).trim();
+ int buy = Integer.parseInt(promotion.get(1).trim());
+ int get = Integer.parseInt(promotion.get(2).trim());
+ String start_date = promotion.get(3).trim();
+ String end_date = promotion.get(4).trim();
+
+ return new Promotion(name, buy, get, start_date, end_date);
+ }
+
+ public int checkPromotionDate() {
+ final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+
+ try {
+ Date startDate = DATE_FORMAT.parse(startDateStr);
+ Date endDate = DATE_FORMAT.parse(endDateStr);
+ Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now()));
+
+ if (!now.before(startDate) && !now.after(endDate)) {
+ return this.buy;
+ }
+ } catch (ParseException e) {
+ return 0;
+ }
+ return 0;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public String getStartDateStr() {
+ return startDateStr;
+ }
+
+ public String getEndDateStr() {
+ return endDateStr;
+ }
+} | Java | 문자열을 프로모션으로 파싱하는 역할을 파싱하는 객체를 만들어서 거기로 넘기는건 어떨까요!! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | answer을 enum 상수로 만드는 것은 어떨까요? |
@@ -0,0 +1,59 @@
+package store.model;
+
+import static store.utils.ErrorMessage.INVALID_FORMAT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Order {
+ private List<Product> order;
+
+ public Order(String inputOrder) {
+ validateProductFormat(inputOrder);
+ this.order = generateProducts(inputOrder);
+ }
+
+ public List<Product> generateProducts(String inputOrder) {
+ List<Product> products = new ArrayList<>();
+ String[] orders = inputOrder.split("],\\[");
+
+ for (String order : orders) {
+ String formatOrder = order.replace("[", "").replace("]", "");
+ int quantityIndex = formatOrder.lastIndexOf('-') + 1;
+
+ String name = formatOrder.substring(0, quantityIndex - 1).trim();
+ String quantity = formatOrder.substring(quantityIndex).trim();
+
+ products.add(new Product(name, quantity));
+ }
+ return products;
+ }
+
+ private void validateProductFormat(String inputOrder) {
+ String[] orderList = inputOrder.split(",");
+
+ for (String order : orderList) {
+ if (!isValidProductEntry(order.trim())) {
+ throw new IllegalArgumentException(INVALID_FORMAT);
+ }
+ }
+ }
+
+ private boolean isValidProductEntry(String order) {
+ if (!order.startsWith("[") || !order.endsWith("]")) {
+ return false;
+ }
+
+ String part = order.substring(1, order.length() - 1);
+ String[] parts = part.split("-");
+ if (parts[0].isEmpty()) {
+ return false;
+ }
+
+ return parts.length == 2;
+ }
+
+ public List<Product> getOrder() {
+ return order;
+ }
+} | Java | 개인적으로 위의 앞 뒤 [ ] 확인하는 부분과 빈문자열인지 확인하는 로직을 분리해도 될 것 같습니다! |
@@ -0,0 +1,50 @@
+package store.model;
+
+public class Receipt {
+ private String name;
+ private int individualPrice;
+ private int quantity;
+ private int promotionQuantity;
+ private int promotionBuy;
+
+ public Receipt(String name, int individualPrice, int quantity, int promotionBuy) {
+ this.name = name;
+ this.individualPrice = individualPrice;
+ this.quantity = quantity;
+ this.promotionBuy = promotionBuy;
+ }
+
+ public void addPromotion() {
+ quantity++;
+ }
+
+ public void removeNonPromotion(int nomDiscountableQuantity) {
+ quantity -= nomDiscountableQuantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getIndividualPrice() {
+ return individualPrice;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getPromotionQuantity() {
+ return promotionQuantity;
+ }
+
+ public int getPromotionBuy() {
+ return promotionBuy;
+ }
+
+ public void setPromotionQuantity(int promotionQuantity) {
+ this.promotionQuantity = promotionQuantity;
+ }
+}
+
+ | Java | 이번 과제에서 게터 사용을 줄이기가 쉽지 않아, 저도 결국 사용할 수밖에 없었습니다ㅜㅜ
게터를 사용하면 객체의 캡슐화를 위반할 위험이 있고, 객체의 상태를 외부에서 쉽게 변경할 수 있게 되어 객체의 책임이 외부로 밀려날 수 있기 때문에 지양해야 한다고 알고 있습니다.
그래서 앞으로 게터 사용을 줄이기 위해 DTO를 활용해보는 것도 좋은 방법이 될 것 같습니다! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | 서비스에서 View를 호출하는건 개인적으로 layered architecture구조상 적합하지 않다고 생각됩니다!
Layered architecture는 관심사별로 계층을 나눈 구조로 알고 있습니다. Presentation Layer 는 사용자와의 상호작용을 담당하는 역할, business Layer 는 비지니스 로직만 담당하는 역할입니다. 따라서 View 객체들은 presentation layer 에 속한다고 볼 수 있습니다.
하지만 현재 코드를 보면 business layer 가 presentation layer 를 의존하는 것으로 보이는데, 이렇게 되면 business layer에 presentation layer의 코드가 노출되기때문에, 관심사가 분리되지 않았다고 볼 수 있습니다. |
@@ -0,0 +1,86 @@
+package store.view;
+
+import static store.utils.ErrorMessage.ERROR;
+import static store.utils.ErrorMessage.RETRY;
+
+import java.util.List;
+import store.model.Receipt;
+import store.model.Store;
+
+public class OutputView {
+ private static final String ERROR_ANSWER = "[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.";
+
+ private final String WECOME_MESSAGE = "안녕하세요. W편의점입니다.\n현재 보유하고 있는 상품입니다.\n";
+ private final String RESULT_START_MESSAGE = "\n==============W 편의점================";
+ private final String RESULT_MESSAGE = "%-16s\t%-5s\t%s\n";
+ private final String ORDER_LIST = "%-16s\t%-7d\t%,d\n";
+ private final String PROMOTION_MESSAGE = "=============증 정===============";
+ private final String PROMOTION_LIST = "%-16s\t%,-5d\n";
+ private final String LINE = "====================================";
+
+
+ public void printError(String errorMessage) {
+ System.out.println(ERROR + errorMessage + RETRY);
+ }
+
+ public static void printErrorAnswer() {
+ System.out.println(ERROR_ANSWER);
+ }
+
+ public void printProductList(List<Store> products) {
+ System.out.println(WECOME_MESSAGE);
+
+ for (Store product : products) {
+ System.out.println(product);
+ }
+ }
+
+ public void printReceipt(List<Receipt> receipts, int discount) {
+ System.out.println(RESULT_START_MESSAGE);
+ System.out.printf(RESULT_MESSAGE, "상품명", "수량", "금액");
+ int totalOrderPrice = printOrder(receipts);
+
+ System.out.println(PROMOTION_MESSAGE);
+ int totalPromotionPrice = printPromotion(receipts);
+
+ System.out.println(LINE);
+ printPaymentPrice(receipts, totalOrderPrice, totalPromotionPrice, discount);
+ }
+
+ private int printOrder(List<Receipt> receipts) {
+ int totalOrder = 0;
+
+ for (Receipt receipt : receipts) {
+ int price = receipt.getIndividualPrice() * receipt.getQuantity();
+ totalOrder += price;
+ System.out.printf(ORDER_LIST, receipt.getName(), receipt.getQuantity(), price);
+ }
+
+ return totalOrder;
+ }
+
+ private int printPromotion(List<Receipt> receipts) {
+ int totalPromotion = 0;
+
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionQuantity() != 0) {
+ int price = receipt.getIndividualPrice() * (receipt.getPromotionQuantity() / (receipt.getPromotionBuy() + 1));
+ totalPromotion += price;
+ System.out.printf(PROMOTION_LIST, receipt.getName(), receipt.getPromotionQuantity() / (receipt.getPromotionBuy() + 1));
+ }
+ }
+
+ return totalPromotion;
+ }
+
+ private void printPaymentPrice(List<Receipt> receipts, int totalOrder, int totalPromotion, int discount) {
+ int totalQuantity = 0;
+ for (Receipt receipt : receipts) {
+ totalQuantity += receipt.getQuantity();
+ }
+ System.out.printf("%-16s\t%-7d\t%,-7d\n", "총구매액", totalQuantity, totalOrder);
+ System.out.printf("%-23s\t-%,d\n", "행사할인", totalPromotion);
+ System.out.printf("%-23s\t-%,d\n", "멤버십할인", discount);
+ System.out.printf("%-23s\t%,d\n", "내실돈", (totalOrder - totalPromotion - discount));
+ }
+}
\ No newline at end of file | Java | 이 부분을 상수로 처리하지 않은 이유가 있을까요? |
@@ -0,0 +1,89 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+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() {
+ List<Store> store = printProductList();
+ List<Promotion> promotions = loadPromotions();
+ Order order;
+
+ do {
+ order = purchaseProduct(store);
+ priceCalculator(store, order, promotions);
+
+ } while (!checkEnd(store, order));
+ }
+
+ private boolean checkEnd(List<Store> store, Order order) {
+ while (true) {
+ try {
+ if (!storeService.isAnswer(inputView.inputEndMessage())) {
+ return true;
+ }
+ updateStore(store, order);
+ return false;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void updateStore(List<Store> store, Order order) {
+ storeService.checkStock(store, order);
+ outputView.printProductList(store);
+ }
+
+ private void priceCalculator(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = storeService.parseReceipt(store, order, promotions);
+ storeService.checkTribeQuantity(receipts, store);
+ storeService.checkTribePromotion(receipts, store);
+ int discount = storeService.membershipDiscount(receipts);
+
+ outputView.printReceipt(receipts, discount);
+ }
+
+ private List<Store> printProductList() {
+ List<Store> store = new ArrayList<>();
+ storeService.loadProductsForm(store);
+ outputView.printProductList(store);
+ return store;
+ }
+
+ private List<Promotion> loadPromotions() {
+ List<Promotion> promotions = new ArrayList<>();
+ storeService.loadPromotionsForm(promotions);
+ return promotions;
+ }
+
+ private Order purchaseProduct(List<Store> store) {
+ while (true) {
+ try {
+ String inputOrder = inputView.inputPurchaseProduct();
+ Order order = new Order(inputOrder);
+ storeService.checkProduct(store, order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | do while문을 처음 사용해서 잘 몰랐는데 안에서 선언하는 방법은 생각도 못했네요 배워갑니다! |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ private int get;
+ private String startDateStr;
+ private String endDateStr;
+
+ public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDateStr = startdateStr;
+ this.endDateStr = enddateStr;
+ }
+
+ public static Promotion parsePromotions(String line) {
+ List<String> promotion = Arrays.asList(line.split(","));
+
+ String name = promotion.get(0).trim();
+ int buy = Integer.parseInt(promotion.get(1).trim());
+ int get = Integer.parseInt(promotion.get(2).trim());
+ String start_date = promotion.get(3).trim();
+ String end_date = promotion.get(4).trim();
+
+ return new Promotion(name, buy, get, start_date, end_date);
+ }
+
+ public int checkPromotionDate() {
+ final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+
+ try {
+ Date startDate = DATE_FORMAT.parse(startDateStr);
+ Date endDate = DATE_FORMAT.parse(endDateStr);
+ Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now()));
+
+ if (!now.before(startDate) && !now.after(endDate)) {
+ return this.buy;
+ }
+ } catch (ParseException e) {
+ return 0;
+ }
+ return 0;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public String getStartDateStr() {
+ return startDateStr;
+ }
+
+ public String getEndDateStr() {
+ return endDateStr;
+ }
+} | Java | 가독성이 더 좋다고 생각되는 방향으로 작성했습니다 |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | readLine() 을 사용하여 한 줄씩 읽기 좋다고 생각하여 사용했습니다 |
@@ -0,0 +1,14 @@
+package store.utils;
+
+public class ErrorMessage {
+ public static final String ERROR = "[ERROR] ";
+ public static final String RETRY = " 다시 입력해 주세요.";
+ public static final String INVALID_FORMAT = " 올바르지 않은 형식으로 입력했습니다. ";
+ public static final String INVALID_NAME = " 존재하지 않는 상품입니다.";
+ public static final String INVALID_QUANTITY = "재고 수량을 초과하여 구매할 수 없습니다.";
+ public static final String INVALID_INPUT = "잘못된 입력입니다.";
+
+ private ErrorMessage() {
+
+ }
+} | Java | 값들을 그룹화 하여 사용하지 않고 단순 메세지 출력이기에 상수 클래스로 해도 좋을 것 같다고 생각했습니다 |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ private int get;
+ private String startDateStr;
+ private String endDateStr;
+
+ public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDateStr = startdateStr;
+ this.endDateStr = enddateStr;
+ }
+
+ public static Promotion parsePromotions(String line) {
+ List<String> promotion = Arrays.asList(line.split(","));
+
+ String name = promotion.get(0).trim();
+ int buy = Integer.parseInt(promotion.get(1).trim());
+ int get = Integer.parseInt(promotion.get(2).trim());
+ String start_date = promotion.get(3).trim();
+ String end_date = promotion.get(4).trim();
+
+ return new Promotion(name, buy, get, start_date, end_date);
+ }
+
+ public int checkPromotionDate() {
+ final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+
+ try {
+ Date startDate = DATE_FORMAT.parse(startDateStr);
+ Date endDate = DATE_FORMAT.parse(endDateStr);
+ Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now()));
+
+ if (!now.before(startDate) && !now.after(endDate)) {
+ return this.buy;
+ }
+ } catch (ParseException e) {
+ return 0;
+ }
+ return 0;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public String getStartDateStr() {
+ return startDateStr;
+ }
+
+ public String getEndDateStr() {
+ return endDateStr;
+ }
+} | Java | 역할 분리를 좀 더 상세히 해야 될 것 같네요.. 참고하겠습니다! |
@@ -0,0 +1,50 @@
+package store.model;
+
+public class Receipt {
+ private String name;
+ private int individualPrice;
+ private int quantity;
+ private int promotionQuantity;
+ private int promotionBuy;
+
+ public Receipt(String name, int individualPrice, int quantity, int promotionBuy) {
+ this.name = name;
+ this.individualPrice = individualPrice;
+ this.quantity = quantity;
+ this.promotionBuy = promotionBuy;
+ }
+
+ public void addPromotion() {
+ quantity++;
+ }
+
+ public void removeNonPromotion(int nomDiscountableQuantity) {
+ quantity -= nomDiscountableQuantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getIndividualPrice() {
+ return individualPrice;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getPromotionQuantity() {
+ return promotionQuantity;
+ }
+
+ public int getPromotionBuy() {
+ return promotionBuy;
+ }
+
+ public void setPromotionQuantity(int promotionQuantity) {
+ this.promotionQuantity = promotionQuantity;
+ }
+}
+
+ | Java | 말씀하신 내용 듣고 제 코드를 다시 살펴보니, 객체내에서는 단순히 데이터만 담아두고 게터 사용으로 대부분 외부에서 로직을 처리하여 객체지향의 의미를 잃은 코드를 작성한 것 같습니다...
구현하는데 너무 급급했던거같네요ㅠㅠ 피드백 감사합니다 |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Product;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreService {
+ private static final int NON_PROMOTION = 0;
+ private static final int GET = 1;
+ private static final int MAX_MEMBERSHIP = 8000;
+
+ public void loadProductsForm(List<Store> store) {
+ try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ addProduct(store, line);
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ public void loadPromotionsForm(List<Promotion> promotions) {
+ try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader(
+ new InputStreamReader(in))) {
+ String line = br.readLine();
+
+ while ((line = br.readLine()) != null) {
+ promotions.add(parsePromotions(line));
+ }
+ } catch (IOException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private void addProduct(List<Store> store, String line) {
+ checkNotPromotionProduct(store, line);
+ store.add(parseStore(line));
+ }
+
+ public void checkProduct(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ checkName(store, product);
+ checkQuantity(store, product);
+ }
+ }
+
+ private void checkName(List<Store> store, Product product) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ return;
+ }
+ }
+
+ throw new IllegalArgumentException(INVALID_NAME);
+ }
+
+ private void checkQuantity(List<Store> store, Product product) {
+ int quantity = 0;
+
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ quantity += storeProduct.getQuantity();
+ }
+ }
+
+ if (quantity < product.getQuantity()) {
+ throw new IllegalArgumentException(INVALID_QUANTITY);
+ }
+ }
+
+ public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+
+ for (Product product : order.getOrder()) {
+ String name = product.getName();
+ int indivialPrice = getPrice(store, product.getName());
+ int quantity = product.getQuantity();
+ int promotinBuy = checkPromotionProduct(store, product, promotions);
+ receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy));
+ }
+ return receipts;
+ }
+
+ private int getPrice(List<Store> store, String productName) {
+ int price = 0;
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(productName)) {
+ price = storeProduct.getPrice();
+ }
+ }
+
+ return price;
+ }
+
+ private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) {
+ for (Store storeProduct : store) {
+ if (storeProduct.getName().equals(product.getName())) {
+ if (storeProduct.getQuantity() == 0) {
+ return 0;
+ }
+ return getPromotion(storeProduct.getPromotion(), promotions);
+ }
+ }
+
+ return 0;
+ }
+
+ private int getPromotion(String promotion, List<Promotion> promotions) {
+ for (Promotion promotionType : promotions) {
+ if (promotionType.getName().equals(promotion)) {
+ return promotionType.checkPromotionDate();
+ }
+ }
+ return 0;
+ }
+
+ public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkPromotionQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkPromotionQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkNonGet(receipt, storeProduct.getQuantity());
+ break;
+ }
+ }
+ }
+
+ private void checkNonGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) {
+ if (isGet(receipt, storeQuantity)) {
+ receipt.addPromotion();
+ }
+ }
+ }
+
+ private boolean isGet(Receipt receipt, int storeQuantity) {
+ if (receipt.getQuantity() + GET <= storeQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.getFree(receipt.getName()));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+ return false;
+ }
+
+ public void checkTribePromotion(List<Receipt> receipts, List<Store> store) {
+ for (Receipt receipt : receipts) {
+ if (receipt.getPromotionBuy() != NON_PROMOTION) {
+ checkStoreQuantity(receipt, store);
+ }
+ }
+ }
+
+ private void checkStoreQuantity(Receipt receipt, List<Store> store) {
+ for (Store storeProduct : store) {
+ if (receipt.getName().equals(storeProduct.getName())) {
+ checkOverGet(receipt, storeProduct);
+ break;
+ }
+ }
+ }
+
+ private void checkOverGet(Receipt receipt, Store storeProduct) {
+ int promotionProductQuantity = storeProduct.getQuantity()
+ - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET);
+
+ int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity;
+
+ if (nomDiscountableQuantity > 0) {
+ if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) {
+ receipt.removeNonPromotion(nomDiscountableQuantity);
+ }
+ receipt.setPromotionQuantity(promotionProductQuantity);
+ return;
+ }
+ receipt.setPromotionQuantity(
+ receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1));
+ }
+
+ private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) {
+ while (true) {
+ try {
+ return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity));
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ public int membershipDiscount(List<Receipt> receipts) {
+ int totalPrice = 0;
+ int promotionPrice = 0;
+
+ if (isMembership()) {
+ for (Receipt receipt : receipts) {
+ totalPrice += receipt.getIndividualPrice() * receipt.getQuantity();
+ promotionPrice += checkPromotionPrice(receipt);
+ }
+ }
+
+ return checkDisCount(totalPrice, promotionPrice);
+ }
+
+ private boolean isMembership() {
+ while (true) {
+ try {
+ return isAnswer(InputView.membershipMessage());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorAnswer();
+ }
+ }
+ }
+
+ private int checkPromotionPrice(Receipt receipt) {
+ return receipt.getIndividualPrice() * receipt.getPromotionQuantity();
+ }
+
+ private int checkDisCount(int totalPrice, int promotionPrice) {
+ int disCount = (int) ((totalPrice - promotionPrice) * 0.3);
+ if (disCount > MAX_MEMBERSHIP) {
+ return MAX_MEMBERSHIP;
+ }
+
+ return disCount;
+ }
+
+ public boolean isAnswer(String answer) {
+ if (answer.equals("Y")) {
+ return true;
+ }
+ if (answer.equals("N")) {
+ return false;
+ }
+
+ throw new IllegalArgumentException(INVALID_INPUT);
+ }
+
+ public void checkStock(List<Store> store, Order order) {
+ for (Product product : order.getOrder()) {
+ handleProductDeduction(store, product);
+ }
+ }
+
+ private void handleProductDeduction(List<Store> store, Product product) {
+ Store matchedStoreProduct = findStoreProduct(store, product.getName());
+
+ int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity());
+ if (remainingQuantity > 0) {
+ applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity);
+ }
+ }
+
+ private Store findStoreProduct(List<Store> store, String productName) {
+ return store.stream()
+ .filter(storeProduct -> storeProduct.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) {
+ for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) {
+ remainingQuantity = store.get(i).deduction(remainingQuantity);
+ }
+ }
+
+} | Java | OutputView 클래스에서 유일하게 작성한 스태틱 메서드 입니다.
저도 구현하는 과정에서 옳지 않다고 생각했지만,
비즈니스 로직을 처리하는 과정에서 옳지 않은 입력이 왔을 때 outputView 객체를 참조 할 방법이 떠오르지 않아 이렇게 작성하게 됐습니다..
적합하지 않은 이유를 상세하게 말씀해 주셔서 새롭게 하나 더 배워갑니다 감사합니다..! |
@@ -0,0 +1,16 @@
+package store.constant;
+
+public enum CommonMessage {
+ YES("Y"),
+ NO("N");
+ private final String commonMessage;
+
+ CommonMessage(final String commonMessage) {
+ this.commonMessage = commonMessage;
+ }
+
+ public String getCommonMessage() {
+ return commonMessage;
+ }
+
+} | Java | 입력이 둘뿐인 경우에 대해서 Enum으로 관리하는 것도 좋은 방법인 것 같아요! |
@@ -0,0 +1,22 @@
+package store.constant;
+
+public enum FileMessage {
+ PRODUCTS_FILE_NAME("products.md"),
+ PROMOTION_FILE_NAME("promotions.md"),
+ NULL("null"),
+ SOFT_DRINK("탄산2+1"),
+ MD_RECOMMEND_PRODUCT("MD추천상품"),
+ FLASH_DISCOUNT("반짝할인"),
+ FILE_START_WORD("name");
+
+ private final String fileMessage;
+
+ FileMessage(final String fileMessage) {
+ this.fileMessage = fileMessage;
+ }
+
+ public String getFileMessage() {
+ return fileMessage;
+ }
+
+} | Java | 파일에 있는 프로모션 데이터를 Enum으로 관리하는건 좋지 않은 것 같습니다
프로모션 종류가 3개 고정이 아니라 각기 다른 수백 개, 수천 개로 늘어날 수 있을 것 같아요! |
@@ -0,0 +1,71 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+
+public class Receipt {
+ private final double THIRTY_PERCENT = 0.3;
+ private final List<ReceiptItem> receiptItems = new ArrayList<>();
+
+ public void addItem(ReceiptItem receiptItem) {
+ receiptItems.add(receiptItem);
+ }
+
+ public List<ReceiptItem> getReceiptItems() {
+ return receiptItems;
+ }
+
+ public int totalPurchaseAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice();
+ }
+ return sum;
+ }
+
+ public int totalPromotionDiscount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getGetQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ public int getTotalPurchaseCount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity();
+ }
+ return sum;
+ }
+
+ public int validateMembership(String userAnswer) {
+ if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) {
+ return getMembershipDiscount();
+ }
+ return CommonValue.ZERO.getValue();
+ }
+
+ private int noTotalPromotionAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getBuyQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ private int getMembershipDiscount() {
+ int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT);
+ if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) {
+ membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue();
+ }
+ return membershipDiscount;
+ }
+
+} | Java | model의 역할을 수행하는 클래스로 보이는데 패키지를 분리하지 않고, domain 패키지에 같이 두신 이유가 있을까요? |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | `userMembership()`에서 멤버십 할인 여부에 따라 최종 계산 금액에서 30% 할인이 되고 있는데,
요구사항에서는 프로모션 상품을 제외한 일반 상품으로 결제된 상품들에 대해서만 멤버십 할인이 되어야 한다고 명시되어 있습니다
이 부분이 처리되지 않은 것 같습니다! |
@@ -0,0 +1,19 @@
+package store.constant;
+
+public enum CommonValue {
+ ZERO(0),
+ ONE(1),
+ TWO(2),
+ EIGHT_THOUSAND(8000);
+
+ private final int value;
+
+ CommonValue(final int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+} | Java | 상수들을 enum으로 잘 관리해주셨는데요!
저는 개인적으로 enum의 값을 꺼내기 위해 `.getValue()` 까지 붙는게 조금 지저분해보입니다.
static 상수의 경우 `Constant.ZERO` 이런식으로 사용할 수 있지만 enum은 `CommonValue.ZERO.getValue()` 로 1depth 더 늘어나는 느낌이랄까요..? |
@@ -0,0 +1,71 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+
+public class Receipt {
+ private final double THIRTY_PERCENT = 0.3;
+ private final List<ReceiptItem> receiptItems = new ArrayList<>();
+
+ public void addItem(ReceiptItem receiptItem) {
+ receiptItems.add(receiptItem);
+ }
+
+ public List<ReceiptItem> getReceiptItems() {
+ return receiptItems;
+ }
+
+ public int totalPurchaseAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice();
+ }
+ return sum;
+ }
+
+ public int totalPromotionDiscount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getGetQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ public int getTotalPurchaseCount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity();
+ }
+ return sum;
+ }
+
+ public int validateMembership(String userAnswer) {
+ if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) {
+ return getMembershipDiscount();
+ }
+ return CommonValue.ZERO.getValue();
+ }
+
+ private int noTotalPromotionAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getBuyQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ private int getMembershipDiscount() {
+ int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT);
+ if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) {
+ membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue();
+ }
+ return membershipDiscount;
+ }
+
+} | Java | int를 double과 곱한 뒤 int로 형변환을 하고 있는데요!
double로 계산되는 과정에서 부동소수점 오류를 피할 수 없을 것으로 보입니다. 이때는 `* 30 / 100` 으로 계산해서 아예 소수점이 안생기도록 계산하시는 것은 어떨까요? |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | 저는 MVC 패턴에 Service 계층을 추가해서 책임 분리에 애먹었었는데, Service가 없으니 좀 더 자연스럽게 데이터 전달이 이루어지네요..!! |
@@ -0,0 +1,141 @@
+package store.view.output;
+
+import java.util.List;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.ReceiptItem;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+
+public class OutputView {
+
+ public void writeStorageStatus(Storage storage) {
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ System.out.println(OutputMessage.WELCOME_MESSAGE.getOutputMessage());
+ System.out.println(OutputMessage.SHOW_CURRENT_ITEMS.getOutputMessage());
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ writeInitPromotionProducts(storage);
+ writeInitOnlyGeneralProducts(storage);
+ }
+
+ public void writeReceipt(Receipt receipt, String userAnswer) {
+ writeReceiptMenuHeader();
+ writeReceiptMenuName(receipt);
+ writePresentation(receipt);
+ System.out.println(OutputMessage.PERFORATION_LINE.getOutputMessage());
+ writeUserTotalReceipt(receipt, userAnswer);
+ }
+
+ private void writeUserTotalReceipt(Receipt receipt, String userAnswer) {
+ writeShowTotalPurchaseAmount(receipt);
+ writeShowTotalPromotionDiscountAmount(receipt);
+ writeShowTotalMembershipDiscountAmount(receipt, userAnswer);
+ writeShowTotalPaymentAmount(receipt, userAnswer);
+ }
+
+ private void writeShowTotalPaymentAmount(Receipt receipt, String userAnswer) {
+ String nameAndPrice = String.format(OutputMessage.SHOW_PAYMENT_FORMAT.getOutputMessage(), "내실돈",
+ String.format("%,d", receipt.totalPurchaseAmount() - receipt.totalPromotionDiscount() -
+ receipt.validateMembership(userAnswer)));
+ System.out.println(nameAndPrice);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+
+ private void writeShowTotalMembershipDiscountAmount(Receipt receipt, String userAnswer) {
+ String name = String.format("%-14s", "멤버십할인").replace(" ", "\u3000");
+ String price = String.format("-%,d", receipt.validateMembership(userAnswer));
+ System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private void writeShowTotalPromotionDiscountAmount(Receipt receipt) {
+ String name = String.format("%-14s", "행사할인").replace(" ", "\u3000");
+ String price = String.format("-%,d", receipt.totalPromotionDiscount());
+ System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private void writeShowTotalPurchaseAmount(Receipt receipt) {
+ String name = String.format("%-14s", "총구매액").replace(" ", "\u3000");
+ String quantity = String.format("%-10d", receipt.getTotalPurchaseCount());
+ String price = String.format("%,-10d", receipt.totalPurchaseAmount());
+ System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private void writePresentation(Receipt receipt) {
+ System.out.println(OutputMessage.SHOW_RECEIPT_PRESENTATION_HEADER.getOutputMessage());
+ for (ReceiptItem receiptItem : receipt.getReceiptItems()) {
+ if (receiptItem.getGetQuantity() != 0) {
+ String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000");
+ String quantity = String.format("%,-10d", receiptItem.getGetQuantity());
+ System.out.printf(OutputMessage.SHOW_PRESENTATION_FORMAT.getOutputMessage(), name, quantity);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+ }
+ }
+
+ private void writeReceiptMenuName(Receipt receipt) {
+ System.out.println(OutputMessage.SHOW_RECEIPT_MENU_NAME.getOutputMessage());
+ for (ReceiptItem receiptItem : receipt.getReceiptItems()) {
+ String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000");
+ String quantity = String.format("%-10d", receiptItem.getTotalBuyQuantity());
+ String price = String.format("%,-10d", receiptItem.getPrice() * receiptItem.getTotalBuyQuantity());
+ System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+ }
+
+ private void writeReceiptMenuHeader() {
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ System.out.println(OutputMessage.SHOW_RECEIPT_HEADER.getOutputMessage());
+ }
+
+
+ private void writeInitPromotionProducts(Storage storage) {
+ for (PromotionProduct promotionProduct : storage.getPromotionProducts()) {
+ System.out.println(promotionProduct);
+ findEqualGeneralProductName(storage.getGeneralProducts(), promotionProduct.getName());
+ }
+ }
+
+ private void findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) {
+ for (GeneralProduct generalProduct : generalProducts) {
+ if (generalProduct.getName().equals(name)) {
+ System.out.println(generalProduct);
+ break;
+ }
+ }
+ }
+
+ private void writeInitOnlyGeneralProducts(Storage storage) {
+ for (GeneralProduct generalProduct : storage.getGeneralProducts()) {
+ String generalProductName = generalProduct.getName();
+ boolean flag = findEqualPromotionProductName(storage.getPromotionProducts(), generalProductName);
+ writeOnlyGeneralProduct(flag, generalProduct);
+ }
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private boolean findEqualPromotionProductName(List<PromotionProduct> promotionProducts, String name) {
+ for (PromotionProduct promotionProduct : promotionProducts) {
+ if (promotionProduct.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void writeOnlyGeneralProduct(boolean flag, GeneralProduct generalProduct) {
+ if (!flag) {
+ System.out.println(generalProduct.toString());
+ }
+ }
+
+ public void displayErrorMessage(ConvenienceStoreException convenienceStoreException) {
+ System.out.println(convenienceStoreException.getMessage());
+ }
+
+} | Java | 프로모션 상품이 소진되고 나서 프로모션 상품도 재고 없음으로 출력되는데,
사용자는 프로모션 상품을 구매할 수 없으므로 아예 노출시키지 않는 것도 좋을 것 같아요!
UX쪽으로도 한번 고민해보시면 좋을 것 같습니다🙂 |
@@ -0,0 +1,38 @@
+package store.domain;
+
+public class GeneralProduct {
+ private final String name;
+ private final String price;
+ private int quantity;
+
+ public GeneralProduct(final String name, final String price, final int quantity) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPrice() {
+ return price;
+ }
+
+ public void subtraction(int value) {
+ this.quantity -= Math.abs(value);
+ }
+
+ @Override
+ public String toString() {
+ if (quantity == 0) {
+ return String.format("- %s %,d원 재고 없음", name, Integer.parseInt(price));
+ }
+ return String.format("- %s %,d원 %s개", name, Integer.parseInt(price), quantity);
+ }
+
+} | Java | 개인적인 궁금증으로 여쭤봅니다
`price`를 `String` 으로 관리하신 특별한 이유가 있으실까요? |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | `HYPHEN`이나 `ZERO` 같이 이름 자체가 의미를 직관적으로 담고 있는 경우는
enum보다 일반 클래스를 사용해서 `getValue()`메서드를 사용하지 않는 편이 조금 더 깔끔하지 않을까요..? |
@@ -0,0 +1,40 @@
+package store.domain;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final String startDate, final String endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = LocalDate.parse(startDate);
+ this.endDate = LocalDate.parse(endDate);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public boolean isActive(LocalDateTime dateTime) {
+ LocalDate date = dateTime.toLocalDate();
+ return (date.isEqual(startDate) || date.isAfter(startDate)) &&
+ (date.isEqual(endDate) || date.isBefore(endDate));
+ }
+
+}
+ | Java | 조건부가 길다보니까 날짜가 기간에 포함되는지 확인하는 메서드를 구현하는 것도 나쁘지 않다고 생각이 들었습니다
```
boolean isBetween(LocalDate date) {
return !date.isBefore(startDate) && !date.isAfter(endDate);
}
``` |
@@ -0,0 +1,83 @@
+package store.domain;
+
+import java.util.Collections;
+import java.util.List;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.exception.ConvenienceStoreException;
+import store.exception.ErrorMessage;
+
+public class Storage {
+ private final List<GeneralProduct> generalProducts;
+ private final List<PromotionProduct> promotionProducts;
+
+ public Storage(final List<GeneralProduct> generalProducts, final List<PromotionProduct> promotionProducts) {
+ this.generalProducts = generalProducts;
+ this.promotionProducts = promotionProducts;
+ }
+
+ public List<String> validateStorageStatus(List<String> purchaseProduct) {
+ for (String purchaseItem : purchaseProduct) {
+ List<String> item = List.of(purchaseItem.split(SignMessage.HYPHEN.getSign()));
+ validateItemName(item.get(CommonValue.ZERO.getValue()));
+ validateQuantity(item.get(CommonValue.ZERO.getValue()), item.get(CommonValue.ONE.getValue()));
+ }
+ return purchaseProduct;
+ }
+
+ public List<GeneralProduct> getGeneralProducts() {
+ return Collections.unmodifiableList(generalProducts);
+ }
+
+ public List<PromotionProduct> getPromotionProducts() {
+ return Collections.unmodifiableList(promotionProducts);
+ }
+
+ public GeneralProduct findGeneralProduct(String productName) {
+ return generalProducts.stream()
+ .filter(product -> product.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public PromotionProduct findPromotionProduct(String productName) {
+ return promotionProducts.stream()
+ .filter(product -> product.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void subtractPromotionProduct(PromotionProduct promotionProduct, int itemQuantity) {
+ promotionProduct.subtraction(itemQuantity);
+ }
+
+ public void subtractGeneralProduct(GeneralProduct generalProduct, int itemQuantity) {
+ generalProduct.subtraction(itemQuantity);
+ }
+
+ private void validateQuantity(String name, String quantity) {
+ if (getProductQuantity(name) < Integer.parseInt(quantity)) {
+ throw ConvenienceStoreException.from(ErrorMessage.STORAGE_OVER);
+ }
+ }
+
+ private int getProductQuantity(String name) {
+ PromotionProduct promotionProduct = findPromotionProduct(name);
+ int count = CommonValue.ZERO.getValue();
+ if (promotionProduct != null) {
+ count += promotionProduct.getQuantity();
+ }
+ return count + findGeneralProduct(name).getQuantity();
+ }
+
+ private void validateItemName(String name) {
+ if (!isProductInStorage(name)) {
+ throw ConvenienceStoreException.from(ErrorMessage.NON_EXISTENT_PRODUCT);
+ }
+ }
+
+ private boolean isProductInStorage(String productName) {
+ return generalProducts.stream().anyMatch(product -> product.getName().equals(productName));
+ }
+
+} | Java | `Unmodifiable Collection`을 사용하셔서
외부의 변형을 막으신 점 너무 좋습니다..! |
@@ -0,0 +1,114 @@
+package store.service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.FileMessage;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.Promotion;
+import store.domain.PromotionProduct;
+import store.domain.Storage;
+import store.utils.FileLoader;
+
+public class StorageService {
+ private static final String FILE_NOT_FOUND_ERROR = "[ERROR] 파일을 찾을 수 없습니다.";
+ private final List<String> productFile;
+ private final List<String> promotionFile;
+
+ public StorageService(final String productFileName, final String promotionFileName) {
+ this.productFile = loadFile(productFileName);
+ this.promotionFile = loadFile(promotionFileName);
+ }
+
+ public Storage initializeStorage() {
+ List<Promotion> promotions = generatePromotionData(promotionFile);
+ List<GeneralProduct> onlyGeneralProducts = findGeneralProduct(productFile);
+ List<PromotionProduct> onlyPromotionProducts = findPromotionProduct(productFile, promotions);
+ List<GeneralProduct> insertedGeneralProducts = insertOutOfStock(onlyPromotionProducts, onlyGeneralProducts);
+ return new Storage(insertedGeneralProducts, onlyPromotionProducts);
+ }
+
+ private List<String> loadFile(String fileName) {
+ try {
+ return FileLoader.fileReadLine(fileName);
+ } catch (IOException e) {
+ throw new IllegalArgumentException(FILE_NOT_FOUND_ERROR);
+ }
+ }
+
+ private List<Promotion> generatePromotionData(List<String> promotionFile) {
+ List<Promotion> promotions = new ArrayList<>();
+ for (String line : promotionFile) {
+ List<String> items = List.of(line.split(SignMessage.COMMA.getSign()));
+ promotions.add(new Promotion(items.get(0), Integer.parseInt(items.get(1)), Integer.parseInt(items.get(2)),
+ items.get(3), items.get(4)));
+ }
+ return promotions;
+ }
+
+ private List<GeneralProduct> insertOutOfStock(List<PromotionProduct> prItem, List<GeneralProduct> generalProducts) {
+ int idx = 0;
+ for (PromotionProduct product : prItem) {
+ if (findEqualGeneralProductName(generalProducts, product.getName())) {
+ idx += 1;
+ continue;
+ }
+ generalProducts.add(idx, new GeneralProduct(product.getName(), product.getPrice(), 0));
+ }
+ return generalProducts;
+ }
+
+
+ private boolean findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) {
+ for (GeneralProduct generalProduct : generalProducts) {
+ if (generalProduct.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private List<GeneralProduct> findGeneralProduct(List<String> getFile) {
+ List<GeneralProduct> onlyGeneralProducts = new ArrayList<>();
+ for (String itemDetails : getFile) {
+ if (itemDetails.contains(FileMessage.NULL.getFileMessage())) {
+ List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign()));
+ onlyGeneralProducts.add(new GeneralProduct(item.get(0), item.get(1), Integer.parseInt(item.get(2))));
+ }
+ }
+ return onlyGeneralProducts;
+ }
+
+ private List<PromotionProduct> findPromotionProduct(List<String> getFile, List<Promotion> promotions) {
+ List<PromotionProduct> onlyPromotionProducts = new ArrayList<>();
+ for (String itemDetails : getFile) {
+ if (isPromotionProduct(itemDetails)) {
+ addPromotionProduct(onlyPromotionProducts, itemDetails, promotions);
+ }
+ }
+ return onlyPromotionProducts;
+ }
+
+ private boolean isPromotionProduct(String itemDetails) {
+ return itemDetails.contains(FileMessage.SOFT_DRINK.getFileMessage())
+ || itemDetails.contains(FileMessage.MD_RECOMMEND_PRODUCT.getFileMessage())
+ || itemDetails.contains(FileMessage.FLASH_DISCOUNT.getFileMessage());
+ }
+
+ private void addPromotionProduct(List<PromotionProduct> products, String itemDetails, List<Promotion> promotions) {
+ List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign()));
+ String productName = item.get(0);
+ String productCategory = item.get(1);
+ int price = Integer.parseInt(item.get(2));
+ Promotion promotion = matchingPromotion(item.get(3), promotions);
+
+ products.add(new PromotionProduct(productName, productCategory, price, promotion));
+ }
+
+ private Promotion matchingPromotion(String promotionName, List<Promotion> promotions) {
+ return promotions.stream().filter(promotion -> promotion.getName().equals(promotionName)).findFirst()
+ .orElse(null);
+ }
+
+} | Java | 이 상수는 `ErrorMessage` 클래스에 포함되지 않은 이유가 혹시 있을까요? |
@@ -0,0 +1,16 @@
+package store.constant;
+
+public enum CommonMessage {
+ YES("Y"),
+ NO("N");
+ private final String commonMessage;
+
+ CommonMessage(final String commonMessage) {
+ this.commonMessage = commonMessage;
+ }
+
+ public String getCommonMessage() {
+ return commonMessage;
+ }
+
+} | Java | 감사합니다!
특정 범위의 값만 사용을 하니까 enum으로 사용해볼까? 생각해봤어요! |
@@ -0,0 +1,19 @@
+package store.constant;
+
+public enum CommonValue {
+ ZERO(0),
+ ONE(1),
+ TWO(2),
+ EIGHT_THOUSAND(8000);
+
+ private final int value;
+
+ CommonValue(final int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+} | Java | 사실 이 부분에 대해 고민을 많이 했습니다.
상수를 enum으로 관리할지 여부를 고민했던 이유는, 해당 상수들이 특정한 값의 범위에 속하지 않고, `==`을 통한 비교를 수행하는 부분도 없었기 때문입니다. 그래서 굳이 enum을 사용할 필요가 없다고 생각했습니다.
다만, 가독성 측면에서 코드를 명확하게 만들고자 enum을 선택했는데, 실제 사용 시 `CommonValue.ZERO.getValue()`처럼 접근하는 것이 코드가 길어지고 다소 불편하게 느껴질 수 있습니다.
이 점에서 보면, 말씀하신 대로 static 상수로 관리하는 것이 더 간결하고 직관적일 것 같습니다. |
@@ -0,0 +1,22 @@
+package store.constant;
+
+public enum FileMessage {
+ PRODUCTS_FILE_NAME("products.md"),
+ PROMOTION_FILE_NAME("promotions.md"),
+ NULL("null"),
+ SOFT_DRINK("탄산2+1"),
+ MD_RECOMMEND_PRODUCT("MD추천상품"),
+ FLASH_DISCOUNT("반짝할인"),
+ FILE_START_WORD("name");
+
+ private final String fileMessage;
+
+ FileMessage(final String fileMessage) {
+ this.fileMessage = fileMessage;
+ }
+
+ public String getFileMessage() {
+ return fileMessage;
+ }
+
+} | Java | 피드백 감사드립니다!
말씀해주신 대로, Enum은 주로 고정된 상수 값을 정의할 때 사용됩니다. 그런데 새로운 프로모션이 추가되거나 변경될 때마다 재컴파일해야 하는 불편함이 있을 것 같습니다.
이 부분은 제가 미처 고려하지 못했던 점인데, 지적해주셔서 감사드립니다! |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | 사실 Service 계층을 추가해서 책임을 분리하려고 했습니다.
커밋 기록을 보시면 아시겠지만, 마지막 날에 ReceiptService를 추가했습니다! 상품 관련 부분도 분리하려고 했는데, 시간이 부족해서 더 리팩토링하지 못한 점이 아쉽습니다 😅
그럼에도 좋게 봐주셔서 감사합니다! |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | 말씀해주신 내용을 확인해보았습니다!
제가 알고 있는 요구사항은, `[콜라-2]`, `[에너지바-1]`을 구매한 경우 1개 무료 증정을 받고, 멤버십을 적용한다면 에너지바 1개에 대해서만 멤버십 할인이 적용되는 것입니다.
마찬가지로, `[콜라-2]`개를 구매하고 무료 증정을 받지 않는다면, 콜라 2개에 대해서 멤버십 할인이 적용되는 것으로 이해하고 있습니다.
제 로직은 위와 같은 방식으로 동작하고 있습니다.
혹시 다른 요구사항이 있었다면 설명해 주실 수 있으신가요?
예를 들어, `[콜라-2]`, `[에너지바-1]`를 구매한 상황에서 콜라 1개를 무료 증정 받는 경우, 그리고 멤버십 할인이 적용되는 경우를 살펴보겠습니다.
`ReceiptItem`의 `getQuantity` 메서드에서 반환하는 값은 사용자가 무료로 증정받은 상품의 개수를 의미합니다.
`OutputView`의 `writeReceipt` 메서드에서는 `writeUserTotalReceipt()` 메서드를 마지막 라인에서 호출하며, 이 메서드에서 `writeShowTotalMembershipDiscountAmount()`를 통해 멤버십 할인 부분이 출력됩니다.
`Receipt` 클래스의 `validateMembership` 메서드를 보면, 사용자의 대답이 `Y`일 경우 `getMembershipDiscount()`를 호출하게 되어 있습니다.
`getMembershipDiscount` 메서드에서는 `noTotalPromotionAmount()`를 호출하는데, 이 메서드에서는 `receiptItem`의 `증정 개수가 0`일 경우에만 프로모션이 적용되지 않은 상품으로 판단하고, 이에 따라 멤버십 할인을 적용하기 위해 총 가격을 계산합니다.
따라서,` [콜라-2]`,` [에너지바-1]`을 구매하고, 멤버십 할인을 받을 경우, 에너지바 1개에 대해서만 멤버십 할인이 적용되는 로직입니다.
동일하게 `[콜라-2]`를 구매하고, 무료 증정 1개를 받지 않는다고 선택했을 경우, 멤버십 할인을 받을 때 콜라 2개 전체에 대해 멤버십 할인이 적용됩니다.
추가적으로 개선할 부분이 있다면 피드백 주시면 감사하겠습니다! 😊 |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | 말씀하신 부분에 동의합니다.
HYPHEN이나 ZERO와 같이 이름 자체가 의미를 직관적으로 담고 있는 경우, Enum보다는 일반 클래스를 사용하여 getValue() 메서드를 사용하지 않는 방식이 더 깔끔할 것 같아요!!
이렇게 하면 코드의 가독성이 높아지고, 불필요한 getValue() 호출을 피할 수 있어 더 직관적일 것 같습니다.
Enum은 보통 상태나 범위가 명확한 상수들을 정의할 때 적합한데, 이 경우에는 일반 클래스를 사용하는 것이 더 나을 것 같습니다.... |
@@ -0,0 +1,38 @@
+package store.domain;
+
+public class GeneralProduct {
+ private final String name;
+ private final String price;
+ private int quantity;
+
+ public GeneralProduct(final String name, final String price, final int quantity) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPrice() {
+ return price;
+ }
+
+ public void subtraction(int value) {
+ this.quantity -= Math.abs(value);
+ }
+
+ @Override
+ public String toString() {
+ if (quantity == 0) {
+ return String.format("- %s %,d원 재고 없음", name, Integer.parseInt(price));
+ }
+ return String.format("- %s %,d원 %s개", name, Integer.parseInt(price), quantity);
+ }
+
+} | Java | 아뇨.. 특별한 이유는 없었습니다
우선 문자열로 받은 후에 추후에 int형으로 수정하려고 하였는데 까먹고 놓친 것 같아요!
말씀해주셔서 감사드립니다! |
@@ -0,0 +1,40 @@
+package store.domain;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final String startDate, final String endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = LocalDate.parse(startDate);
+ this.endDate = LocalDate.parse(endDate);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ public boolean isActive(LocalDateTime dateTime) {
+ LocalDate date = dateTime.toLocalDate();
+ return (date.isEqual(startDate) || date.isAfter(startDate)) &&
+ (date.isEqual(endDate) || date.isBefore(endDate));
+ }
+
+}
+ | Java | 조건이 길어지다 보니, 날짜가 기간에 포함되는지 확인하는 메서드를 구현하는 것도 좋은 접근 같아요. `isBetween` 메서드를 사용하면 코드 가독성을 높이는 데 도움이 될 것 같네요! |
@@ -0,0 +1,71 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+
+public class Receipt {
+ private final double THIRTY_PERCENT = 0.3;
+ private final List<ReceiptItem> receiptItems = new ArrayList<>();
+
+ public void addItem(ReceiptItem receiptItem) {
+ receiptItems.add(receiptItem);
+ }
+
+ public List<ReceiptItem> getReceiptItems() {
+ return receiptItems;
+ }
+
+ public int totalPurchaseAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice();
+ }
+ return sum;
+ }
+
+ public int totalPromotionDiscount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getGetQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ public int getTotalPurchaseCount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity();
+ }
+ return sum;
+ }
+
+ public int validateMembership(String userAnswer) {
+ if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) {
+ return getMembershipDiscount();
+ }
+ return CommonValue.ZERO.getValue();
+ }
+
+ private int noTotalPromotionAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getBuyQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ private int getMembershipDiscount() {
+ int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT);
+ if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) {
+ membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue();
+ }
+ return membershipDiscount;
+ }
+
+} | Java | 좋은 질문 감사합니다!
Receipt 클래스를 domain 패키지에 두는 이유는 이 클래스가 애플리케이션의 핵심 도메인 로직을 처리하고 있기 때문입니다.
Receipt는 그 자체로 구매 내역을 다루고 이를 기반으로 비즈니스 로직을 처리하는 클래스이기 때문에 도메인 계층에 위치하는 것이 자연스럽다고 생각했습니다.
물론, model이라는 별도의 패키지를 두고 관리할 수도 있지만, 현재 구조에서는 domain 패키지가 애플리케이션의 주요 비즈니스 로직을 모두 포함하고 있어서, Receipt와 같은 클래스를 별도로 분리하지 않고 도메인 내에 포함시키는 것이 코드의 일관성을 유지하는 데 도움이 된다고 판단했습니다. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.