code stringlengths 41 34.3k | lang stringclasses 8 values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,45 @@
+package christmas.controller;
+
+import christmas.domain.Order;
+import christmas.domain.Orders;
+import christmas.domain.product.Product;
+import christmas.repository.ProductRepository;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+public class InputParser {
+ public static final int ITEM_NAME_INDEX = 0;
+ public static final int ITEM_QUANTITY_INDEX = 1;
+ private final ProductRepository productRepository;
+
+ public InputParser(ProductRepository productRepository) {
+ this.productRepository = productRepository;
+ }
+
+ public int parseInt(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ public Orders parseOrders(String input) {
+ List<Order> orders = new ArrayList<>();
+
+ List<String> splitInput = Arrays.stream(input.split(",")).toList();
+ for (String itemInput : splitInput) {
+ List<String> field = Arrays.stream(itemInput.split("-")).toList();
+
+ Optional<Product> product = this.productRepository.findByName(field.get(ITEM_NAME_INDEX).strip());
+ if (product.isEmpty()) {
+ throw new IllegalArgumentException();
+ }
+ orders.add(new Order(product.get(), parseInt(field.get(ITEM_QUANTITY_INDEX).strip())));
+ }
+ return new Orders(orders);
+ }
+
+} | Java | Repository를 static이 아닌 의존성 주입으로 사용하신 이유가 궁금합니다!
둘 중 어떤 게 적절한지 고민돼서요 |
@@ -0,0 +1,56 @@
+package christmas.controller;
+
+import christmas.domain.Orders;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class RetryInputUtil {
+
+ private final InputParser inputParser;
+
+ public RetryInputUtil(InputParser inputParser) {
+ this.inputParser = inputParser;
+ }
+
+ public int getDay() {
+ return retryLogics(InputView::getDay, inputParser::parseInt, this::dayValidate, "유효하지 않은 날짜입니다. 다시 입력해 주세요.");
+ }
+
+ public Orders getOrders() {
+ return retryLogics(InputView::getOrders, inputParser::parseOrders, "유효하지 않은 주문입니다. 다시 입력해 주세요.");
+ }
+
+ private void dayValidate(int day) {
+ if (!(1 <= day && day <= 31)) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, Consumer<T> validator, String errorMessage) {
+ while (true) {
+ try {
+ String userInput = userInputReader.get();
+ T parsedInput = parser.apply(userInput);
+ validator.accept(parsedInput);
+ return parsedInput;
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(errorMessage);
+ }
+ }
+ }
+
+ private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, String errorMessage) {
+ while (true) {
+ try {
+ String userInput = userInputReader.get();
+ return parser.apply(userInput);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(errorMessage);
+ }
+
+ }
+ }
+} | Java | Orders에 대한 validation도 추가한다면 retryLogics() 하나로 처리할 수 있을 것 같아요! |
@@ -0,0 +1,76 @@
+package christmas.dto;
+
+import christmas.enums.Badge;
+import christmas.enums.BenefitType;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+public record BenefitResultDto(
+ int day,
+ List<ItemDto> orderedItems,
+ int totalPrice,
+ Optional<ItemDto> giveaway,
+ Map<BenefitType, Integer> benefits,
+ int totalBenefitAmount,
+ int expectedPaymentAmount,
+ Optional<Badge> badge
+) {
+
+ public static class Builder {
+ int day;
+ List<ItemDto> orderedItems;
+ int totalPrice;
+ Optional<ItemDto> giveaway;
+ Map<BenefitType, Integer> benefits;
+ int totalBenefitAmount;
+ int expectedPaymentAmount;
+ Optional<Badge> badge;
+
+ public Builder day(int day) {
+ this.day = day;
+ return this;
+ }
+
+ public Builder orderedItems(List<ItemDto> orderedItems) {
+ this.orderedItems = orderedItems;
+ return this;
+ }
+
+ public Builder totalPrice(int totalPrice) {
+ this.totalPrice = totalPrice;
+ return this;
+ }
+
+ public Builder giveaway(Optional<ItemDto> giveaway) {
+ this.giveaway = giveaway;
+ return this;
+ }
+
+ public Builder benefits(Map<BenefitType, Integer> benefits) {
+ this.benefits = benefits;
+ return this;
+ }
+
+ public Builder totalBenefitAmount(int totalBenefitAmount) {
+ this.totalBenefitAmount = totalBenefitAmount;
+ return this;
+ }
+
+ public Builder expectedPaymentAmount(int expectedPaymentAmount) {
+ this.expectedPaymentAmount = expectedPaymentAmount;
+ return this;
+ }
+
+ public Builder badge(Optional<Badge> badge) {
+ this.badge = badge;
+ return this;
+ }
+
+ public BenefitResultDto build() {
+ return new BenefitResultDto(day, orderedItems, totalPrice, giveaway, benefits,
+ totalBenefitAmount,
+ expectedPaymentAmount, badge);
+ }
+ }
+} | Java | 저도 결과 정보들을 dto로 만들었지만 필드가 너무 많은 것이 고민이 되었는데, 빌더를 활용할 수 있겠네요! |
@@ -0,0 +1,35 @@
+package christmas.enums;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+public enum Badge {
+ STAR(5_000, "별"),
+ TREE(10_000, "트리"),
+ SANTA(20_000, "산타");
+
+ private final int discountAmount;
+ private final String name;
+
+ Badge(int discountAmount, String name) {
+ this.discountAmount = discountAmount;
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public static Optional<Badge> getBadgeByPaymentAmount(int discountAmount) {
+ List<Badge> badges = Arrays.stream(Badge.values()).sorted().toList();
+
+ Badge selectedBadge = null;
+ for (Badge badge : badges) {
+ if (badge.discountAmount <= discountAmount) {
+ selectedBadge = badge;
+ }
+ }
+ return Optional.ofNullable(selectedBadge);
+ }
+} | Java | 여기에 "없음"을 name으로 갖는 enum을 추가하면 Optional<Badge> 대신 활용할 수 있을 것 같습니다! |
@@ -0,0 +1,56 @@
+package christmas.controller;
+
+import christmas.domain.Orders;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class RetryInputUtil {
+
+ private final InputParser inputParser;
+
+ public RetryInputUtil(InputParser inputParser) {
+ this.inputParser = inputParser;
+ }
+
+ public int getDay() {
+ return retryLogics(InputView::getDay, inputParser::parseInt, this::dayValidate, "유효하지 않은 날짜입니다. 다시 입력해 주세요.");
+ }
+
+ public Orders getOrders() {
+ return retryLogics(InputView::getOrders, inputParser::parseOrders, "유효하지 않은 주문입니다. 다시 입력해 주세요.");
+ }
+
+ private void dayValidate(int day) {
+ if (!(1 <= day && day <= 31)) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, Consumer<T> validator, String errorMessage) {
+ while (true) {
+ try {
+ String userInput = userInputReader.get();
+ T parsedInput = parser.apply(userInput);
+ validator.accept(parsedInput);
+ return parsedInput;
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(errorMessage);
+ }
+ }
+ }
+
+ private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, String errorMessage) {
+ while (true) {
+ try {
+ String userInput = userInputReader.get();
+ return parser.apply(userInput);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(errorMessage);
+ }
+
+ }
+ }
+} | Java | 1과 31같은 매직넘버는 상수로 관리하는 것이 어떨까요?
그리고 조건식의 경우, 긍정 조건식이 가독성이 더 좋다고 합니다! |
@@ -0,0 +1,38 @@
+package christmas.domain;
+
+import christmas.dto.ItemDto;
+import christmas.validator.OrdersValidator;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Orders {
+ private final List<Order> orders;
+
+ public Orders(List<Order> orders) {
+ OrdersValidator.validate(orders);
+ this.orders = orders;
+ }
+
+ public int calculateTotalPrice() {
+ return orders.stream().mapToInt(Order::getPrice).sum();
+ }
+
+ public List<Order> getOrders() {
+ return List.copyOf(orders);
+ }
+
+ public List<ItemDto> toDto() {
+ List<ItemDto> items = new ArrayList<>();
+ for (Order order : orders) {
+ items.add(new ItemDto(order.getProduct(), order.getQuantity()));
+ }
+ return items;
+ }
+
+ @Override
+ public String toString() {
+ return "Orders{" +
+ "orders=" + orders +
+ '}';
+ }
+} | Java | Stream을 이용해보는것은 어떨까요? |
@@ -0,0 +1,36 @@
+package christmas.domain.product;
+
+import christmas.enums.ProductType;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private final ProductType type;
+
+ public Product(String name, int price, ProductType type) {
+ this.name = name;
+ this.price = price;
+ this.type = type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public ProductType getType() {
+ return type;
+ }
+
+ @Override
+ public String toString() {
+ return "Product{" +
+ "name='" + name + '\'' +
+ ", price=" + price +
+ ", type=" + type +
+ '}';
+ }
+} | Java | 사용하지 않는 toString을 재정의한 이유가 있을까요? |
@@ -0,0 +1,37 @@
+package christmas.enums;
+
+public enum DayOfWeek {
+ MONDAY(0),
+ TUESDAY(1),
+ WEDNESDAY(2),
+ THURSDAY(3),
+ FRIDAY(4),
+ SATURDAY(5),
+ SUNDAY(6);
+
+ public static final DayOfWeek START_OF_WEEK = FRIDAY;
+ private final int order;
+
+
+ DayOfWeek(int order) {
+ this.order = order;
+ }
+
+ public int getOrder() {
+ return this.order;
+ }
+
+ private static DayOfWeek getDayOfWeekByOrder(int order) {
+ for (DayOfWeek day : DayOfWeek.values()) {
+ if (day.order == order) {
+ return day;
+ }
+ }
+ throw new IllegalArgumentException("Invalid day of week: " + order);
+ }
+
+ public static DayOfWeek getDayOfWeekAsDate(int day) {
+ int order = (START_OF_WEEK.getOrder() + day - 1) / 7;
+ return getDayOfWeekByOrder(order);
+ }
+} | Java | 저는 리스트로 모든 날짜를 enum으로 관리했는데, 이렇게 수식으로 처리할 수도 있겠네요! |
@@ -0,0 +1,37 @@
+package christmas.config;
+
+import christmas.controller.Controller;
+import christmas.controller.InputParser;
+import christmas.controller.RetryInputUtil;
+import christmas.file.parser.ProductParser;
+import christmas.file.reader.CsvReader;
+import christmas.initializer.ProductInitializer;
+import christmas.repository.ProductRepository;
+import christmas.service.PromotionService;
+
+public class DependencyInjector {
+ public Controller createController() {
+ ProductRepository productRepository = getProductRepository();
+ InputParser inputParser = getInputParser(productRepository);
+ RetryInputUtil retryInputUtil = getRetryInputUtil(inputParser);
+ PromotionService promotionService = new PromotionService(productRepository);
+
+ ProductParser productParser = new ProductParser(CsvReader.of("products.md", false));
+ ProductInitializer initializer = new ProductInitializer(productRepository, productParser);
+ initializer.init();
+
+ return new Controller(retryInputUtil, promotionService);
+ }
+
+ private static ProductRepository getProductRepository() {
+ return new ProductRepository();
+ }
+
+ private static InputParser getInputParser(ProductRepository productRepository) {
+ return new InputParser(productRepository);
+ }
+
+ private static RetryInputUtil getRetryInputUtil(InputParser inputParser) {
+ return new RetryInputUtil(inputParser);
+ }
+} | Java | 이번 프리코스 4주차 미션에서 md파일을 읽어오는것이 있었는데 크리스마스 과제도 이렇게 푸시다니 최종 코테 대비를 제대로 하시는군요! |
@@ -0,0 +1,23 @@
+package christmas.domain.promotion;
+
+public class GiveawayPromotion {
+
+ private static final int GIVEAWAY_PAYMENT_AMOUNT = 120_000;
+ private static final String GIVEAWAY_PRODUCT_NAME = "샴페인";
+ private static final int GIVEAWAY_PRODUCT_AMOUNT = 1;
+
+ public static boolean isAvailable(int paymentAmount) {
+ if (paymentAmount < GIVEAWAY_PAYMENT_AMOUNT) {
+ return false;
+ }
+ return true;
+ }
+
+ public static String getGiveawayProductName() {
+ return GIVEAWAY_PRODUCT_NAME;
+ }
+
+ public static int getGiveawayProductQuantity() {
+ return GIVEAWAY_PRODUCT_AMOUNT;
+ }
+} | Java | 증정품 부분을 하드코딩하는게 아닌, 레파지토리에서 가져오는 로직은 어떠신가요? |
@@ -0,0 +1,27 @@
+package store.exception.messages;
+
+public enum ErrorMessage {
+
+ INVALID_FILE_FORMAT_ERROR("파일 처리 중 오류가 발생했습니다"),
+ INVALID_FORMAT("잘못된 입력 형식입니다. [상품명-수량] 형식으로 입력해 주세요."),
+ INVALID_NUMBER("유효한 숫자를 입력해 주세요."),
+ INVALID_ANSWER("잘못된 입력입니다. Y 또는 N으로 다시 입력해 주세요."),
+ MAXIMUM_NUMBER_LENGTH("숫자는 9자 이내여야합니다."),
+ DUPLICATE_ORDER_ITEM("중복된 상품이 있습니다. 다시 입력해 주세요."),
+ INSUFFICIENT_STOCK("재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."),
+ NOT_FOUND("존재하지 않는 상품입니다. 다시 입력해 주세요.");
+
+ private final String message;
+
+ ErrorMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return "[ERROR] " + message;
+ }
+
+ public String format(Object... args) {
+ return String.format(getMessage(), args);
+ }
+} | Java | 공통된 [ERROR]를 분리하신 부분이 되게 좋네요! |
@@ -0,0 +1,39 @@
+package store.inventory.parser;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.List;
+import store.inventory.domain.Promotion;
+
+public class PromotionParser {
+
+ private static final int HEADER_LINE = 1;
+ private static final String DELIMITER = ",";
+
+ public static List<Promotion> parsePromotions(String filePath) throws IOException {
+ List<Promotion> promotions = new ArrayList<>();
+
+ try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) {
+ reader.lines()
+ .skip(HEADER_LINE)
+ .filter(line -> !line.isBlank())
+ .forEach(line -> promotions.add(parsePromotion(line)));
+ }
+ return promotions;
+ }
+
+ private static Promotion parsePromotion(String line) {
+ String[] data = line.split(DELIMITER);
+ String name = data[0].trim();
+ int buyQuantity = Integer.parseInt(data[1].trim());
+ int freeQuantity = Integer.parseInt(data[2].trim());
+ LocalDate startDate = LocalDate.parse(data[3].trim());
+ LocalDate endDate = LocalDate.parse(data[4].trim());
+
+ return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | 안녕하세요!
현재 data 배열은 값이 변경되지 않고, 오로지 읽기 전용으로 사용되고 있는데요. 이를 불변 리스트로 관리하면 더 안전하고, 명확하게 표현할 수 있지 않을까 싶어 리뷰 남겨봅니다.
배열 대신 List.of를 사용해 불변 리스트로 만들면, 데이터의 안전성을 보장하면서도 코드 가독성도 개선될 것 같은데 어떻게 생각하시나요? 😊
```
private static Promotion parsePromotion(String line) {
List<String> data = List.of(line.split(DELIMITER));
String name = data.get(0).trim();
int buyQuantity = Integer.parseInt(data.get(1).trim());
int freeQuantity = Integer.parseInt(data.get(2).trim());
LocalDate startDate = LocalDate.parse(data.get(3).trim());
LocalDate endDate = LocalDate.parse(data.get(4).trim());
return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate);
}
``` |
@@ -0,0 +1,55 @@
+package store.order.domain;
+
+import static store.order.validator.CartValidator.findInventoryItem;
+
+import java.time.LocalDate;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.inventory.domain.InventoryItem;
+import store.order.dto.FreeItemDto;
+import store.order.dto.OrderItemDto;
+import store.order.dto.ReceiptItemDto;
+
+public class Cart {
+
+ private final List<CartItem> items;
+
+ public Cart(final List<CartItem> items) {
+ this.items = items;
+ }
+
+ public static Cart of(
+ final List<OrderItemDto> orderItems,
+ final List<InventoryItem> inventoryItems,
+ final LocalDate today) {
+ List<CartItem> cartItems = orderItems.stream().map(orderItemDto -> {
+ final InventoryItem inventoryItem = findInventoryItem(orderItemDto.productName(), inventoryItems);
+ return CartItem.from(orderItemDto, inventoryItem, today);
+ }).collect(Collectors.toList());
+ return new Cart(cartItems);
+ }
+
+ public PaymentCalculator createPaymentCalculator(final boolean membershipStatus) {
+ return new PaymentCalculator(this, membershipStatus);
+ }
+
+ public int calculateTotalPrice() {
+ return items.stream().mapToInt(CartItem::calculateTotalPrice).sum();
+ }
+
+ public int calculatePromotionDiscount() {
+ return items.stream().mapToInt(CartItem::calculatePromotionDiscount).sum();
+ }
+
+ public List<ReceiptItemDto> getPurchasedItems() {
+ return ReceiptItemDto.from(items);
+ }
+
+ public List<FreeItemDto> getFreeItems() {
+ return FreeItemDto.from(items);
+ }
+
+ public List<CartItem> getItems() {
+ return items;
+ }
+} | Java | `findInventoryItem` 메서드가 `CartValidator` 클래스에 위치하고 있었군요!
처음에는 메서드 이름만 보고 `Cart` 클래스에 있는 메서드라고 착각했습니다.
특임포트 구문을 보고 나서야` CartValidator`에 있는 메서드라는 것을 알 수 있었습니다.
이와 같은 혼란을 줄이기 위해 메서드 호출 시 클래스명을 명시하는 것에 대해 어떻게 생각하시나요?
`final InventoryItem inventoryItem = CartValidator.findInventoryItem(orderItemDto.productName(), inventoryItems);` |
@@ -0,0 +1,25 @@
+package store;
+
+import store.controller.StoreController;
+import store.exception.ExceptionHandler;
+import store.inventory.repository.InventoryRepository;
+import store.inventory.repository.PromotionRepository;
+import store.inventory.service.InventoryService;
+import store.inventory.service.PromotionService;
+import store.service.StoreService;
+
+public class Configuration {
+
+ private final InventoryRepository inventoryRepository = new InventoryRepository();
+ private final PromotionRepository promotionRepository = new PromotionRepository();
+ private final PromotionService promotionService = new PromotionService(promotionRepository);
+ private final InventoryService inventoryService = new InventoryService(inventoryRepository, promotionRepository);
+ private final StoreService storeService = new StoreService(inventoryService, promotionService);
+ private final ExceptionHandler exceptionHandler = new ExceptionHandler();
+
+ public StoreController storeController() {
+ StoreController storeController = new StoreController(storeService, exceptionHandler);
+ storeController.init();
+ return storeController;
+ }
+}
\ No newline at end of file | Java | storeController.init()을 Configuration 클래스 안에서 호출하신 이유가 있을까요? |
@@ -1,7 +1,11 @@
package store;
+import store.controller.StoreController;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ final Configuration configuration = new Configuration();
+ StoreController storeController = configuration.storeController();
+ storeController.run();
}
} | Java | 메서드 내부에서 final 키워드로 선언하신 이유가 있을까요? |
@@ -0,0 +1,73 @@
+package store.inventory.domain;
+
+import java.time.LocalDate;
+import java.util.Optional;
+import store.exception.AdditionalBenefitException;
+import store.exception.PromotionNotAvailableException;
+
+public class PromotionHandler {
+
+ private static final int ZERO = 0;
+
+ private final Stock stock;
+ private Optional<Promotion> promotion;
+
+ public PromotionHandler(final Promotion promotion, final Stock stock) {
+ this.promotion = Optional.ofNullable(promotion);
+ this.stock = stock;
+ }
+
+ public boolean isApplicable(final int quantity, final LocalDate today) {
+ return promotion.isPresent() && promotion.get().isApplicable(quantity, today);
+ }
+
+ public int calculateFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0);
+ }
+
+ public void applyDiscount(final int quantity, String productName) {
+ final int promotionQuantity = calculatePromotionStock(quantity);
+ final int nonPromotionQuantity = quantity - promotionQuantity;
+
+ stock.drainDuringPromotionPeriod(promotionQuantity);
+ if (nonPromotionQuantity > ZERO) {
+ throw new PromotionNotAvailableException(productName, nonPromotionQuantity);
+ }
+ }
+
+ public void checkAdditionalBenefitEligibility(final int quantity, final String productName) {
+ final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity);
+ if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) {
+ throw new AdditionalBenefitException(productName, additionalEligibleQuantity);
+ }
+ }
+
+ public void changePromotion(final Promotion promotion) {
+ this.promotion = Optional.ofNullable(promotion);
+ }
+
+ public String getPromotionName() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ private int calculateRemainingFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO);
+ }
+
+ private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) {
+ final int availablePromotionStock = calculatePromotionStock(quantity);
+ final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock);
+
+ return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock;
+ }
+
+ private int calculatePromotionStock(final int quantity) {
+ return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock()))
+ .orElse(ZERO);
+ }
+
+ private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) {
+ final int promotionSetSize = promotion.get().getPromotionSetSize();
+ return availablePromotionStock + additionalEligibleQuantity * promotionSetSize;
+ }
+} | Java | Promotion을 Optional로 관리하신 이유가 있을까요?? |
@@ -0,0 +1,56 @@
+package store.inventory.domain;
+
+import static store.exception.messages.ErrorMessage.INSUFFICIENT_STOCK;
+
+public class Stock {
+
+ private int generalStock;
+ private int promotionStock;
+
+ public Stock(final int generalStock, final int promotionStock) {
+ this.generalStock = generalStock;
+ this.promotionStock = promotionStock;
+ }
+
+ public void useGeneralStock(final int quantity) {
+ validateGeneralStock(quantity);
+ generalStock -= quantity;
+ }
+
+ public void drainDuringPromotionPeriod(final int totalQuantity) {
+ final int remainingPromo = usePromotionStock(totalQuantity);
+ useGeneralStock(remainingPromo);
+ }
+
+ public void addGeneralStock(final int quantity) {
+ this.generalStock += quantity;
+ }
+
+ public void addPromotionStock(final int quantity) {
+ this.promotionStock += quantity;
+ }
+
+ public int getGeneralStock() {
+ return generalStock;
+ }
+
+ public int getPromotionStock() {
+ return promotionStock;
+ }
+
+ public int getTotalStock() {
+ return generalStock + promotionStock;
+ }
+
+ private int usePromotionStock(final int quantity) {
+ final int usedStock = Math.min(quantity, promotionStock);
+ promotionStock -= usedStock;
+ return quantity - usedStock;
+ }
+
+ private void validateGeneralStock(final int quantity) {
+ if (quantity > generalStock) {
+ throw new IllegalArgumentException(INSUFFICIENT_STOCK.getMessage());
+ }
+ }
+} | Java | calculateRemainStock과 같은 네이밍은 어떨까요? |
@@ -0,0 +1,73 @@
+package store.inventory.domain;
+
+import java.time.LocalDate;
+import java.util.Optional;
+import store.exception.AdditionalBenefitException;
+import store.exception.PromotionNotAvailableException;
+
+public class PromotionHandler {
+
+ private static final int ZERO = 0;
+
+ private final Stock stock;
+ private Optional<Promotion> promotion;
+
+ public PromotionHandler(final Promotion promotion, final Stock stock) {
+ this.promotion = Optional.ofNullable(promotion);
+ this.stock = stock;
+ }
+
+ public boolean isApplicable(final int quantity, final LocalDate today) {
+ return promotion.isPresent() && promotion.get().isApplicable(quantity, today);
+ }
+
+ public int calculateFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0);
+ }
+
+ public void applyDiscount(final int quantity, String productName) {
+ final int promotionQuantity = calculatePromotionStock(quantity);
+ final int nonPromotionQuantity = quantity - promotionQuantity;
+
+ stock.drainDuringPromotionPeriod(promotionQuantity);
+ if (nonPromotionQuantity > ZERO) {
+ throw new PromotionNotAvailableException(productName, nonPromotionQuantity);
+ }
+ }
+
+ public void checkAdditionalBenefitEligibility(final int quantity, final String productName) {
+ final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity);
+ if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) {
+ throw new AdditionalBenefitException(productName, additionalEligibleQuantity);
+ }
+ }
+
+ public void changePromotion(final Promotion promotion) {
+ this.promotion = Optional.ofNullable(promotion);
+ }
+
+ public String getPromotionName() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ private int calculateRemainingFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO);
+ }
+
+ private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) {
+ final int availablePromotionStock = calculatePromotionStock(quantity);
+ final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock);
+
+ return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock;
+ }
+
+ private int calculatePromotionStock(final int quantity) {
+ return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock()))
+ .orElse(ZERO);
+ }
+
+ private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) {
+ final int promotionSetSize = promotion.get().getPromotionSetSize();
+ return availablePromotionStock + additionalEligibleQuantity * promotionSetSize;
+ }
+} | Java | Promotion 클래스에서도 해당 상수가 선언되어있는데, 따로 클래스로 분리해 재사용성을 고려하는건 어떨까요? |
@@ -0,0 +1,25 @@
+package store.inventory.repository;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import store.inventory.domain.InventoryItem;
+
+public class InventoryRepository {
+
+ private final List<InventoryItem> inventories = new ArrayList<>();
+
+ public void save(InventoryItem inventoryItem) {
+ inventories.add(inventoryItem);
+ }
+
+ public List<InventoryItem> findAll() {
+ return new ArrayList<>(inventories);
+ }
+
+ public Optional<InventoryItem> findByProductName(String productName) {
+ return inventories.stream()
+ .filter(inventory -> inventory.getProductName().equals(productName))
+ .findFirst();
+ }
+} | Java | repository를 구현할 생각은 못했는데, 정말 좋은 것 같아요!!👍 |
@@ -0,0 +1,101 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.util.function.Supplier;
+import store.exception.ExceptionHandler;
+import store.exception.ExceptionResponse;
+import store.exception.UserDecisionException;
+import store.order.domain.Cart;
+import store.order.domain.CartItem;
+import store.order.domain.PaymentCalculator;
+import store.order.dto.ReceiptDto;
+import store.order.dto.YesOrNoDto;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+
+ private static final String PROMOTION_FILE_PATH = Paths.get("src", "main", "resources", "promotions.md").toString();
+ private static final String PRODUCT_FILE_PATH = Paths.get("src", "main", "resources", "products.md").toString();
+
+ private final StoreService storeService;
+ private final ExceptionHandler exceptionHandler;
+
+ public StoreController(StoreService storeService, ExceptionHandler exceptionHandler) {
+ this.storeService = storeService;
+ this.exceptionHandler = exceptionHandler;
+ }
+
+ public void init() {
+ exceptionHandler.handleVoidWithIOException(
+ () -> storeService.loadInitialData(PROMOTION_FILE_PATH, PRODUCT_FILE_PATH));
+ }
+
+ public void run() {
+ do {
+ displayInventory();
+ final Cart cart = createCartWithRetry();
+ processCart(cart);
+ } while (continueShopping());
+ }
+
+ private Cart createCartWithRetry() {
+ return exceptionHandler.handleWithRetry(() -> storeService.prepareCart(InputView.readOrder())).result();
+ }
+
+ private void displayInventory() {
+ OutputView.displayInventory(storeService.getAllInventoryPairs());
+ }
+
+ private void processCart(final Cart cart) {
+ applyPromotions(cart);
+ final PaymentCalculator calculator = requestMembershipStatus(cart);
+ displayReceipt(calculator);
+ }
+
+ private boolean continueShopping() {
+ return handleYesOrNoRetry(InputView::readRetryStatus);
+ }
+
+ private PaymentCalculator requestMembershipStatus(final Cart cart) {
+ final boolean membershipStatus = handleYesOrNoRetry(InputView::readMembershipStatus);
+ return cart.createPaymentCalculator(membershipStatus);
+ }
+
+ private boolean handleYesOrNoRetry(final Supplier<String> inputSupplier) {
+ return exceptionHandler.handleWithRetry(() -> YesOrNoDto.from(inputSupplier.get())).result().isYesOrNo();
+ }
+
+ private void applyPromotions(final Cart cart) {
+ cart.getItems().forEach(this::applyPromotionWithRetry);
+ }
+
+ private void displayReceipt(final PaymentCalculator calculator) {
+ final ReceiptDto receipt = calculator.generateReceipt();
+ OutputView.displayReceipt(receipt);
+ }
+
+ private void applyPromotionWithRetry(final CartItem cartItem) {
+ ExceptionResponse<Void> response = exceptionHandler.handleWithRetry(() -> {
+ cartItem.drainStock(LocalDate.from(DateTimes.now()));
+ return null;
+ });
+ if (response.hasException()) {
+ processUserDecision(response.userDecisionException(), cartItem);
+ }
+ }
+
+ private void processUserDecision(final UserDecisionException exception, final CartItem cartItem) {
+ if (exception.isPromotionNotAvailableException()) {
+ cartItem.handlePromotionShortage(exception.getUserChoice(), exception.getQuantity());
+ return;
+ }
+
+ if (exception.isAdditionalBenefitException() && exception.getUserChoice()) {
+ cartItem.addEligibleFreeItems(exception.getQuantity());
+ }
+ }
+} | Java | 각각의 파일을 불러오고, 에러 핸들링까지 한 게 인상적이네요..! |
@@ -0,0 +1,73 @@
+package store.inventory.domain;
+
+import java.time.LocalDate;
+import java.util.Optional;
+import store.exception.AdditionalBenefitException;
+import store.exception.PromotionNotAvailableException;
+
+public class PromotionHandler {
+
+ private static final int ZERO = 0;
+
+ private final Stock stock;
+ private Optional<Promotion> promotion;
+
+ public PromotionHandler(final Promotion promotion, final Stock stock) {
+ this.promotion = Optional.ofNullable(promotion);
+ this.stock = stock;
+ }
+
+ public boolean isApplicable(final int quantity, final LocalDate today) {
+ return promotion.isPresent() && promotion.get().isApplicable(quantity, today);
+ }
+
+ public int calculateFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0);
+ }
+
+ public void applyDiscount(final int quantity, String productName) {
+ final int promotionQuantity = calculatePromotionStock(quantity);
+ final int nonPromotionQuantity = quantity - promotionQuantity;
+
+ stock.drainDuringPromotionPeriod(promotionQuantity);
+ if (nonPromotionQuantity > ZERO) {
+ throw new PromotionNotAvailableException(productName, nonPromotionQuantity);
+ }
+ }
+
+ public void checkAdditionalBenefitEligibility(final int quantity, final String productName) {
+ final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity);
+ if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) {
+ throw new AdditionalBenefitException(productName, additionalEligibleQuantity);
+ }
+ }
+
+ public void changePromotion(final Promotion promotion) {
+ this.promotion = Optional.ofNullable(promotion);
+ }
+
+ public String getPromotionName() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ private int calculateRemainingFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO);
+ }
+
+ private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) {
+ final int availablePromotionStock = calculatePromotionStock(quantity);
+ final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock);
+
+ return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock;
+ }
+
+ private int calculatePromotionStock(final int quantity) {
+ return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock()))
+ .orElse(ZERO);
+ }
+
+ private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) {
+ final int promotionSetSize = promotion.get().getPromotionSetSize();
+ return availablePromotionStock + additionalEligibleQuantity * promotionSetSize;
+ }
+} | Java | 제가 알기로는 Optional이 객체 필드로 선언하는 것을 고려하지 않고 만들어져 직렬화 및 역직렬화시 문제가 생길수 있는 것으로 알고 있습니다. 그래서 반환값으로만 사용되는게 좋다고 알고 있습니다! |
@@ -0,0 +1,17 @@
+package store.exception;
+
+import static store.exception.messages.UserPromotionMessage.ADDITIONAL_BENEFIT_AVAILABLE;
+
+public class AdditionalBenefitException extends RuntimeException {
+
+ private final int additionalEligibleQuantity;
+
+ public AdditionalBenefitException(String productName, int additionalEligibleQuantity) {
+ super(ADDITIONAL_BENEFIT_AVAILABLE.format(productName, additionalEligibleQuantity));
+ this.additionalEligibleQuantity = additionalEligibleQuantity;
+ }
+
+ public int getAdditionalEligibleQuantity() {
+ return additionalEligibleQuantity;
+ }
+} | Java | 저는 이번에 시간이 없어서 커스텀 예외 클래스를 생각만 하고 만들지 못했는데,, 대단하신거 같습니다! |
@@ -0,0 +1,73 @@
+package store.inventory.domain;
+
+import java.time.LocalDate;
+import java.util.Optional;
+import store.exception.AdditionalBenefitException;
+import store.exception.PromotionNotAvailableException;
+
+public class PromotionHandler {
+
+ private static final int ZERO = 0;
+
+ private final Stock stock;
+ private Optional<Promotion> promotion;
+
+ public PromotionHandler(final Promotion promotion, final Stock stock) {
+ this.promotion = Optional.ofNullable(promotion);
+ this.stock = stock;
+ }
+
+ public boolean isApplicable(final int quantity, final LocalDate today) {
+ return promotion.isPresent() && promotion.get().isApplicable(quantity, today);
+ }
+
+ public int calculateFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0);
+ }
+
+ public void applyDiscount(final int quantity, String productName) {
+ final int promotionQuantity = calculatePromotionStock(quantity);
+ final int nonPromotionQuantity = quantity - promotionQuantity;
+
+ stock.drainDuringPromotionPeriod(promotionQuantity);
+ if (nonPromotionQuantity > ZERO) {
+ throw new PromotionNotAvailableException(productName, nonPromotionQuantity);
+ }
+ }
+
+ public void checkAdditionalBenefitEligibility(final int quantity, final String productName) {
+ final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity);
+ if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) {
+ throw new AdditionalBenefitException(productName, additionalEligibleQuantity);
+ }
+ }
+
+ public void changePromotion(final Promotion promotion) {
+ this.promotion = Optional.ofNullable(promotion);
+ }
+
+ public String getPromotionName() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ private int calculateRemainingFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO);
+ }
+
+ private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) {
+ final int availablePromotionStock = calculatePromotionStock(quantity);
+ final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock);
+
+ return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock;
+ }
+
+ private int calculatePromotionStock(final int quantity) {
+ return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock()))
+ .orElse(ZERO);
+ }
+
+ private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) {
+ final int promotionSetSize = promotion.get().getPromotionSetSize();
+ return availablePromotionStock + additionalEligibleQuantity * promotionSetSize;
+ }
+} | Java | 저도 이 부분을 예외로 만들까 고민을 많이 했었는데, 예외는 예외로만 사용을 해야한다고 생각을 해서 이렇게 구현하지 않았는데 이렇게 보니 예외라고 생각할 수도 있을 것 같아요. 확실히 예외로 구현하는게 깔끔해 보이네요! |
@@ -0,0 +1,25 @@
+package store.inventory.repository;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import store.inventory.domain.InventoryItem;
+
+public class InventoryRepository {
+
+ private final List<InventoryItem> inventories = new ArrayList<>();
+
+ public void save(InventoryItem inventoryItem) {
+ inventories.add(inventoryItem);
+ }
+
+ public List<InventoryItem> findAll() {
+ return new ArrayList<>(inventories);
+ }
+
+ public Optional<InventoryItem> findByProductName(String productName) {
+ return inventories.stream()
+ .filter(inventory -> inventory.getProductName().equals(productName))
+ .findFirst();
+ }
+} | Java | JPA처럼 Optional로 반환하는것 잘 배우고 갑니다! |
@@ -0,0 +1,39 @@
+package store.inventory.parser;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.List;
+import store.inventory.domain.Promotion;
+
+public class PromotionParser {
+
+ private static final int HEADER_LINE = 1;
+ private static final String DELIMITER = ",";
+
+ public static List<Promotion> parsePromotions(String filePath) throws IOException {
+ List<Promotion> promotions = new ArrayList<>();
+
+ try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) {
+ reader.lines()
+ .skip(HEADER_LINE)
+ .filter(line -> !line.isBlank())
+ .forEach(line -> promotions.add(parsePromotion(line)));
+ }
+ return promotions;
+ }
+
+ private static Promotion parsePromotion(String line) {
+ String[] data = line.split(DELIMITER);
+ String name = data[0].trim();
+ int buyQuantity = Integer.parseInt(data[1].trim());
+ int freeQuantity = Integer.parseInt(data[2].trim());
+ LocalDate startDate = LocalDate.parse(data[3].trim());
+ LocalDate endDate = LocalDate.parse(data[4].trim());
+
+ return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | 좋은 의견인 것 같습니다. 자세한 리뷰 및 설명 정말 감사합니다! |
@@ -0,0 +1,55 @@
+package store.order.domain;
+
+import static store.order.validator.CartValidator.findInventoryItem;
+
+import java.time.LocalDate;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.inventory.domain.InventoryItem;
+import store.order.dto.FreeItemDto;
+import store.order.dto.OrderItemDto;
+import store.order.dto.ReceiptItemDto;
+
+public class Cart {
+
+ private final List<CartItem> items;
+
+ public Cart(final List<CartItem> items) {
+ this.items = items;
+ }
+
+ public static Cart of(
+ final List<OrderItemDto> orderItems,
+ final List<InventoryItem> inventoryItems,
+ final LocalDate today) {
+ List<CartItem> cartItems = orderItems.stream().map(orderItemDto -> {
+ final InventoryItem inventoryItem = findInventoryItem(orderItemDto.productName(), inventoryItems);
+ return CartItem.from(orderItemDto, inventoryItem, today);
+ }).collect(Collectors.toList());
+ return new Cart(cartItems);
+ }
+
+ public PaymentCalculator createPaymentCalculator(final boolean membershipStatus) {
+ return new PaymentCalculator(this, membershipStatus);
+ }
+
+ public int calculateTotalPrice() {
+ return items.stream().mapToInt(CartItem::calculateTotalPrice).sum();
+ }
+
+ public int calculatePromotionDiscount() {
+ return items.stream().mapToInt(CartItem::calculatePromotionDiscount).sum();
+ }
+
+ public List<ReceiptItemDto> getPurchasedItems() {
+ return ReceiptItemDto.from(items);
+ }
+
+ public List<FreeItemDto> getFreeItems() {
+ return FreeItemDto.from(items);
+ }
+
+ public List<CartItem> getItems() {
+ return items;
+ }
+} | Java | 코드의 간결성을 위해 생략했었는데 오히려 다른 사람 입장에서 가독성이 낮아질 수도 있겠구나 깨닫게된 리뷰인 것 같습니다. 이후의 협업을 위해 이러한 사항을 고려하는 더 섬세한 개발자가 되어야겠습니다. 감사합니다! |
@@ -0,0 +1,25 @@
+package store;
+
+import store.controller.StoreController;
+import store.exception.ExceptionHandler;
+import store.inventory.repository.InventoryRepository;
+import store.inventory.repository.PromotionRepository;
+import store.inventory.service.InventoryService;
+import store.inventory.service.PromotionService;
+import store.service.StoreService;
+
+public class Configuration {
+
+ private final InventoryRepository inventoryRepository = new InventoryRepository();
+ private final PromotionRepository promotionRepository = new PromotionRepository();
+ private final PromotionService promotionService = new PromotionService(promotionRepository);
+ private final InventoryService inventoryService = new InventoryService(inventoryRepository, promotionRepository);
+ private final StoreService storeService = new StoreService(inventoryService, promotionService);
+ private final ExceptionHandler exceptionHandler = new ExceptionHandler();
+
+ public StoreController storeController() {
+ StoreController storeController = new StoreController(storeService, exceptionHandler);
+ storeController.init();
+ return storeController;
+ }
+}
\ No newline at end of file | Java | 파일 일관성 상 컨피그 파일에서 프로그램 설정을 완료해야한다고 생각했습니다. 지금 생각해보니 컨트롤러 내의 init을 컨피그 파일로 이전하지 않는 이상 컨트롤러 start() 메서드 내에서 호출해도 됐을 것 같네요! |
@@ -1,7 +1,11 @@
package store;
+import store.controller.StoreController;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ final Configuration configuration = new Configuration();
+ StoreController storeController = configuration.storeController();
+ storeController.run();
}
} | Java | 최대한 피드백 대로 final을 사용하고 싶었습니다. final을 적용하면서 어디부터 어디까지 적용해야하나라는 의문이 생겼었는데 그때 시간이 부족하여 일단 웬만하면 적용하는 식으로 했습니다. 따라서 현재 과제에서는 final 적용에 대해 많이 서툰 것 같네요 매개변수, 정말 바뀌지 않는 곳에서만 final 키워드를 사용할 수 있도록 해야겠습니다! |
@@ -0,0 +1,73 @@
+package store.inventory.domain;
+
+import java.time.LocalDate;
+import java.util.Optional;
+import store.exception.AdditionalBenefitException;
+import store.exception.PromotionNotAvailableException;
+
+public class PromotionHandler {
+
+ private static final int ZERO = 0;
+
+ private final Stock stock;
+ private Optional<Promotion> promotion;
+
+ public PromotionHandler(final Promotion promotion, final Stock stock) {
+ this.promotion = Optional.ofNullable(promotion);
+ this.stock = stock;
+ }
+
+ public boolean isApplicable(final int quantity, final LocalDate today) {
+ return promotion.isPresent() && promotion.get().isApplicable(quantity, today);
+ }
+
+ public int calculateFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0);
+ }
+
+ public void applyDiscount(final int quantity, String productName) {
+ final int promotionQuantity = calculatePromotionStock(quantity);
+ final int nonPromotionQuantity = quantity - promotionQuantity;
+
+ stock.drainDuringPromotionPeriod(promotionQuantity);
+ if (nonPromotionQuantity > ZERO) {
+ throw new PromotionNotAvailableException(productName, nonPromotionQuantity);
+ }
+ }
+
+ public void checkAdditionalBenefitEligibility(final int quantity, final String productName) {
+ final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity);
+ if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) {
+ throw new AdditionalBenefitException(productName, additionalEligibleQuantity);
+ }
+ }
+
+ public void changePromotion(final Promotion promotion) {
+ this.promotion = Optional.ofNullable(promotion);
+ }
+
+ public String getPromotionName() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ private int calculateRemainingFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO);
+ }
+
+ private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) {
+ final int availablePromotionStock = calculatePromotionStock(quantity);
+ final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock);
+
+ return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock;
+ }
+
+ private int calculatePromotionStock(final int quantity) {
+ return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock()))
+ .orElse(ZERO);
+ }
+
+ private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) {
+ final int promotionSetSize = promotion.get().getPromotionSetSize();
+ return availablePromotionStock + additionalEligibleQuantity * promotionSetSize;
+ }
+} | Java | 헉 기본적인 개념을 놓치고 있었네요. 조언 감사합니다! |
@@ -0,0 +1,56 @@
+package store.inventory.domain;
+
+import static store.exception.messages.ErrorMessage.INSUFFICIENT_STOCK;
+
+public class Stock {
+
+ private int generalStock;
+ private int promotionStock;
+
+ public Stock(final int generalStock, final int promotionStock) {
+ this.generalStock = generalStock;
+ this.promotionStock = promotionStock;
+ }
+
+ public void useGeneralStock(final int quantity) {
+ validateGeneralStock(quantity);
+ generalStock -= quantity;
+ }
+
+ public void drainDuringPromotionPeriod(final int totalQuantity) {
+ final int remainingPromo = usePromotionStock(totalQuantity);
+ useGeneralStock(remainingPromo);
+ }
+
+ public void addGeneralStock(final int quantity) {
+ this.generalStock += quantity;
+ }
+
+ public void addPromotionStock(final int quantity) {
+ this.promotionStock += quantity;
+ }
+
+ public int getGeneralStock() {
+ return generalStock;
+ }
+
+ public int getPromotionStock() {
+ return promotionStock;
+ }
+
+ public int getTotalStock() {
+ return generalStock + promotionStock;
+ }
+
+ private int usePromotionStock(final int quantity) {
+ final int usedStock = Math.min(quantity, promotionStock);
+ promotionStock -= usedStock;
+ return quantity - usedStock;
+ }
+
+ private void validateGeneralStock(final int quantity) {
+ if (quantity > generalStock) {
+ throw new IllegalArgumentException(INSUFFICIENT_STOCK.getMessage());
+ }
+ }
+} | Java | 프로모션 재고를 사용하는 것이 중점이라 생각하여 해당 네이밍으로 메서드명을 명명했었는데, 부족하면 일반 재고를 사용한다라는 의미를 포함하여 메서드명을 정했어도 됐을 것 같네요! 한번 더 생각할 기회를 주셔서 감사합니다 |
@@ -0,0 +1,73 @@
+package store.inventory.domain;
+
+import java.time.LocalDate;
+import java.util.Optional;
+import store.exception.AdditionalBenefitException;
+import store.exception.PromotionNotAvailableException;
+
+public class PromotionHandler {
+
+ private static final int ZERO = 0;
+
+ private final Stock stock;
+ private Optional<Promotion> promotion;
+
+ public PromotionHandler(final Promotion promotion, final Stock stock) {
+ this.promotion = Optional.ofNullable(promotion);
+ this.stock = stock;
+ }
+
+ public boolean isApplicable(final int quantity, final LocalDate today) {
+ return promotion.isPresent() && promotion.get().isApplicable(quantity, today);
+ }
+
+ public int calculateFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0);
+ }
+
+ public void applyDiscount(final int quantity, String productName) {
+ final int promotionQuantity = calculatePromotionStock(quantity);
+ final int nonPromotionQuantity = quantity - promotionQuantity;
+
+ stock.drainDuringPromotionPeriod(promotionQuantity);
+ if (nonPromotionQuantity > ZERO) {
+ throw new PromotionNotAvailableException(productName, nonPromotionQuantity);
+ }
+ }
+
+ public void checkAdditionalBenefitEligibility(final int quantity, final String productName) {
+ final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity);
+ if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) {
+ throw new AdditionalBenefitException(productName, additionalEligibleQuantity);
+ }
+ }
+
+ public void changePromotion(final Promotion promotion) {
+ this.promotion = Optional.ofNullable(promotion);
+ }
+
+ public String getPromotionName() {
+ return promotion.map(Promotion::getName).orElse("");
+ }
+
+ private int calculateRemainingFreeQuantity(final int quantity) {
+ return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO);
+ }
+
+ private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) {
+ final int availablePromotionStock = calculatePromotionStock(quantity);
+ final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock);
+
+ return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock;
+ }
+
+ private int calculatePromotionStock(final int quantity) {
+ return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock()))
+ .orElse(ZERO);
+ }
+
+ private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) {
+ final int promotionSetSize = promotion.get().getPromotionSetSize();
+ return availablePromotionStock + additionalEligibleQuantity * promotionSetSize;
+ }
+} | Java | 0과 같이 비즈니스적으로 의미 없는 상수는 그냥 해당 클래스 내에서만 가지고 있도록 하는 것이 좋다고 생각했습니다.
그래도 자주 쓰는 것들은 클래스로 분리할까라는 생각도 잠깐 스쳐지나갔었는데 개인적으로 해당 주차 과제가 시간적으로 부족했어서 의미 없는 수들을 위해 따로 클래스까지 분리하고 작성할 시간 및 비용적 측면에서 ZERO의 재사용성을 최대로 끌어올릴 필요 없다고 결정했었습니다. |
@@ -1 +1,239 @@
# java-convenience-store-precourse
+## 🏪 프로그램 소개
+구매자의 할인 혜택과 재고 상황을 고려하여 최종 결제 금액을 계산하고 안내하는 결제 시스템
+### 입력
+- 상품 목록과 행사 목록 파일
+- 구매할 상품과 수량
+ - 상품명, 수량은 하이픈(-), 개별 상품 대괄호([])로 묶어 쉼표(,)로 구분
+ - ex) [콜라-10],[사이다-3]
+- 프리모션 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, 그 수량만큼 추가 여부
+ - Y: 증정 받을 수 있는 상품을 추가
+ - N: 증정 받을 수 있는 상품을 추가하지 않음
+- 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, 일부 수량에 대해 정가로 결제할지 여부
+ - Y: 일부 수량에 대해 정가로 결제
+ - N: 정가로 결제해야하는 수량만큼 제외한 후 결제를 진행
+- 멤버십 할인 적용 여부
+ - Y: 멤버십 할인 적용
+ - N: 멤버십 할인 적용하지 않음
+- 추가 구매 여부
+ - Y: 재고가 업데이트된 상품 목록을 확인 후 추가로 구매 진행
+ - N: 구매 종료
+### 출력
+- 환영 인사
+- 상품명, 가격, 프로모션 이름, 재고
+ - 재고가 0개라면 ```재고없음```을 출력
+- 프로모션 적용이 가능한 상품에 대해 고객이 해당 수량만큼 가져오지 않았을 경우, 혜택에 대한 안내 메시지를 출력
+- 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, 일부 수량에 대해 정가로 결제할지 여부에 대한 안내 메시지 출력
+- 멤버십 할인 적용 여부를 확인하기 위해 안내 문구 출력
+- 구매 상품 내역, 증정 상품 내역, 금액 정보 출력
+- 추가 구매 여부를 확인하기 위한 안내 문구 출력
+- 사용자가 잘못된 값을 입력했을 때, “ERROR”로 시작하는 오류 메시지와 함께 상황에 맞는 안내 출력
+```
+안녕하세요. W편의점입니다.
+현재 보유하고 있는 상품입니다.
+
+- 콜라 1,000원 10개 탄산2+1
+- 콜라 1,000원 10개
+- 사이다 1,000원 8개 탄산2+1
+- 사이다 1,000원 7개
+- 오렌지주스 1,800원 9개 MD추천상품
+- 오렌지주스 1,800원 재고 없음
+- 탄산수 1,200원 5개 탄산2+1
+- 탄산수 1,200원 재고 없음
+- 물 500원 10개
+- 비타민워터 1,500원 6개
+- 감자칩 1,500원 5개 반짝할인
+- 감자칩 1,500원 5개
+- 초코바 1,200원 5개 MD추천상품
+- 초코바 1,200원 5개
+- 에너지바 2,000원 5개
+- 정식도시락 6,400원 8개
+- 컵라면 1,700원 1개 MD추천상품
+- 컵라면 1,700원 10개
+
+구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])
+[콜라-3],[에너지바-5]
+
+멤버십 할인을 받으시겠습니까? (Y/N)
+Y
+
+==============W 편의점================
+상품명 수량 금액
+콜라 3 3,000
+에너지바 5 10,000
+=============증 정===============
+콜라 1
+====================================
+총구매액 8 13,000
+행사할인 -1,000
+멤버십할인 -3,000
+내실돈 9,000
+
+감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)
+Y
+
+안녕하세요. W편의점입니다.
+현재 보유하고 있는 상품입니다.
+
+- 콜라 1,000원 7개 탄산2+1
+- 콜라 1,000원 10개
+- 사이다 1,000원 8개 탄산2+1
+- 사이다 1,000원 7개
+- 오렌지주스 1,800원 9개 MD추천상품
+- 오렌지주스 1,800원 재고 없음
+- 탄산수 1,200원 5개 탄산2+1
+- 탄산수 1,200원 재고 없음
+- 물 500원 10개
+- 비타민워터 1,500원 6개
+- 감자칩 1,500원 5개 반짝할인
+- 감자칩 1,500원 5개
+- 초코바 1,200원 5개 MD추천상품
+- 초코바 1,200원 5개
+- 에너지바 2,000원 재고 없음
+- 정식도시락 6,400원 8개
+- 컵라면 1,700원 1개 MD추천상품
+- 컵라면 1,700원 10개
+
+구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])
+[콜라-10]
+
+현재 콜라 4개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)
+Y
+
+멤버십 할인을 받으시겠습니까? (Y/N)
+N
+
+==============W 편의점================
+상품명 수량 금액
+콜라 10 10,000
+=============증 정===============
+콜라 2
+====================================
+총구매액 10 10,000
+행사할인 -2,000
+멤버십할인 -0
+내실돈 8,000
+
+감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)
+Y
+
+안녕하세요. W편의점입니다.
+현재 보유하고 있는 상품입니다.
+
+- 콜라 1,000원 재고 없음 탄산2+1
+- 콜라 1,000원 7개
+- 사이다 1,000원 8개 탄산2+1
+- 사이다 1,000원 7개
+- 오렌지주스 1,800원 9개 MD추천상품
+- 오렌지주스 1,800원 재고 없음
+- 탄산수 1,200원 5개 탄산2+1
+- 탄산수 1,200원 재고 없음
+- 물 500원 10개
+- 비타민워터 1,500원 6개
+- 감자칩 1,500원 5개 반짝할인
+- 감자칩 1,500원 5개
+- 초코바 1,200원 5개 MD추천상품
+- 초코바 1,200원 5개
+- 에너지바 2,000원 재고 없음
+- 정식도시락 6,400원 8개
+- 컵라면 1,700원 1개 MD추천상품
+- 컵라면 1,700원 10개
+
+구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])
+[오렌지주스-1]
+
+현재 오렌지주스은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)
+Y
+
+멤버십 할인을 받으시겠습니까? (Y/N)
+Y
+
+==============W 편의점================
+상품명 수량 금액
+오렌지주스 2 3,600
+=============증 정===============
+오렌지주스 1
+====================================
+총구매액 2 3,600
+행사할인 -1,800
+멤버십할인 -0
+내실돈 1,800
+
+감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)
+N
+```
+
+## 🛠️ 구현 기능 목록
+### 입력
+- ```camp.nextstep.edu.missionutils.Console```의 ```readLine()``` 으로 입력을 받는다.
+ - 구매할 상품과 수량
+ - ex) [콜라-10],[사이다-3]
+ - Y/N
+ - 프로모션 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, 그 수량만큼 추가 여부
+ - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, 일부 수량에 대해 정가로 결제할지 여부
+ - 멤버십 할인 적용 여부
+ - 추가 구매 여부
+- 잘못된 입력을 받을 시 ```IllegalArgumentException```를 발생시키고 그 부분부터 입력을 다시 받는다.
+ - ```IllegalArgumentException```, ```IllegalStateException``` 과 같은 명확을 유형으로 처리된다.
+### 예외 입력
+- 공통
+ - 빈 입력
+ - 공백이 포함된 입력
+- 구매할 상품
+ - 잘못된 상품명
+- 구매할 수량
+ - 정수가 아닌 값
+ - 재고보다 적은 값
+ - 재고보다 큰 값
+- 구매할 상품과 수량
+ - [상품명-수량],[상품명-수량]이 아닌 잘못된 형식
+- Y/N
+ - Y/N 이외의 문자열
+### 기능
+- 상품 목록과 행사 목록 파일 불러오기
+- 재고관리
+ - 각 상품의 재고 수량을 고려하여 결제 가능 여부 확인
+ - 고객이 상품을 구매할 때마다, 결제된 수량만큼 해당 상품의 재고에서 차감하여 수량 관리
+ - 재고를 차감함으로써 시스템은 최고 재고 상태를 유지하며, 다음 고객이 구매할 때 정확한 재고 정보를 제공
+- 프로모션 할인
+ - 오늘 날짜가 프로모션 기간 내에 포함된 경우에만 할인 제공
+ - 현재 날짜와 시간 가져오기는 ```camp.nextstep.edu.missionutils.DateTimes```의 ```now()``` 활용
+ - 프로모션은 N개 구매 시 1개 무료 증정의 형태로 진행
+ - 1+1 또는 2+1 프로모션이 각각 지정된 상품에 적용되며, 동일 상품에 여러 프로모션 적용되지 않음
+ - 프로모션 혜택은 프로모션 재고 내에서만 적용 가능
+ - 프로모션 기간 중이라면 프로모션 재고 우선적으로 차감
+ - 재고가 부족할 경우 일반 재고 사용
+ - 프로모션 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, 필요한 수량을 추가로 가져오면 혜택을 받을 수 있음을 안내
+ - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, 일부 수량에 대해 정가로 결제하게 됨을 안내
+- 멤버십 할인
+ - 멤버십 회원은 프로모션 미적용 금액의 30%를 할인 받음
+ - 프로모션 적용 후 남은 금액에 대해 멤버십 할인 적용
+ - 멤버십 할인의 최대 한도는 8,000원
+### 출력
+- 환영인사
+- 상품명, 가격, 프로모션 이름, 재고
+- 안내 메시지
+ - 프로모션 적용이 가능한 상품에 대해 고객이 해당 수량만큼 가져오지 않았을 경우
+ - 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우
+ - 멤버십 할인 적용 여부를 확인하기 위한 경우
+- 영수증: 고객의 구매 내역과 할인을 요약하여 출력
+ - 구매 상품 내역
+ - 구매한 상품명
+ - 수량
+ - 가격
+ - 증정 상품 내역
+ - 프로모션에 따라 무료로 제공된 증점 상품 목록
+ - 금액 정보
+ - 총 구매액: 구매한 상품의 총 수량과 총 금액
+ - 행사할인: 프로모션에 의해 할인된 금액
+ - 멤버십할인: 멤버십에 의해 추가로 할인된 금액
+ - 내실돈: 최종 결제 금액
+- ```IllegalArgumentException``` 가 발생할 때 “[ERROR]”로 시작하는 오류 메시지와 함께 상황에 맞는 안내를 출력한다.
+ - 구매할 상품과 수량 형식이 올바르지 않은 경우
+ - ```[ERROR] 올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.```
+ - 존재하지 않는 상품을 입력한 경우
+ - ```[ERROR] 존재하지 않는 상품입니다. 다시 입력해 주세요.```
+ - 구매 수량이 재고 수량을 초과한 경우
+ - ```[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.```
+ - 기타 잘못된 입력의 경우
+ - ```[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.``` | Unknown | 꼼꼼하게 잘 정리하신 거 같아요! |
@@ -0,0 +1,52 @@
+package store.io;
+
+import store.object.Receipt;
+import store.product.Product;
+
+import java.util.List;
+
+public class OutputView {
+ public void greeting() {
+ System.out.println("안녕하세요. W편의점입니다.");
+ System.out.println("현재 보유하고 있는 상품입니다.\n");
+ }
+
+ public void printProducts(List<Product> products) {
+ products.forEach(System.out::println);
+ }
+
+ public void purchaseGuide() {
+ System.out.println("\n구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])");
+ }
+
+ public void promotionAdditionalGuide(String productName) {
+ System.out.printf("\n현재 %s은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)\n", productName);
+ }
+
+ public void promotionImpossibleGuide(String productName, int amount) {
+ System.out.printf("\n현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)\n", productName, amount);
+ }
+
+ public void membershipGuide() {
+ System.out.println("\n멤버십 할인을 받으시겠습니다? (Y/N)");
+ }
+
+ public void printReceipt(Receipt receipt) {
+ System.out.println("\n==============W 편의점================");
+ String productReportFormat = "%-19s%-10s%-6s";
+ System.out.printf((productReportFormat) + "%n", "상품명", "수량", "금액");
+ System.out.printf(receipt.productReport());
+ System.out.println("==============증 정================");
+ System.out.printf(receipt.promotionReport());
+ System.out.println("======================================");
+ System.out.printf(receipt.paymentReport());
+ }
+
+ public void closingGuide() {
+ System.out.println("\n감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)");
+ }
+
+ public void printError(String errorMessage) {
+ System.out.println("\n" + errorMessage);
+ }
+} | Java | `\n`은 OS에 종속적인 개행 문자인 거 같아요!
`System.lineSeparator()`를 활용해보시면 더 좋을 거 같아요! |
@@ -0,0 +1,61 @@
+package store.product;
+
+import store.file.FileReader;
+import store.io.OutputView;
+import store.object.Amount;
+import store.type.ErrorMessage;
+
+import java.util.List;
+import java.util.Map;
+
+public class ProductManager {
+ private final List<Product> products;
+
+ public ProductManager() {
+ FileReader fileReader = new FileReader();
+ products = fileReader.createProduct();
+ }
+
+ public Amount purchase(String name, int amount) {
+ List<Product> purchaseProducts = products.stream()
+ .filter(product -> product.isCorrect(name))
+ .toList();
+
+ isExceed(purchaseProducts, amount);
+ return applyPromotion(purchaseProducts, amount);
+ }
+
+ public Amount applyPromotion(List<Product> purchaseProducts, int amount) {
+ Amount purchaseAmount = purchaseProducts.getFirst().buy(amount);
+ if (purchaseAmount.isAdditional()) {
+ Amount additionalAmount = purchaseProducts.getLast().buy(purchaseAmount.getAdditional());
+ purchaseAmount.addBuyAmount(additionalAmount.getBuy());
+ }
+ return purchaseAmount;
+ }
+
+ public void print() {
+ OutputView outputView = new OutputView();
+ outputView.printProducts(products);
+ }
+
+ public void isExceed(List<Product> purchaseProducts, int amount) {
+ int totalQuantity = 0;
+ for (Product product : purchaseProducts) {
+ totalQuantity += product.getQuantity();
+ }
+ if (totalQuantity < amount) {
+ throw new IllegalArgumentException(ErrorMessage.EXCEED_QUANTITY.getMessage());
+ }
+ }
+
+ public void validate(Map<String, Integer> purchaseData) {
+ for (String productName : purchaseData.keySet()) {
+ boolean exists = products.stream()
+ .anyMatch(product -> product.isExist(productName));
+ if (!exists) {
+ throw new IllegalArgumentException(ErrorMessage.NON_EXISTING_PRODUCT.getMessage());
+ }
+ }
+ }
+} | Java | `ConvenienceStore`에서 `outputview`를 가지고 있는데, 따로 또 생성해서 출력하신 이유가 궁금합니다! |
@@ -0,0 +1,81 @@
+package store.promotion;
+
+import store.io.InputView;
+import store.io.OutputView;
+import store.object.Amount;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+public class Promotion {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public Amount apply(String productName, int price, int quantity, int amount) {
+ int total = buy + get;
+ int maxAmount = quantity / total * total;
+ if (amount <= maxAmount && amount % total == 0) {
+ return new Amount(productName, price, amount, amount / total, 0, 0);
+ }
+ if (amount % total == buy && amount < maxAmount) {
+ return additionalGet(productName, price, quantity, amount, total);
+ }
+ return additionalBuy(productName, price, quantity, amount, total, maxAmount);
+ }
+
+ public Amount additionalGet(String productName, int price, int quantity, int amount, int total) {
+ outputView.promotionAdditionalGuide(productName);
+ if (inputView.readAnswer().equals("Y")) {
+ return new Amount(productName, price, amount + 1, (amount + 1) / total, 0, 0);
+ }
+ return new Amount(productName, price, amount, amount / total, 0, 0);
+ }
+
+ public Amount additionalBuy(String productName, int price, int quantity, int amount, int total, int maxAmount) {
+ int impossibleAmount = calcImpossibleAmount(amount, total, maxAmount);
+ outputView.promotionImpossibleGuide(productName, impossibleAmount);
+ if (inputView.readAnswer().trim().equals("Y")) {
+ if (quantity - (amount - impossibleAmount) < impossibleAmount) {
+ return new Amount(productName, price, quantity, (amount - impossibleAmount) / total, amount - quantity, impossibleAmount);
+ }
+ return new Amount(productName, price, amount, (amount - impossibleAmount) / total, 0, impossibleAmount);
+ }
+ return new Amount(productName, price, amount - impossibleAmount, (amount - impossibleAmount) / total, 0, 0);
+ }
+
+ public int calcImpossibleAmount(int amount, int total, int maxAmount) {
+ int impossibleAmount = amount % total;
+ if (amount > maxAmount) {
+ impossibleAmount = amount - maxAmount;
+ }
+ return impossibleAmount;
+ }
+
+ public boolean isPossible(LocalDateTime now) {
+ LocalDate nowDate = now.toLocalDate();
+ return (startDate.isBefore(nowDate) || startDate.isEqual(nowDate)) &&
+ (endDate.isAfter(nowDate) || endDate.isEqual(nowDate));
+ }
+
+ public boolean isMatch(String promotion) {
+ return promotion.equals(name);
+ }
+
+ @Override
+ public String toString() {
+ return this.name;
+ }
+} | Java | `toLocalDate`메서드를 잘 활용하신 부분이 인상적입니다! |
@@ -0,0 +1,18 @@
+package store.type;
+
+public enum ProductType {
+ NAME(0),
+ PRICE(1),
+ QUANTITY(2),
+ PROMOTION(3);
+
+ private final int value;
+
+ ProductType(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+} | Java | split한 배열을 접근할 인덱스를 enum으로 만드신 점이 인상적입니다!
`value`는 의미가 명확하지 않은 거 같아요!
`index`는 어떨까요? |
@@ -0,0 +1,24 @@
+package store.file;
+
+import store.product.Product;
+import store.promotion.Promotion;
+import store.promotion.PromotionManager;
+
+import java.io.InputStream;
+import java.util.List;
+
+public class FileReader {
+ public List<Product> createProduct() {
+ ProductParser productParser = new ProductParser(new PromotionManager(createPromotion()));
+ return productParser.read(road("products"));
+ }
+
+ public List<Promotion> createPromotion() {
+ PromotionParser promotionParser = new PromotionParser();
+ return promotionParser.read(road("promotions"));
+ }
+
+ public InputStream road(String filename) {
+ return getClass().getClassLoader().getResourceAsStream(filename + ".md");
+ }
+} | Java | 혹시 `load`나 `read`를 잘못 작성하신 부분일까요? |
@@ -0,0 +1,45 @@
+package store.io;
+
+import camp.nextstep.edu.missionutils.Console;
+import store.type.ErrorMessage;
+
+public class InputView {
+ private final OutputView outputView = new OutputView();
+
+ public String readAnswer() {
+ while (true) {
+ try {
+ String input = Console.readLine();
+ answerValidate(input);
+ return input;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public String readPurchaseProduct() {
+ while (true) {
+ try {
+ String input = Console.readLine();
+ purchaseProductValidate(input);
+ return input;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void answerValidate(String input) {
+ if (!"Y".equals(input) && !"N".equals(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_INPUT.getMessage());
+ }
+ }
+
+ public void purchaseProductValidate(String input) {
+ String regex = "\\[([a-zA-Z가-힣]+-[1-9][0-9]*)\\](,\\[([a-zA-Z가-힣]+-[1-9][0-9]*)\\])*";
+ if (!input.matches(regex)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FORMAT.getMessage());
+ }
+ }
+} | Java | while-true 부분이 반복되어서 함수형 인터페이스도 활용해보시면 유지보수에 더 좋을 거 같아요! |
@@ -0,0 +1,77 @@
+package store.object;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Receipt {
+ private final List<Amount> amounts = new ArrayList<>();
+ private boolean membershipDiscount;
+ private int totalPrice = 0;
+ private int totalBuyAmount = 0;
+ private int promotionPrice = 0;
+ private int membershipAvailablePrice = 0;
+ private int membershipPrice = 0;
+ private int payment = 0;
+
+ public void addAmount(Amount amount) {
+ if (amount.isPurchase()) {
+ amounts.add(amount);
+ }
+ }
+
+ public void membershipApply(String input) {
+ if (input.equals("Y")) {
+ membershipDiscount = true;
+ }
+ }
+
+ public String productReport() {
+ StringBuilder productReport = new StringBuilder();
+ amounts.forEach(amount -> productReport.append(amount.parseProductDetails()));
+ return productReport.toString();
+ }
+
+ public String promotionReport() {
+ StringBuilder promotionReport = new StringBuilder();
+ amounts.forEach(amount -> promotionReport.append(amount.parsePromotionDetails()));
+ return promotionReport.toString();
+ }
+
+ public String paymentReport() {
+ calcPayment();
+ return parsePaymentDetails();
+ }
+
+ public void calcPayment() {
+ amounts.forEach(amount -> totalPrice += amount.totalPrice());
+ amounts.forEach(amount -> totalBuyAmount += amount.getBuy());
+ amounts.forEach(amount -> promotionPrice += amount.promotionPrice());
+ calcMembershipPrice();
+
+ payment = totalPrice - promotionPrice - membershipPrice;
+ }
+
+ public void calcMembershipPrice() {
+ amounts.forEach(amount -> membershipAvailablePrice += amount.membershipAvailablePrice());
+ if (membershipDiscount) {
+ membershipPrice = (int) Math.floor(membershipAvailablePrice * 0.3);
+ }
+ if (membershipPrice > 8000) {
+ membershipPrice = 8000;
+ }
+ }
+
+ public String parsePaymentDetails() {
+ StringBuilder paymentReport = new StringBuilder();
+ String totalPriceFormat = "%-19s%-10d%,-6d";
+ String otherPriceFormat = "%-29s%s%,-6d";
+ return (paymentReport.append(String.format(totalPriceFormat, "총구매액", totalBuyAmount, totalPrice)).append("\n")
+ .append(String.format(otherPriceFormat, "행사할인", "-", promotionPrice)).append("\n")
+ .append(String.format(otherPriceFormat, "멤버십할인", "-", membershipPrice)).append("\n")
+ .append(String.format(otherPriceFormat, "내실돈", "", payment)).append("\n")).toString();
+ }
+
+ public boolean isExistence() {
+ return amounts.size() > 0;
+ }
+} | Java | `0.3`과 `8000`는 상수화하시면 의미가 더 명확해질 거 같아요! |
@@ -0,0 +1,80 @@
+package store;
+
+import camp.nextstep.edu.missionutils.Console;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import store.object.ConvenienceStore;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ReceiptTest {
+ private static ByteArrayOutputStream outputStream;
+
+ @BeforeEach
+ void setUpStream() {
+ outputStream = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outputStream));
+ }
+
+ @AfterEach
+ void restoreStream() {
+ Console.close();
+ System.setOut(System.out);
+ }
+
+ @ParameterizedTest
+ @CsvSource(value = {"3,1", "4,1", "10,3", "12,3"})
+ void 영수증으로_고객의_구매와_증정_내역_보기(int amount, int promotionAmount) {
+ String yes = "Y\n";
+ String input = yes + yes;
+ System.setIn(new ByteArrayInputStream(input.getBytes()));
+
+ ConvenienceStore convenienceStore = new ConvenienceStore();
+ convenienceStore.init();
+ Map<String, Integer> purchaseData = Map.of(
+ "콜라", amount
+ );
+ convenienceStore.createReceipt(purchaseData);
+ convenienceStore.showReceipt();
+
+ String expectedProduct = String.format("콜라%d%,d", amount, amount * 1000);
+ String expectedPromotion = String.format("콜라%d", promotionAmount);
+
+ assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedProduct));
+ assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedPromotion));
+ }
+
+ @Test
+ void 영수증으로_금액_정보_보기() {
+ String yes = "Y\n";
+ String input = yes + yes;
+ System.setIn(new ByteArrayInputStream(input.getBytes()));
+
+ ConvenienceStore convenienceStore = new ConvenienceStore();
+ convenienceStore.init();
+ Map<String, Integer> purchaseData = Map.of(
+ "콜라", 3,
+ "에너지바", 5
+ );
+ convenienceStore.createReceipt(purchaseData);
+ convenienceStore.showReceipt();
+
+ String expectedReceipt = "총구매액813,000";
+ String expectedPromotion = "행사할인-1,000";
+ String expectedMembership = "멤버십할인-3,000";
+ String expectedPayment = "내실돈9,000";
+
+ assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedReceipt));
+ assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedPromotion));
+ assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedMembership));
+ assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedPayment));
+ }
+} | Java | 꼼꼼한 테스트가 인상적입니다!
사소한 부분이지만, 위에 있는 assert가 실패하면 밑에 있는 assert는 실행되지 않을 거 같아요!
assertAll도 활용해보시면 더 좋을 거 같아요! |
@@ -0,0 +1,82 @@
+package store.object;
+
+import store.io.InputParser;
+import store.io.InputView;
+import store.io.OutputView;
+import store.product.ProductManager;
+
+import java.util.Map;
+
+public class ConvenienceStore {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final InputParser inputParser = new InputParser();
+ private final ProductManager productManager = new ProductManager();
+ private Receipt receipt;
+ private boolean isOpen = true;
+
+ public void open() {
+ while (isOpen) {
+ init();
+ announcement();
+ purchase();
+ close();
+ System.out.println();
+ }
+ }
+
+ public void init() {
+ receipt = new Receipt();
+ }
+
+ public void announcement() {
+ outputView.greeting();
+ productManager.print();
+ }
+
+ public void purchase() {
+ outputView.purchaseGuide();
+ while (true) {
+ try {
+ inputHandle();
+ return;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void inputHandle() {
+ String purchaseProducts = inputView.readPurchaseProduct();
+ Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts);
+ productManager.validate(purchaseData);
+ createReceipt(purchaseData);
+ }
+
+ public void createReceipt(Map<String, Integer> purchaseData) {
+ purchaseData.forEach((name, amount) -> {
+ Amount purchaseAmount = productManager.purchase(name, amount);
+ receipt.addAmount(purchaseAmount);
+ });
+ if (receipt.isExistence()) {
+ membership();
+ showReceipt();
+ }
+ }
+
+ public void membership() {
+ outputView.membershipGuide();
+ receipt.membershipApply(inputView.readAnswer().trim());
+ }
+
+ public void showReceipt() {
+ outputView.printReceipt(receipt);
+ }
+
+ public void close() {
+ outputView.closingGuide();
+ if (inputView.readAnswer().equals("N")) {
+ isOpen = false;
+ }
+ }
+} | Java | 추출하기보다 그대로 쓰는 게 가독성 측면으로 더 괜찮아보이는데, 어떻게 생각하시나요? |
@@ -0,0 +1,61 @@
+package store.product;
+
+import store.file.FileReader;
+import store.io.OutputView;
+import store.object.Amount;
+import store.type.ErrorMessage;
+
+import java.util.List;
+import java.util.Map;
+
+public class ProductManager {
+ private final List<Product> products;
+
+ public ProductManager() {
+ FileReader fileReader = new FileReader();
+ products = fileReader.createProduct();
+ }
+
+ public Amount purchase(String name, int amount) {
+ List<Product> purchaseProducts = products.stream()
+ .filter(product -> product.isCorrect(name))
+ .toList();
+
+ isExceed(purchaseProducts, amount);
+ return applyPromotion(purchaseProducts, amount);
+ }
+
+ public Amount applyPromotion(List<Product> purchaseProducts, int amount) {
+ Amount purchaseAmount = purchaseProducts.getFirst().buy(amount);
+ if (purchaseAmount.isAdditional()) {
+ Amount additionalAmount = purchaseProducts.getLast().buy(purchaseAmount.getAdditional());
+ purchaseAmount.addBuyAmount(additionalAmount.getBuy());
+ }
+ return purchaseAmount;
+ }
+
+ public void print() {
+ OutputView outputView = new OutputView();
+ outputView.printProducts(products);
+ }
+
+ public void isExceed(List<Product> purchaseProducts, int amount) {
+ int totalQuantity = 0;
+ for (Product product : purchaseProducts) {
+ totalQuantity += product.getQuantity();
+ }
+ if (totalQuantity < amount) {
+ throw new IllegalArgumentException(ErrorMessage.EXCEED_QUANTITY.getMessage());
+ }
+ }
+
+ public void validate(Map<String, Integer> purchaseData) {
+ for (String productName : purchaseData.keySet()) {
+ boolean exists = products.stream()
+ .anyMatch(product -> product.isExist(productName));
+ if (!exists) {
+ throw new IllegalArgumentException(ErrorMessage.NON_EXISTING_PRODUCT.getMessage());
+ }
+ }
+ }
+} | Java | ```suggestion
products.stream()
.findAny(product -> product.isExist(productName))
.orElseThrow(() -> new IllegalArgumentException());
```
이 형태로 더 간단하게 만드는 방식을 사용해도 괜찮을 것 같습니다. |
@@ -0,0 +1,18 @@
+package store.promotion;
+
+import java.util.List;
+
+public class PromotionManager {
+ private final List<Promotion> promotions;
+
+ public PromotionManager(List<Promotion> promotions) {
+ this.promotions = promotions;
+ }
+
+ public Promotion match(String promotion) {
+ return promotions.stream()
+ .filter(p -> p.isMatch(promotion))
+ .findFirst()
+ .orElse(null);
+ }
+} | Java | 굳이 null로 리턴하시는 이유가 있을까요? 클라이언트가 null에 대한 대비가 안되어있다면 NPE가 발생할텐데, 여기서 바로 예외를 던지는 것은 어떠신가요? |
@@ -0,0 +1,19 @@
+package store.type;
+
+public enum PromotionType {
+ NAME(0),
+ GET(1),
+ BUY(2),
+ START_DATE(3),
+ END_DATE(4);
+
+ private final int value;
+
+ PromotionType(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+} | Java | 이걸 굳이 enum으로 만드신 의도가 있나요? 딱히 enumeric해보이지 않습니다.. |
@@ -1,7 +1,11 @@
package store;
+import store.object.ConvenienceStore;
+
public class Application {
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ ConvenienceStore convenienceStore = new ConvenienceStore();
+ convenienceStore.open();
+ System.out.println();
}
-}
+}
\ No newline at end of file | Java | 이 부분은 왜 있는건지 궁금합니다! |
@@ -0,0 +1,24 @@
+package store.file;
+
+import store.product.Product;
+import store.promotion.Promotion;
+import store.promotion.PromotionManager;
+
+import java.io.InputStream;
+import java.util.List;
+
+public class FileReader {
+ public List<Product> createProduct() {
+ ProductParser productParser = new ProductParser(new PromotionManager(createPromotion()));
+ return productParser.read(road("products"));
+ }
+
+ public List<Promotion> createPromotion() {
+ PromotionParser promotionParser = new PromotionParser();
+ return promotionParser.read(road("promotions"));
+ }
+
+ public InputStream road(String filename) {
+ return getClass().getClassLoader().getResourceAsStream(filename + ".md");
+ }
+} | Java | 파일명을 상수로 따로 저장해두면 더 좋을 것 같습니다. |
@@ -0,0 +1,24 @@
+package store.file;
+
+import store.product.Product;
+import store.promotion.Promotion;
+import store.promotion.PromotionManager;
+
+import java.io.InputStream;
+import java.util.List;
+
+public class FileReader {
+ public List<Product> createProduct() {
+ ProductParser productParser = new ProductParser(new PromotionManager(createPromotion()));
+ return productParser.read(road("products"));
+ }
+
+ public List<Promotion> createPromotion() {
+ PromotionParser promotionParser = new PromotionParser();
+ return promotionParser.read(road("promotions"));
+ }
+
+ public InputStream road(String filename) {
+ return getClass().getClassLoader().getResourceAsStream(filename + ".md");
+ }
+} | Java | 찾아보니 파일을 읽어오는 방법이더라고요. 처음봐서 신기했어요 |
@@ -0,0 +1,43 @@
+package store.file;
+
+import store.product.Product;
+import store.promotion.Promotion;
+import store.promotion.PromotionManager;
+import store.type.ProductType;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ProductParser {
+ private final PromotionManager promotionManager;
+
+ public ProductParser(PromotionManager promotionManager) {
+ this.promotionManager = promotionManager;
+ }
+
+ public List<Product> read(InputStream productsInputStream) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) {
+ return reader.lines()
+ .skip(1)
+ .map(this::parse)
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ return Collections.emptyList();
+ }
+ }
+
+ public Product parse(String product) {
+ String[] productParts = product.split(",");
+ String name = productParts[ProductType.NAME.getValue()];
+ int price = Integer.parseInt(productParts[ProductType.PRICE.getValue()]);
+ int quantity = Integer.parseInt(productParts[ProductType.QUANTITY.getValue()]);
+ Promotion promotion = promotionManager.match(productParts[ProductType.PROMOTION.getValue()]);
+
+ return new Product(name, price, quantity, promotion);
+ }
+} | Java | readLine을 사용해 읽을때보다 stream을 활용하면 skip(1)을 통해 더 깔끔한 코드가 되는게 정말 좋은 것 같습니다.
skip(1)에서 1을 titleLine과 같은 상수로 처리해버린다면 가독성이 더욱 좋아질 것 같습니다. |
@@ -0,0 +1,43 @@
+package store.file;
+
+import store.product.Product;
+import store.promotion.Promotion;
+import store.promotion.PromotionManager;
+import store.type.ProductType;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ProductParser {
+ private final PromotionManager promotionManager;
+
+ public ProductParser(PromotionManager promotionManager) {
+ this.promotionManager = promotionManager;
+ }
+
+ public List<Product> read(InputStream productsInputStream) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) {
+ return reader.lines()
+ .skip(1)
+ .map(this::parse)
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ return Collections.emptyList();
+ }
+ }
+
+ public Product parse(String product) {
+ String[] productParts = product.split(",");
+ String name = productParts[ProductType.NAME.getValue()];
+ int price = Integer.parseInt(productParts[ProductType.PRICE.getValue()]);
+ int quantity = Integer.parseInt(productParts[ProductType.QUANTITY.getValue()]);
+ Promotion promotion = promotionManager.match(productParts[ProductType.PROMOTION.getValue()]);
+
+ return new Product(name, price, quantity, promotion);
+ }
+} | Java | getValue보다 getIdx와 같은 메서드로 만들어진다면 더 좋을 것 같습니다 |
@@ -0,0 +1,43 @@
+package store.file;
+
+import store.product.Product;
+import store.promotion.Promotion;
+import store.promotion.PromotionManager;
+import store.type.ProductType;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ProductParser {
+ private final PromotionManager promotionManager;
+
+ public ProductParser(PromotionManager promotionManager) {
+ this.promotionManager = promotionManager;
+ }
+
+ public List<Product> read(InputStream productsInputStream) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) {
+ return reader.lines()
+ .skip(1)
+ .map(this::parse)
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ return Collections.emptyList();
+ }
+ }
+
+ public Product parse(String product) {
+ String[] productParts = product.split(",");
+ String name = productParts[ProductType.NAME.getValue()];
+ int price = Integer.parseInt(productParts[ProductType.PRICE.getValue()]);
+ int quantity = Integer.parseInt(productParts[ProductType.QUANTITY.getValue()]);
+ Promotion promotion = promotionManager.match(productParts[ProductType.PROMOTION.getValue()]);
+
+ return new Product(name, price, quantity, promotion);
+ }
+} | Java | 이것도 상수로 만든다면 더 좋을 것 같아요 |
@@ -0,0 +1,47 @@
+package store.file;
+
+import store.promotion.Promotion;
+import store.type.PromotionType;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class PromotionParser {
+ public List<Promotion> read(InputStream productsInputStream) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) {
+ return reader.lines()
+ .skip(1)
+ .map(this::parse)
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ return Collections.emptyList();
+ }
+ }
+
+ public Promotion parse(String promotion) {
+ String[] promotionParts = promotion.split(",");
+ String name = promotionParts[PromotionType.NAME.getValue()];
+ int get = Integer.parseInt(promotionParts[PromotionType.GET.getValue()]);
+ int buy = Integer.parseInt(promotionParts[PromotionType.BUY.getValue()]);
+ LocalDate startDate = formatDate(promotionParts[PromotionType.START_DATE.getValue()]);
+ LocalDate endDate = formatDate(promotionParts[PromotionType.END_DATE.getValue()]);
+
+ return new Promotion(name, get, buy, startDate, endDate);
+ }
+
+ public LocalDate formatDate(String date) {
+ try {
+ DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ return LocalDate.parse(date, dateFormat);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+} | Java | 예외처리로 단순히 메세지를 보여주고 종료하는 것이 아닌 빈 리스트를 만들어 넘기는 부분에서 좋은 것 같습니다. 하지만 파일이 비어서 빈 리스트를 나타낸 것인지 파일을 읽다가 오류가 나서 빈 리스트인지에 대한 구분이 필요하다 생각해 추가적인 메세지를 띄우는 것이나 차이점을 만든다면 더 좋을 것 같습니다. |
@@ -0,0 +1,47 @@
+package store.file;
+
+import store.promotion.Promotion;
+import store.type.PromotionType;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class PromotionParser {
+ public List<Promotion> read(InputStream productsInputStream) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) {
+ return reader.lines()
+ .skip(1)
+ .map(this::parse)
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ return Collections.emptyList();
+ }
+ }
+
+ public Promotion parse(String promotion) {
+ String[] promotionParts = promotion.split(",");
+ String name = promotionParts[PromotionType.NAME.getValue()];
+ int get = Integer.parseInt(promotionParts[PromotionType.GET.getValue()]);
+ int buy = Integer.parseInt(promotionParts[PromotionType.BUY.getValue()]);
+ LocalDate startDate = formatDate(promotionParts[PromotionType.START_DATE.getValue()]);
+ LocalDate endDate = formatDate(promotionParts[PromotionType.END_DATE.getValue()]);
+
+ return new Promotion(name, get, buy, startDate, endDate);
+ }
+
+ public LocalDate formatDate(String date) {
+ try {
+ DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ return LocalDate.parse(date, dateFormat);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+} | Java | 단순히 null을 내보낸다면 에러를 잡아내기 어려울 수 있다고 생각합니다 추가적인 예외처리가 필요하다고 생각합니다. |
@@ -0,0 +1,45 @@
+package store.io;
+
+import camp.nextstep.edu.missionutils.Console;
+import store.type.ErrorMessage;
+
+public class InputView {
+ private final OutputView outputView = new OutputView();
+
+ public String readAnswer() {
+ while (true) {
+ try {
+ String input = Console.readLine();
+ answerValidate(input);
+ return input;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public String readPurchaseProduct() {
+ while (true) {
+ try {
+ String input = Console.readLine();
+ purchaseProductValidate(input);
+ return input;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void answerValidate(String input) {
+ if (!"Y".equals(input) && !"N".equals(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_INPUT.getMessage());
+ }
+ }
+
+ public void purchaseProductValidate(String input) {
+ String regex = "\\[([a-zA-Z가-힣]+-[1-9][0-9]*)\\](,\\[([a-zA-Z가-힣]+-[1-9][0-9]*)\\])*";
+ if (!input.matches(regex)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FORMAT.getMessage());
+ }
+ }
+} | Java | 메서드에서 매번 생성되는 것보다는 상수로 올려두는 것은 어떤가요? 필드에 모여있으면 찾기도 편해서 더 좋을 것 같습니다. |
@@ -0,0 +1,45 @@
+package store.io;
+
+import camp.nextstep.edu.missionutils.Console;
+import store.type.ErrorMessage;
+
+public class InputView {
+ private final OutputView outputView = new OutputView();
+
+ public String readAnswer() {
+ while (true) {
+ try {
+ String input = Console.readLine();
+ answerValidate(input);
+ return input;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public String readPurchaseProduct() {
+ while (true) {
+ try {
+ String input = Console.readLine();
+ purchaseProductValidate(input);
+ return input;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void answerValidate(String input) {
+ if (!"Y".equals(input) && !"N".equals(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_INPUT.getMessage());
+ }
+ }
+
+ public void purchaseProductValidate(String input) {
+ String regex = "\\[([a-zA-Z가-힣]+-[1-9][0-9]*)\\](,\\[([a-zA-Z가-힣]+-[1-9][0-9]*)\\])*";
+ if (!input.matches(regex)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FORMAT.getMessage());
+ }
+ }
+} | Java | Y와 N을 상수로 올리시면 좋을 것 같습니다. 프로그래밍 요구사항에 상수화가 있어서 참고하시면 좋을 것 같습니다 |
@@ -0,0 +1,52 @@
+package store.io;
+
+import store.object.Receipt;
+import store.product.Product;
+
+import java.util.List;
+
+public class OutputView {
+ public void greeting() {
+ System.out.println("안녕하세요. W편의점입니다.");
+ System.out.println("현재 보유하고 있는 상품입니다.\n");
+ }
+
+ public void printProducts(List<Product> products) {
+ products.forEach(System.out::println);
+ }
+
+ public void purchaseGuide() {
+ System.out.println("\n구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])");
+ }
+
+ public void promotionAdditionalGuide(String productName) {
+ System.out.printf("\n현재 %s은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)\n", productName);
+ }
+
+ public void promotionImpossibleGuide(String productName, int amount) {
+ System.out.printf("\n현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)\n", productName, amount);
+ }
+
+ public void membershipGuide() {
+ System.out.println("\n멤버십 할인을 받으시겠습니다? (Y/N)");
+ }
+
+ public void printReceipt(Receipt receipt) {
+ System.out.println("\n==============W 편의점================");
+ String productReportFormat = "%-19s%-10s%-6s";
+ System.out.printf((productReportFormat) + "%n", "상품명", "수량", "금액");
+ System.out.printf(receipt.productReport());
+ System.out.println("==============증 정================");
+ System.out.printf(receipt.promotionReport());
+ System.out.println("======================================");
+ System.out.printf(receipt.paymentReport());
+ }
+
+ public void closingGuide() {
+ System.out.println("\n감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)");
+ }
+
+ public void printError(String errorMessage) {
+ System.out.println("\n" + errorMessage);
+ }
+} | Java | toString을 활용한 깔끔한 처리가 좋은 것 같아요. 한가지 아쉽다면 StringBuilder와 같은 클래스를 사용해 출력할 메세지들을 모아서 한번에 출력하는데 IO작업이 줄어들어 더욱 좋을 것 같습니다. |
@@ -0,0 +1,82 @@
+package store.object;
+
+import store.io.InputParser;
+import store.io.InputView;
+import store.io.OutputView;
+import store.product.ProductManager;
+
+import java.util.Map;
+
+public class ConvenienceStore {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final InputParser inputParser = new InputParser();
+ private final ProductManager productManager = new ProductManager();
+ private Receipt receipt;
+ private boolean isOpen = true;
+
+ public void open() {
+ while (isOpen) {
+ init();
+ announcement();
+ purchase();
+ close();
+ System.out.println();
+ }
+ }
+
+ public void init() {
+ receipt = new Receipt();
+ }
+
+ public void announcement() {
+ outputView.greeting();
+ productManager.print();
+ }
+
+ public void purchase() {
+ outputView.purchaseGuide();
+ while (true) {
+ try {
+ inputHandle();
+ return;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void inputHandle() {
+ String purchaseProducts = inputView.readPurchaseProduct();
+ Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts);
+ productManager.validate(purchaseData);
+ createReceipt(purchaseData);
+ }
+
+ public void createReceipt(Map<String, Integer> purchaseData) {
+ purchaseData.forEach((name, amount) -> {
+ Amount purchaseAmount = productManager.purchase(name, amount);
+ receipt.addAmount(purchaseAmount);
+ });
+ if (receipt.isExistence()) {
+ membership();
+ showReceipt();
+ }
+ }
+
+ public void membership() {
+ outputView.membershipGuide();
+ receipt.membershipApply(inputView.readAnswer().trim());
+ }
+
+ public void showReceipt() {
+ outputView.printReceipt(receipt);
+ }
+
+ public void close() {
+ outputView.closingGuide();
+ if (inputView.readAnswer().equals("N")) {
+ isOpen = false;
+ }
+ }
+} | Java | 얘도 출력을 담당하는 부분이라 OutputView에 넣어 사용하면 더 좋을 것 같습니다. |
@@ -0,0 +1,82 @@
+package store.object;
+
+import store.io.InputParser;
+import store.io.InputView;
+import store.io.OutputView;
+import store.product.ProductManager;
+
+import java.util.Map;
+
+public class ConvenienceStore {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final InputParser inputParser = new InputParser();
+ private final ProductManager productManager = new ProductManager();
+ private Receipt receipt;
+ private boolean isOpen = true;
+
+ public void open() {
+ while (isOpen) {
+ init();
+ announcement();
+ purchase();
+ close();
+ System.out.println();
+ }
+ }
+
+ public void init() {
+ receipt = new Receipt();
+ }
+
+ public void announcement() {
+ outputView.greeting();
+ productManager.print();
+ }
+
+ public void purchase() {
+ outputView.purchaseGuide();
+ while (true) {
+ try {
+ inputHandle();
+ return;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void inputHandle() {
+ String purchaseProducts = inputView.readPurchaseProduct();
+ Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts);
+ productManager.validate(purchaseData);
+ createReceipt(purchaseData);
+ }
+
+ public void createReceipt(Map<String, Integer> purchaseData) {
+ purchaseData.forEach((name, amount) -> {
+ Amount purchaseAmount = productManager.purchase(name, amount);
+ receipt.addAmount(purchaseAmount);
+ });
+ if (receipt.isExistence()) {
+ membership();
+ showReceipt();
+ }
+ }
+
+ public void membership() {
+ outputView.membershipGuide();
+ receipt.membershipApply(inputView.readAnswer().trim());
+ }
+
+ public void showReceipt() {
+ outputView.printReceipt(receipt);
+ }
+
+ public void close() {
+ outputView.closingGuide();
+ if (inputView.readAnswer().equals("N")) {
+ isOpen = false;
+ }
+ }
+} | Java | 입력 파라미터에 넣지 않기위해 필드에 넣으신 느낌인데 지역 변수로 사용하는게 더 좋을 것 같습니다. |
@@ -0,0 +1,82 @@
+package store.object;
+
+import store.io.InputParser;
+import store.io.InputView;
+import store.io.OutputView;
+import store.product.ProductManager;
+
+import java.util.Map;
+
+public class ConvenienceStore {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final InputParser inputParser = new InputParser();
+ private final ProductManager productManager = new ProductManager();
+ private Receipt receipt;
+ private boolean isOpen = true;
+
+ public void open() {
+ while (isOpen) {
+ init();
+ announcement();
+ purchase();
+ close();
+ System.out.println();
+ }
+ }
+
+ public void init() {
+ receipt = new Receipt();
+ }
+
+ public void announcement() {
+ outputView.greeting();
+ productManager.print();
+ }
+
+ public void purchase() {
+ outputView.purchaseGuide();
+ while (true) {
+ try {
+ inputHandle();
+ return;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ public void inputHandle() {
+ String purchaseProducts = inputView.readPurchaseProduct();
+ Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts);
+ productManager.validate(purchaseData);
+ createReceipt(purchaseData);
+ }
+
+ public void createReceipt(Map<String, Integer> purchaseData) {
+ purchaseData.forEach((name, amount) -> {
+ Amount purchaseAmount = productManager.purchase(name, amount);
+ receipt.addAmount(purchaseAmount);
+ });
+ if (receipt.isExistence()) {
+ membership();
+ showReceipt();
+ }
+ }
+
+ public void membership() {
+ outputView.membershipGuide();
+ receipt.membershipApply(inputView.readAnswer().trim());
+ }
+
+ public void showReceipt() {
+ outputView.printReceipt(receipt);
+ }
+
+ public void close() {
+ outputView.closingGuide();
+ if (inputView.readAnswer().equals("N")) {
+ isOpen = false;
+ }
+ }
+} | Java | 얘를 boolean을 반환하게 해서 처리했다면 isOpen은 필드로 안나가도 되지 않았을까요? |
@@ -0,0 +1,69 @@
+package store.product;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import store.object.Amount;
+import store.promotion.Promotion;
+import store.type.ErrorMessage;
+
+import java.util.Optional;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int quantity;
+ private final Promotion promotion;
+
+ public Product(String name, int price, int quantity, Promotion promotion) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotion = promotion;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Amount buy(int amount) {
+ if (promotion != null) {
+ return promotionBuy(amount);
+ }
+ isExceed(amount);
+ quantity -= amount;
+ return new Amount(name, price, amount, 0, 0, amount);
+ }
+
+ public Amount promotionBuy(int amount) {
+ if (promotion.isPossible(DateTimes.now())) {
+ Amount purchaseAmount = promotion.apply(name, price, quantity, amount);
+ quantity -= purchaseAmount.getBuy();
+ return purchaseAmount;
+ }
+ return new Amount(name, price, 0, 0, amount, 0);
+ }
+
+ public boolean isCorrect(String name) {
+ return name.equals(this.name);
+ }
+
+ public void isExceed(int amount) {
+ if (amount > quantity) {
+ throw new IllegalArgumentException(ErrorMessage.EXCEED_QUANTITY.getMessage());
+ }
+ }
+
+ public boolean isExist(String otherName) {
+ return this.name.equals(otherName);
+ }
+
+ @Override
+ public String toString() {
+ String promotionName = Optional.ofNullable(promotion)
+ .map(Promotion::toString)
+ .orElse("");
+ if (quantity == 0) {
+ return String.format("- %s %,d원 재고 없음 %s", name, price, promotionName).trim();
+ }
+ return String.format("- %s %,d원 %d개 %s", name, price, quantity, promotionName).trim();
+ }
+} | Java | 코드에 입력 파라미터로 0과 같은 특정한 값이 들어가는 경우 가독성을 매우 해친다고 생각합니다. 이보다는 Amount의 생성자를 0, 0을 넣지 않으면 자동으로 0이 들어가도록 작성해보는 것은 어떨까요? |
@@ -0,0 +1,81 @@
+package store.promotion;
+
+import store.io.InputView;
+import store.io.OutputView;
+import store.object.Amount;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+public class Promotion {
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public Amount apply(String productName, int price, int quantity, int amount) {
+ int total = buy + get;
+ int maxAmount = quantity / total * total;
+ if (amount <= maxAmount && amount % total == 0) {
+ return new Amount(productName, price, amount, amount / total, 0, 0);
+ }
+ if (amount % total == buy && amount < maxAmount) {
+ return additionalGet(productName, price, quantity, amount, total);
+ }
+ return additionalBuy(productName, price, quantity, amount, total, maxAmount);
+ }
+
+ public Amount additionalGet(String productName, int price, int quantity, int amount, int total) {
+ outputView.promotionAdditionalGuide(productName);
+ if (inputView.readAnswer().equals("Y")) {
+ return new Amount(productName, price, amount + 1, (amount + 1) / total, 0, 0);
+ }
+ return new Amount(productName, price, amount, amount / total, 0, 0);
+ }
+
+ public Amount additionalBuy(String productName, int price, int quantity, int amount, int total, int maxAmount) {
+ int impossibleAmount = calcImpossibleAmount(amount, total, maxAmount);
+ outputView.promotionImpossibleGuide(productName, impossibleAmount);
+ if (inputView.readAnswer().trim().equals("Y")) {
+ if (quantity - (amount - impossibleAmount) < impossibleAmount) {
+ return new Amount(productName, price, quantity, (amount - impossibleAmount) / total, amount - quantity, impossibleAmount);
+ }
+ return new Amount(productName, price, amount, (amount - impossibleAmount) / total, 0, impossibleAmount);
+ }
+ return new Amount(productName, price, amount - impossibleAmount, (amount - impossibleAmount) / total, 0, 0);
+ }
+
+ public int calcImpossibleAmount(int amount, int total, int maxAmount) {
+ int impossibleAmount = amount % total;
+ if (amount > maxAmount) {
+ impossibleAmount = amount - maxAmount;
+ }
+ return impossibleAmount;
+ }
+
+ public boolean isPossible(LocalDateTime now) {
+ LocalDate nowDate = now.toLocalDate();
+ return (startDate.isBefore(nowDate) || startDate.isEqual(nowDate)) &&
+ (endDate.isAfter(nowDate) || endDate.isEqual(nowDate));
+ }
+
+ public boolean isMatch(String promotion) {
+ return promotion.equals(name);
+ }
+
+ @Override
+ public String toString() {
+ return this.name;
+ }
+} | Java | ```suggestion
return !startDate.isAfter(nowDate) &&
!endDate.isBefore(nowDate);
```
이렇게 바꾸면 더 깔끔하게 코드를 만들 수 있을 것 같습니다 |
@@ -0,0 +1,19 @@
+package store.type;
+
+public enum PromotionType {
+ NAME(0),
+ GET(1),
+ BUY(2),
+ START_DATE(3),
+ END_DATE(4);
+
+ private final int value;
+
+ PromotionType(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+} | Java | 저도 이 부분은 그냥 필드로 작성하셨어도 괜찮다고 생각합니다 |
@@ -3,38 +3,52 @@
import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent;
import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase;
import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand;
-import jakarta.annotation.PostConstruct;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import lombok.RequiredArgsConstructor;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
-@RequiredArgsConstructor
public class InMemoryMessageQueue {
- private final PostSystemUsecase postSystemUsecase;
- private final BlockingQueue<ViewPostEvent> queue;
- private final ExecutorService executorService = Executors.newSingleThreadExecutor();
+ private static final Long INITIAL_DELAY = 10L;
+ private static final Long FIXED_DELAY = 100L;
+ private static final int THRESHOLD = 100;
- @PostConstruct
- public void init() {
- executorService.submit(
- () -> {
- try {
- while (true) {
- var event = queue.take();
- log.info("View post event consumed. postId: {}", event.postId());
- var command = new UpdateViewCountCommand(event.postId());
- postSystemUsecase.updateViewCount(command);
- }
- } catch (InterruptedException e) {
- log.error("consume error: {}", e.getMessage());
- throw new RuntimeException(e);
- }
- });
+ public InMemoryMessageQueue(
+ PostSystemUsecase postSystemUsecase,
+ Queue<ViewPostEvent> queue,
+ ScheduledExecutorService executorService) {
+
+ executorService.scheduleWithFixedDelay(
+ createEventConsumerRunnable(postSystemUsecase, queue),
+ INITIAL_DELAY,
+ FIXED_DELAY,
+ TimeUnit.MILLISECONDS);
+ }
+
+ private Runnable createEventConsumerRunnable(
+ PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) {
+ return () -> {
+ try {
+ List<UpdateViewCountCommand> commands = new ArrayList<>();
+ ViewPostEvent event;
+ int count = 0;
+ while ((event = queue.poll()) != null && count < THRESHOLD) {
+ log.info("View post event consumed. postId: {}", event.postId());
+ var command = new UpdateViewCountCommand(event.postId());
+ postSystemUsecase.updateViewCount(command);
+ commands.add(command);
+ count++;
+ }
+ postSystemUsecase.persistViewCountsInBatch(commands);
+ } catch (Exception e) {
+ log.error("error: {}", e.getMessage());
+ }
+ };
}
} | Java | queue가 계속 차 있는 경우에는 무한 루프에 빠지게 될 것 같네요. |
@@ -3,38 +3,52 @@
import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent;
import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase;
import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand;
-import jakarta.annotation.PostConstruct;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import lombok.RequiredArgsConstructor;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
-@RequiredArgsConstructor
public class InMemoryMessageQueue {
- private final PostSystemUsecase postSystemUsecase;
- private final BlockingQueue<ViewPostEvent> queue;
- private final ExecutorService executorService = Executors.newSingleThreadExecutor();
+ private static final Long INITIAL_DELAY = 10L;
+ private static final Long FIXED_DELAY = 100L;
+ private static final int THRESHOLD = 100;
- @PostConstruct
- public void init() {
- executorService.submit(
- () -> {
- try {
- while (true) {
- var event = queue.take();
- log.info("View post event consumed. postId: {}", event.postId());
- var command = new UpdateViewCountCommand(event.postId());
- postSystemUsecase.updateViewCount(command);
- }
- } catch (InterruptedException e) {
- log.error("consume error: {}", e.getMessage());
- throw new RuntimeException(e);
- }
- });
+ public InMemoryMessageQueue(
+ PostSystemUsecase postSystemUsecase,
+ Queue<ViewPostEvent> queue,
+ ScheduledExecutorService executorService) {
+
+ executorService.scheduleWithFixedDelay(
+ createEventConsumerRunnable(postSystemUsecase, queue),
+ INITIAL_DELAY,
+ FIXED_DELAY,
+ TimeUnit.MILLISECONDS);
+ }
+
+ private Runnable createEventConsumerRunnable(
+ PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) {
+ return () -> {
+ try {
+ List<UpdateViewCountCommand> commands = new ArrayList<>();
+ ViewPostEvent event;
+ int count = 0;
+ while ((event = queue.poll()) != null && count < THRESHOLD) {
+ log.info("View post event consumed. postId: {}", event.postId());
+ var command = new UpdateViewCountCommand(event.postId());
+ postSystemUsecase.updateViewCount(command);
+ commands.add(command);
+ count++;
+ }
+ postSystemUsecase.persistViewCountsInBatch(commands);
+ } catch (Exception e) {
+ log.error("error: {}", e.getMessage());
+ }
+ };
}
} | Java | executorService가 로직을 제대로 실행한다는 것은 어떻게 테스트 할 수 있을까요? |
@@ -3,38 +3,52 @@
import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent;
import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase;
import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand;
-import jakarta.annotation.PostConstruct;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import lombok.RequiredArgsConstructor;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
-@RequiredArgsConstructor
public class InMemoryMessageQueue {
- private final PostSystemUsecase postSystemUsecase;
- private final BlockingQueue<ViewPostEvent> queue;
- private final ExecutorService executorService = Executors.newSingleThreadExecutor();
+ private static final Long INITIAL_DELAY = 10L;
+ private static final Long FIXED_DELAY = 100L;
+ private static final int THRESHOLD = 100;
- @PostConstruct
- public void init() {
- executorService.submit(
- () -> {
- try {
- while (true) {
- var event = queue.take();
- log.info("View post event consumed. postId: {}", event.postId());
- var command = new UpdateViewCountCommand(event.postId());
- postSystemUsecase.updateViewCount(command);
- }
- } catch (InterruptedException e) {
- log.error("consume error: {}", e.getMessage());
- throw new RuntimeException(e);
- }
- });
+ public InMemoryMessageQueue(
+ PostSystemUsecase postSystemUsecase,
+ Queue<ViewPostEvent> queue,
+ ScheduledExecutorService executorService) {
+
+ executorService.scheduleWithFixedDelay(
+ createEventConsumerRunnable(postSystemUsecase, queue),
+ INITIAL_DELAY,
+ FIXED_DELAY,
+ TimeUnit.MILLISECONDS);
+ }
+
+ private Runnable createEventConsumerRunnable(
+ PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) {
+ return () -> {
+ try {
+ List<UpdateViewCountCommand> commands = new ArrayList<>();
+ ViewPostEvent event;
+ int count = 0;
+ while ((event = queue.poll()) != null && count < THRESHOLD) {
+ log.info("View post event consumed. postId: {}", event.postId());
+ var command = new UpdateViewCountCommand(event.postId());
+ postSystemUsecase.updateViewCount(command);
+ commands.add(command);
+ count++;
+ }
+ postSystemUsecase.persistViewCountsInBatch(commands);
+ } catch (Exception e) {
+ log.error("error: {}", e.getMessage());
+ }
+ };
}
} | Java | 말씀해주신대로, 비동기 프로세스 생성에 대한 부분과, 비즈니스 로직 처리에대한 부분을 분리하여 각각 테스트하도록 수정했습니다.
감사합니다 :) |
@@ -3,38 +3,52 @@
import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent;
import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase;
import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand;
-import jakarta.annotation.PostConstruct;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import lombok.RequiredArgsConstructor;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
-@RequiredArgsConstructor
public class InMemoryMessageQueue {
- private final PostSystemUsecase postSystemUsecase;
- private final BlockingQueue<ViewPostEvent> queue;
- private final ExecutorService executorService = Executors.newSingleThreadExecutor();
+ private static final Long INITIAL_DELAY = 10L;
+ private static final Long FIXED_DELAY = 100L;
+ private static final int THRESHOLD = 100;
- @PostConstruct
- public void init() {
- executorService.submit(
- () -> {
- try {
- while (true) {
- var event = queue.take();
- log.info("View post event consumed. postId: {}", event.postId());
- var command = new UpdateViewCountCommand(event.postId());
- postSystemUsecase.updateViewCount(command);
- }
- } catch (InterruptedException e) {
- log.error("consume error: {}", e.getMessage());
- throw new RuntimeException(e);
- }
- });
+ public InMemoryMessageQueue(
+ PostSystemUsecase postSystemUsecase,
+ Queue<ViewPostEvent> queue,
+ ScheduledExecutorService executorService) {
+
+ executorService.scheduleWithFixedDelay(
+ createEventConsumerRunnable(postSystemUsecase, queue),
+ INITIAL_DELAY,
+ FIXED_DELAY,
+ TimeUnit.MILLISECONDS);
+ }
+
+ private Runnable createEventConsumerRunnable(
+ PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) {
+ return () -> {
+ try {
+ List<UpdateViewCountCommand> commands = new ArrayList<>();
+ ViewPostEvent event;
+ int count = 0;
+ while ((event = queue.poll()) != null && count < THRESHOLD) {
+ log.info("View post event consumed. postId: {}", event.postId());
+ var command = new UpdateViewCountCommand(event.postId());
+ postSystemUsecase.updateViewCount(command);
+ commands.add(command);
+ count++;
+ }
+ postSystemUsecase.persistViewCountsInBatch(commands);
+ } catch (Exception e) {
+ log.error("error: {}", e.getMessage());
+ }
+ };
}
} | Java | 확인해주셔서 감사합니다.
Threshold를 설정하도록 변경했습니다 :) |
@@ -1 +1,107 @@
-# java-convenience-store-precourse
+# 편의점
+
+
+
+## 📚목차
+
+- [🎥 시연 영상](#-시연-영상)
+- [🚀 편의점 프로젝트 개요](#-편의점-프로젝트-개요)
+- [📌 편의점 규칙 및 설명](#-편의점-규칙-및-설명)
+ - [재고 관리](#재고-관리)
+ - [프로모션 할인](#프로모션-할인)
+ - [멤버십 할인](#멤버십-할인)
+ - [영수증 출력](#영수증-출력)
+- [💎 기능 목록](#-기능-목록)
+
+## 🎥 시연 영상
+
+
+
+## 🚀 편의점 프로젝트 개요
+
+이 프로젝트는 구매자의 할인 혜택과 재고 상황을 고려하여 최종 결제 금액을 계산하고 안내하는 결제 시스템입니다.
+
+- 사용자가 입력한 상품의 가격과 수량을 기반으로 최종 결제 금액을 계산합니다.
+- 총구매액은 상품별 가격과 수량을 곱하여 계산하며, 프로모션 및 멤버십 할인 정책을 반영하여 최종 결제 금액을 산출합니다.
+- 구매 내역과 산출한 금액 정보를 영수증으로 출력합니다.
+- 영수증 출력 후 추가 구매를 진행할지 또는 종료할지를 선택할 수 있습니다.
+
+## 📌 편의점 규칙 및 설명
+
+**재고 관리**
+
+- 고객이 상품을 구매할 때마다, 결제된 수량만큼 해당 상품의 재고에서 차감됩니다.
+- 재고를 차감함으로써 시스템은 최신 재고 상태를 유지하며, 다음 고객이 구매할 때 정확한 재고 정보가 제공됩니다.
+- 재고는 처음 환영 인사 때 제공됩니다.
+ - 상품명, 가격, 프로모션 이름, 재고가 안내됩니다.
+ - 만약 재고가 0개라면 `재고 없음`이 출력됩니다.
+
+<img width="264" alt="image" src="https://github.com/user-attachments/assets/94be4ffa-275d-4b1e-9a45-8e7dcd8347be">
+
+
+**프로모션 할인**
+
+- 오늘 날짜가 프로모션 기간 내에 포함된 경우에만 할인을 적용됩니다.
+- 프로모션은 N개 구매 시 1개 무료 증정(Buy N Get 1 Free)의 형태로 진행됩니다.
+- 1+1 또는 2+1 프로모션이 각각 지정된 상품에 적용되며, 동일 상품에 여러 프로모션이 적용되지 않습니다.
+- 프로모션 혜택은 프로모션 재고 내에서만 적용할 수 있다.
+- 프로모션 기간 중이라면 프로모션 재고를 우선적으로 차감하며, 프로모션 재고가 부족할 경우에는 일반 재고가 사용됩니다.
+ - 프로모션 기간 중이 아니라도 프로모션 재고가 우선적으로 차감됩니다. 이때 결제는 프로모션 혜택없이 진행됩니다.
+- 프로모션 적용이 가능한 상품에 대해 고객이 해당 수량보다 적게 가져온 경우, 필요한 수량을 추가로 가져오면 혜택을 받을 수 있음이 안내됩니다.
+ - 예시(2+1 상품)
+ - 고객이 2개만 가져왔을 시 증정 받을 수 있는 상품을 안내한다.
+ - <안내 메시지> 현재 {상품명}은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)
+ - Y: 증정 받을 수 있는 상품을 추가됩니다.
+ - N: 증정 받을 수 있는 상품을 추가되지 않습니다.
+ - 고객이 1개만 가져왔을 시 프로모션 혜택은 적용되지 않고 따로 안내가 되지 않는다.
+- 프로모션 재고가 부족하여 일부 수량을 프로모션 혜택 없이 결제해야 하는 경우, 일부 수량에 대해 정가로 결제해야하고 이를 안내받을 수 있습니다.
+ - <안내 메시지> 현재 {상품명} {수량}개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)
+ - Y: 일부 수량에 대해 정가로 결제한다.
+ - N: 정가로 결제해야하는 수량만큼 제외한 후 결제를 진행한다.
+
+**멤버십 할인**
+
+- 멤버십 회원은 프로모션 미적용 금액의 30%를 할인이 적용됩니다.
+- 프로모션 적용 후 남은 금액에 대해 멤버십 할인이 적용됩니다.
+- 멤버십 할인의 최대 한도는 8,000원입니다.
+- 최종 결제전 안내 메시지가 전달됩니다.
+ - <안내 메시지> 멤버십 할인을 받으시겠습니까? (Y/N)
+ - Y: 멤버십 할인이 적용됩니다.
+ - N: 멤버십 할인이 적용되지 않습니다.
+
+**영수증 출력**
+
+- 영수증은 고객의 구매 내역과 할인을 요약하여 출력됩니다.
+- 영수증 항목은 아래와 같습니다.
+ - 구매 상품 내역: 구매한 상품명, 수량, 가격
+ - 증정 상품 내역: 프로모션에 따라 무료로 제공된 증정 상품의 목록
+ - 금액 정보
+ - 총구매액: 구매한 상품의 총 수량과 총 금액
+ - 행사할인: 프로모션에 의해 할인된 금액
+ - 멤버십할인: 멤버십에 의해 추가로 할인된 금액
+ - 내실돈: 최종 결제 금액
+- 영수증은 구성 요소를 보기 좋게 정렬됩니다.
+
+<img width="320" alt="image" src="https://github.com/user-attachments/assets/a82b976c-2673-426e-bab3-16e45a4c0ab8">
+
+## 💎 기능 목록
+
+- [x] (1) 재고 출력
+ - 상품 재고 및 프로모션 파일 읽기
+ - [예외] 상품 재고 파일 경로가 올바르지 않을 때
+ - [예외] 상품 재고 파일이 올바른 형식으로 작성되지 않았을 때
+- [x] (2) 구매할 상품명과 수량 입력 받기
+- [x] (3) 구매할 상품명과 수량 유효성 검사
+ - 예외상황이라면 에러메시지 출력후 다시 입력 받기
+ - 프로모션 적용가능한 상품에 대해 고객이 해당 수량만큼 가져오지 않았을 경우 안내 메시지 출력후 추가여부 입력
+ - 프로모션 재고가 부족하다면 일부 수량에 대해 정가로 결제할지 여부 입력
+ - [예외] 구매할 상품과 수량 형식이 올바르지 않은 경우
+ - [예외] 존재하지 않는 상품을 입력한 경우
+ - [예외] 구매 수량이 재고 수량을 초과한 경우
+ - [예외] 기타 잘못된 입력의 경우
+- [x] (4) 멤버십 할인 적용 여부 입력 받기
+ - [예외] Y/N이 아닌 잘못된 입력의 경우
+- [x] (5) 구매 상품 내역, 증정 상품 내역, 금액 정보 출력
+- [x] (6) 추가 구매 여부 입력 받기
+ - yes 이면 추가 구매 진행 no이면 종료
+ - [예외] Y/N이 아닌 잘못된 입력의 경우 | Unknown | 공들이신 게 보이는 리드미군요 👍 멋집니다 |
@@ -0,0 +1,14 @@
+package store.model;
+
+public final class Membership {
+ private static final int DISCOUNT_PERCENTAGE = 30;
+ private static final int MAX_DISCOUNT = 8_000;
+
+ private Membership() {
+ }
+
+ public static long calculateDiscount(long amount) {
+ long discountAmount = amount * DISCOUNT_PERCENTAGE / 100;
+ return Math.min(discountAmount, MAX_DISCOUNT);
+ }
+} | Java | 건당 최대 할인량(8000)을 고정하고 사용하신 부분이 저랑 다르네요!
저는 어플리케이션의 한 사이클 (시작~종료) 의 최대 멤버십 할인량을 8000원이라고 보았습니다 😄
만약 해당 방식으로 할인율 및 최대 할인액을 상수처리 해서 사용하실 것이라면, Answer 클래스처럼 enum으로 관리하면 어떨까요? |
@@ -0,0 +1,59 @@
+package store.model.item;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import store.error.FileParsingException;
+import store.utils.MarkdownReader;
+
+public class ItemLoader {
+ private static final String NULL = "null";
+
+ private ItemLoader() {
+ }
+
+ public static ItemLoader getInstance() {
+ return new ItemLoader();
+ }
+
+ public List<Item> loadItems(String filePath) {
+ try {
+ List<String[]> itemData = MarkdownReader.readFile(filePath);
+ return parseItems(itemData);
+ } catch (IOException e) {
+ throw new FileParsingException(e);
+ }
+ }
+
+ private List<Item> parseItems(List<String[]> itemData) {
+ List<Item> items = new ArrayList<>();
+ for (int i = 0; i < itemData.size(); i++) {
+ Item item = parseItem(itemData.get(i));
+ items.add(item);
+ if (shouldAddNonPromotionItem(item, i, itemData)) {
+ items.add(new Item(item.getName(), item.getPrice(), 0, null));
+ }
+ }
+ return items;
+ }
+
+ private Item parseItem(String[] itemData) {
+ String name = itemData[0];
+ int price = Integer.parseInt(itemData[1]);
+ int quantity = Integer.parseInt(itemData[2]);
+ String promotionName = itemData[3];
+ if (NULL.equals(promotionName)) {
+ promotionName = null;
+ }
+ return new Item(name, price, quantity, promotionName);
+ }
+
+ private boolean shouldAddNonPromotionItem(Item currentItem, int currentIndex, List<String[]> itemData) {
+ if (currentItem.getPromotionName() == null) {
+ return false;
+ }
+ boolean isLastItem = currentIndex == itemData.size() - 1;
+ boolean isDifferentNextItem = !isLastItem && !itemData.get(currentIndex + 1)[0].equals(currentItem.getName());
+ return isLastItem || isDifferentNextItem;
+ }
+} | Java | 이 부분도 신경 쓰셨군요 😄 멋집니다 |
@@ -0,0 +1,106 @@
+package store.model.item;
+
+import java.util.List;
+import store.model.promotion.Promotion;
+import store.model.promotion.PromotionManager;
+
+public class ItemRepository {
+ public static final String NO_ITEM = "존재하지 않는 상품입니다. 다시 입력해 주세요.";
+ private final List<Item> items;
+ private final PromotionManager promotionManager;
+
+ public ItemRepository(List<Item> items, PromotionManager promotionManager) {
+ this.items = items;
+ this.promotionManager = promotionManager;
+ }
+
+ public List<Item> getItems() {
+ return items;
+ }
+
+ public Item findItemWithoutPromotionByName(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName))
+ .filter(item -> item.getPromotionName() == null)
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NO_ITEM));
+ }
+
+ public Item findPromotionItemByName(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName))
+ .filter(item -> item.getPromotionName() != null)
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NO_ITEM));
+ }
+
+ public int findPromotionItemQuantityByName(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName) && item.getPromotionName() != null)
+ .findFirst()
+ .map(Item::getQuantity)
+ .orElse(0);
+ }
+
+ public Item findOnlyActivePromotionItem(String itemName) {
+ return items.stream()
+ .filter(item -> {
+ Promotion promotion = promotionManager.getPromotion(item.getPromotionName());
+ return isEligibleForPromotion(itemName, item, promotion);
+ })
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NO_ITEM));
+ }
+
+ private boolean isEligibleForPromotion(String itemName, Item item, Promotion promotion) {
+ return item.getName().equals(itemName) && promotion != null && promotion.isPromotionActive();
+ }
+
+ public int findMinPromotionQuantity(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName))
+ .filter(item -> item.getPromotionName() != null)
+ .mapToInt(item -> promotionManager.getPromotion(item.getPromotionName()).getGet()
+ + promotionManager.getPromotion(item.getPromotionName()).getBuy())
+ .sum();
+ }
+
+ public int findPromotionQuantityForItem(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName) && promotionManager.isPromotionActive(
+ item.getPromotionName()))
+ .mapToInt(Item::getQuantity)
+ .sum();
+ }
+
+ public int findTotalQuantityForItem(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName))
+ .mapToInt(Item::getQuantity)
+ .sum();
+ }
+
+ public boolean hasPromotion(String itemName) {
+ return items.stream()
+ .anyMatch(item -> item.getName().equals(itemName) && item.getPromotionName() != null);
+ }
+
+ public boolean isPromotionInactive(String itemName) {
+ return items.stream()
+ .filter(item -> item.getName().equals(itemName) && item.getPromotionName() != null)
+ .anyMatch(item -> !promotionManager.isPromotionActive(item.getPromotionName()));
+ }
+
+
+ public void decreaseQuantity(Item item, int quantity) {
+ item.decreaseQuantity(quantity);
+ }
+
+ public void validateItemName(String itemName) {
+ boolean hasItemName = items.stream().anyMatch(item -> itemName.equals(item.getName()));
+ if (!hasItemName) {
+ throw new IllegalArgumentException(NO_ITEM);
+ }
+ }
+
+} | Java | 레포지토리 클래스를 이렇게 사용하면 좀 더 유연하게 도메인을 불러 올 수 있겠군요 ㅎㅎ 👍 |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | while-try-catch가 반복되어서 쓰이고 있기 때문에 템플릿화해서 사용하면 전체 코드 길이를 줄일 수 있을것 같아요! |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 저는 재귀로 가독성을 크게 개선할 수 있는 상황이 아니면, 스택오버플로우 때문에 잘 사용하지 않는데요~
그래서 철원님이 요 메서드를 재귀로 구현하신 이유가 궁금하네요 ㅎㅎ |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 이미 아시고 계시겠지만, 상품 구매 관련 일부 비즈니스 로직이 컨트롤러에 혼재되어 있네요
책임을 분리시키는 리팩토링을 하면 좋을것 같아요 ㅎㅎ |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | OrderProcessor가 Inventory를 주입 받아야 하는 상황이라 생성자에서 주입을 시켜주고 있는데요.
OrderProcessor, Inventory 이 두 객체를 감싸는 A 클래스 하나를 둬서 최종 적으로 A 클래스를 주입하는게 더욱 깔끔할 것 같은데, 철원님 의견은 어떠신가요 ?? |
@@ -0,0 +1,34 @@
+package store.error;
+
+import store.model.item.Item;
+import store.model.order.OrderItem;
+
+public class PromotionConfirmationForFreeException extends RuntimeException {
+ private Item item;
+ private OrderItem orderItem;
+ private int shortfall;
+
+ public PromotionConfirmationForFreeException(Item item, OrderItem orderItem, int shortfall) {
+ super();
+ this.item = item;
+ this.orderItem = orderItem;
+ this.shortfall = shortfall;
+ }
+
+
+ public Item getItem() {
+ return item;
+ }
+
+ public OrderItem getOrderItem() {
+ return orderItem;
+ }
+
+ public int getOrderQuantity() {
+ return orderItem.getQuantity();
+ }
+
+ public int getShortfall() {
+ return shortfall;
+ }
+} | Java | 커스텀 예외안에 도메인 정보들이 있네요~ 아마 예외 발생 시 사용자에게 도메인 정보를 보여줘야해서 이런식으로 구현하신것 같아요~
혹시 이외에 다른 의도가 있으신지 궁금하네요 ! |
@@ -0,0 +1,23 @@
+package store.model;
+
+import java.util.function.Function;
+
+public enum SalesAmountType {
+ MEMBERSHIP("멤버십할인", Membership::calculateDiscount);
+
+ private final String viewName;
+ private final Function<Long, Long> expression;
+
+ SalesAmountType(String viewName, Function<Long, Long> expression) {
+ this.viewName = viewName;
+ this.expression = expression;
+ }
+
+ public long calculate(long amount) {
+ return expression.apply(amount);
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+} | Java | 멤버십 할인 관련 클래스를 enum으로 구현하신 의도가 궁금합니다 ! |
@@ -0,0 +1,158 @@
+package store.model.item;
+
+import java.io.IOException;
+import java.util.List;
+import store.error.FileParsingException;
+import store.error.PromotionConfirmationForFreeException;
+import store.model.Answer;
+import store.model.order.OrderItem;
+import store.model.promotion.Promotion;
+import store.model.promotion.PromotionCalculation;
+import store.model.promotion.PromotionManager;
+
+public class Inventory {
+ private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md";
+
+ private final ItemRepository itemRepository;
+ private final PromotionManager promotionManager;
+
+ public Inventory() {
+ this(PRODUCTS_FILE_PATH);
+ }
+
+ public Inventory(String productsFilePath) {
+ try {
+ this.promotionManager = new PromotionManager();
+ promotionManager.loadPromotions();
+ List<Item> items = ItemLoader.getInstance().loadItems(productsFilePath);
+ this.itemRepository = new ItemRepository(items, promotionManager);
+ } catch (IOException e) {
+ throw new FileParsingException(e);
+ }
+ }
+
+ public void validate(String itemName) {
+ itemRepository.validateItemName(itemName);
+ }
+
+ public void setPrice(OrderItem orderItem) {
+ for (Item item : itemRepository.getItems()) {
+ if (item.getName().equals(orderItem.getName())) {
+ orderItem.setPrice(item.getPrice());
+ }
+ }
+ }
+
+ public void consumePromotionItemWithoutPromotion(OrderItem orderItem) {
+ Item promotionItem = itemRepository.findPromotionItemByName(orderItem.getName());
+ int quantity = promotionItem.getQuantity();
+
+ itemRepository.decreaseQuantity(promotionItem, quantity);
+ orderItem.increaseTotalOrderQuantity(quantity);
+ orderItem.increaseNonPromotionQuantity(quantity);
+ }
+
+ public void consumePromotionItemWithoutPromotion(int orderQuantity, OrderItem orderItem) {
+ Item promotionItem = itemRepository.findPromotionItemByName(orderItem.getName());
+
+ itemRepository.decreaseQuantity(promotionItem, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increaseNonPromotionQuantity(orderQuantity);
+ }
+
+ public void consumePromotionItem(int orderQuantity, OrderItem orderItem) {
+ Item itemInInventory = itemRepository.findOnlyActivePromotionItem(orderItem.getName());
+ Promotion promotion = promotionManager.getPromotion(itemInInventory.getPromotionName());
+ PromotionCalculation promotionData = PromotionCalculation.of(promotion, orderQuantity);
+ processPromotionItem(orderQuantity, orderItem, promotionData, itemInInventory);
+ }
+
+ private void processPromotionItem(int orderQuantity, OrderItem orderItem, PromotionCalculation promotionData,
+ Item itemInInventory) {
+ if (promotionData.hasExactPromotionQuantity()) {
+ processPromotion(itemInInventory, orderItem, orderQuantity, promotionData.getPromotionAppliedQuantity());
+ return;
+ }
+ if (promotionData.hasPartialPromotion()) {
+ processNonPromotion(itemInInventory, orderItem, orderQuantity);
+ return;
+ }
+ throw new PromotionConfirmationForFreeException(itemInInventory, orderItem, promotionData.getShortfall());
+ }
+
+ private void processPromotion(Item item, OrderItem orderItem, int orderQuantity, int promotionQuantity) {
+ itemRepository.decreaseQuantity(item, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increasePromotionAppliedQuantity(promotionQuantity);
+ }
+
+ private void processNonPromotion(Item item, OrderItem orderItem, int orderQuantity) {
+ itemRepository.decreaseQuantity(item, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increaseNonPromotionQuantity(orderQuantity);
+ }
+
+ public void consumeRegularItem(String itemName, int quantity, OrderItem orderItem) {
+ Item regularItem = itemRepository.findItemWithoutPromotionByName(itemName);
+ regularItem.decreaseQuantity(quantity);
+ orderItem.increaseTotalOrderQuantity(quantity);
+ orderItem.increaseNonPromotionQuantity(quantity);
+ }
+
+ public void parseUserChoiceWithoutPromotion(String userChoice, OrderItem orderItem, int remainingPromotionQuantity,
+ int remainingQuantity) {
+ if (Answer.YES.isEqual(userChoice)) {
+ consumePromotionItemWithoutPromotion(remainingPromotionQuantity, orderItem);
+ consumeRegularItem(orderItem.getName(), remainingQuantity - remainingPromotionQuantity, orderItem);
+ }
+ }
+
+ public void parseUserChoiceForFree(String userChoice, Item itemInInventory, OrderItem orderItem, int shortfall) {
+ if (Answer.YES.isEqual(userChoice)) {
+ itemRepository.decreaseQuantity(itemInInventory, orderItem.getQuantity() + shortfall);
+ orderItem.increaseTotalOrderQuantity(orderItem.getQuantity() + shortfall);
+ orderItem.increasePromotionAppliedQuantity(shortfall);
+ return;
+ }
+ itemRepository.decreaseQuantity(itemInInventory, orderItem.getQuantity());
+ orderItem.increaseTotalOrderQuantity(orderItem.getQuantity());
+ }
+
+ public int getApplicablePromotionQuantity(String itemName) {
+ int promotionQuantityForItem = getPromotionQuantityForItem(itemName);
+ int minPromotionQuantity = getMinPromotionQuantity(itemName);
+ if (minPromotionQuantity == 0) {
+ throw new IllegalStateException("일어나면 안되는 에러가 발생했습니다. : Inventory");
+ }
+ int remainder = promotionQuantityForItem % minPromotionQuantity;
+ return promotionQuantityForItem - remainder;
+ }
+
+ public int getMinPromotionQuantity(String itemName) {
+ return itemRepository.findMinPromotionQuantity(itemName);
+ }
+
+ public int getTotalQuantityForItem(String itemName) {
+ return itemRepository.findTotalQuantityForItem(itemName);
+ }
+
+ public int getPromotionQuantityForItem(String itemName) {
+ return itemRepository.findPromotionQuantityForItem(itemName);
+ }
+
+ public int getPromotionItemQuantityByName(String itemName) {
+ return itemRepository.findPromotionItemQuantityByName(itemName);
+ }
+
+ public boolean hasPromotion(String itemName) {
+ return itemRepository.hasPromotion(itemName);
+ }
+
+ public boolean isPromotionInactive(String itemName) {
+ return itemRepository.isPromotionInactive(itemName);
+ }
+
+ public List<Item> getItems() {
+ return itemRepository.getItems();
+ }
+} | Java | 그쵸! 에러는 일어나면 안됩니다 ! ㅋㅋ |
@@ -0,0 +1,158 @@
+package store.model.item;
+
+import java.io.IOException;
+import java.util.List;
+import store.error.FileParsingException;
+import store.error.PromotionConfirmationForFreeException;
+import store.model.Answer;
+import store.model.order.OrderItem;
+import store.model.promotion.Promotion;
+import store.model.promotion.PromotionCalculation;
+import store.model.promotion.PromotionManager;
+
+public class Inventory {
+ private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md";
+
+ private final ItemRepository itemRepository;
+ private final PromotionManager promotionManager;
+
+ public Inventory() {
+ this(PRODUCTS_FILE_PATH);
+ }
+
+ public Inventory(String productsFilePath) {
+ try {
+ this.promotionManager = new PromotionManager();
+ promotionManager.loadPromotions();
+ List<Item> items = ItemLoader.getInstance().loadItems(productsFilePath);
+ this.itemRepository = new ItemRepository(items, promotionManager);
+ } catch (IOException e) {
+ throw new FileParsingException(e);
+ }
+ }
+
+ public void validate(String itemName) {
+ itemRepository.validateItemName(itemName);
+ }
+
+ public void setPrice(OrderItem orderItem) {
+ for (Item item : itemRepository.getItems()) {
+ if (item.getName().equals(orderItem.getName())) {
+ orderItem.setPrice(item.getPrice());
+ }
+ }
+ }
+
+ public void consumePromotionItemWithoutPromotion(OrderItem orderItem) {
+ Item promotionItem = itemRepository.findPromotionItemByName(orderItem.getName());
+ int quantity = promotionItem.getQuantity();
+
+ itemRepository.decreaseQuantity(promotionItem, quantity);
+ orderItem.increaseTotalOrderQuantity(quantity);
+ orderItem.increaseNonPromotionQuantity(quantity);
+ }
+
+ public void consumePromotionItemWithoutPromotion(int orderQuantity, OrderItem orderItem) {
+ Item promotionItem = itemRepository.findPromotionItemByName(orderItem.getName());
+
+ itemRepository.decreaseQuantity(promotionItem, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increaseNonPromotionQuantity(orderQuantity);
+ }
+
+ public void consumePromotionItem(int orderQuantity, OrderItem orderItem) {
+ Item itemInInventory = itemRepository.findOnlyActivePromotionItem(orderItem.getName());
+ Promotion promotion = promotionManager.getPromotion(itemInInventory.getPromotionName());
+ PromotionCalculation promotionData = PromotionCalculation.of(promotion, orderQuantity);
+ processPromotionItem(orderQuantity, orderItem, promotionData, itemInInventory);
+ }
+
+ private void processPromotionItem(int orderQuantity, OrderItem orderItem, PromotionCalculation promotionData,
+ Item itemInInventory) {
+ if (promotionData.hasExactPromotionQuantity()) {
+ processPromotion(itemInInventory, orderItem, orderQuantity, promotionData.getPromotionAppliedQuantity());
+ return;
+ }
+ if (promotionData.hasPartialPromotion()) {
+ processNonPromotion(itemInInventory, orderItem, orderQuantity);
+ return;
+ }
+ throw new PromotionConfirmationForFreeException(itemInInventory, orderItem, promotionData.getShortfall());
+ }
+
+ private void processPromotion(Item item, OrderItem orderItem, int orderQuantity, int promotionQuantity) {
+ itemRepository.decreaseQuantity(item, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increasePromotionAppliedQuantity(promotionQuantity);
+ }
+
+ private void processNonPromotion(Item item, OrderItem orderItem, int orderQuantity) {
+ itemRepository.decreaseQuantity(item, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increaseNonPromotionQuantity(orderQuantity);
+ }
+
+ public void consumeRegularItem(String itemName, int quantity, OrderItem orderItem) {
+ Item regularItem = itemRepository.findItemWithoutPromotionByName(itemName);
+ regularItem.decreaseQuantity(quantity);
+ orderItem.increaseTotalOrderQuantity(quantity);
+ orderItem.increaseNonPromotionQuantity(quantity);
+ }
+
+ public void parseUserChoiceWithoutPromotion(String userChoice, OrderItem orderItem, int remainingPromotionQuantity,
+ int remainingQuantity) {
+ if (Answer.YES.isEqual(userChoice)) {
+ consumePromotionItemWithoutPromotion(remainingPromotionQuantity, orderItem);
+ consumeRegularItem(orderItem.getName(), remainingQuantity - remainingPromotionQuantity, orderItem);
+ }
+ }
+
+ public void parseUserChoiceForFree(String userChoice, Item itemInInventory, OrderItem orderItem, int shortfall) {
+ if (Answer.YES.isEqual(userChoice)) {
+ itemRepository.decreaseQuantity(itemInInventory, orderItem.getQuantity() + shortfall);
+ orderItem.increaseTotalOrderQuantity(orderItem.getQuantity() + shortfall);
+ orderItem.increasePromotionAppliedQuantity(shortfall);
+ return;
+ }
+ itemRepository.decreaseQuantity(itemInInventory, orderItem.getQuantity());
+ orderItem.increaseTotalOrderQuantity(orderItem.getQuantity());
+ }
+
+ public int getApplicablePromotionQuantity(String itemName) {
+ int promotionQuantityForItem = getPromotionQuantityForItem(itemName);
+ int minPromotionQuantity = getMinPromotionQuantity(itemName);
+ if (minPromotionQuantity == 0) {
+ throw new IllegalStateException("일어나면 안되는 에러가 발생했습니다. : Inventory");
+ }
+ int remainder = promotionQuantityForItem % minPromotionQuantity;
+ return promotionQuantityForItem - remainder;
+ }
+
+ public int getMinPromotionQuantity(String itemName) {
+ return itemRepository.findMinPromotionQuantity(itemName);
+ }
+
+ public int getTotalQuantityForItem(String itemName) {
+ return itemRepository.findTotalQuantityForItem(itemName);
+ }
+
+ public int getPromotionQuantityForItem(String itemName) {
+ return itemRepository.findPromotionQuantityForItem(itemName);
+ }
+
+ public int getPromotionItemQuantityByName(String itemName) {
+ return itemRepository.findPromotionItemQuantityByName(itemName);
+ }
+
+ public boolean hasPromotion(String itemName) {
+ return itemRepository.hasPromotion(itemName);
+ }
+
+ public boolean isPromotionInactive(String itemName) {
+ return itemRepository.isPromotionInactive(itemName);
+ }
+
+ public List<Item> getItems() {
+ return itemRepository.getItems();
+ }
+} | Java | 해당 클래스는 크게 3가지 책임을 갖고 있네요
1. 마크 다운 파일을 읽어와서 ItemRepository 생성
2. 재고 관련 비즈니스 로직
3. 프로모셔 관련 비즈니스 로직
철원님이라면 이 3가지 모두 적절하게 분리하실 수 있을것 같아요 ㅎㅎ
리팩토링때 한번 고려해보시죠! |
@@ -0,0 +1,81 @@
+package store.model.item;
+
+import store.error.FileContentException;
+
+public class Item {
+ private static final String KOREAN_REGEX = "^[가-힣]+$";
+ private static final int MAX_PRICE = 100_000_000;
+ public static final int MAX_QUANTITY = 999;
+
+ private final String name;
+ private final int price;
+ private final String promotionName;
+ private int quantity;
+
+ public Item(String name, int price, int quantity, String promotionName) {
+ validate(name, price, quantity);
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotionName = promotionName;
+ }
+
+ private void validate(String name, int price, int quantity) {
+ validateName(name);
+ validatePrice(price);
+ validateQuantity(quantity);
+ }
+
+ private void validateName(String name) {
+ if (name == null || name.trim().isEmpty()) {
+ throw new FileContentException("[ERROR] 상품 이름이 잘못되었습니다.");
+ }
+ if (!name.matches(KOREAN_REGEX)) {
+ throw new FileContentException("[ERROR] 상품 이름은 한글만 입력할 수 있습니다.");
+ }
+ }
+
+ private void validatePrice(int price) {
+ if (price < 0) {
+ throw new FileContentException("[ERROR] 가격은 0원 이상이어야 합니다.");
+ }
+ if (price > MAX_PRICE) {
+ throw new FileContentException("[ERROR] 가격은 최대 1억원 이하까지로만 설정할 수 있습니다.");
+ }
+ }
+
+ private void validateQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new FileContentException("[ERROR] 수량은 0개 이상으로만 설정할 수 있습니다.");
+ }
+ if (quantity > MAX_QUANTITY) {
+ throw new FileContentException("[ERROR] 수량은 최대 999개까지 설정할 수 있습니다.");
+ }
+ }
+
+ void decreaseQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new IllegalArgumentException("[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.");
+ }
+ if (this.quantity == 0) {
+ throw new IllegalArgumentException("[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.");
+ }
+ this.quantity -= quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPromotionName() {
+ return promotionName;
+ }
+} | Java | 혹시 이 친구는 외부에서도 쓰이는 건가요?? |
@@ -0,0 +1,81 @@
+package store.model.item;
+
+import store.error.FileContentException;
+
+public class Item {
+ private static final String KOREAN_REGEX = "^[가-힣]+$";
+ private static final int MAX_PRICE = 100_000_000;
+ public static final int MAX_QUANTITY = 999;
+
+ private final String name;
+ private final int price;
+ private final String promotionName;
+ private int quantity;
+
+ public Item(String name, int price, int quantity, String promotionName) {
+ validate(name, price, quantity);
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotionName = promotionName;
+ }
+
+ private void validate(String name, int price, int quantity) {
+ validateName(name);
+ validatePrice(price);
+ validateQuantity(quantity);
+ }
+
+ private void validateName(String name) {
+ if (name == null || name.trim().isEmpty()) {
+ throw new FileContentException("[ERROR] 상품 이름이 잘못되었습니다.");
+ }
+ if (!name.matches(KOREAN_REGEX)) {
+ throw new FileContentException("[ERROR] 상품 이름은 한글만 입력할 수 있습니다.");
+ }
+ }
+
+ private void validatePrice(int price) {
+ if (price < 0) {
+ throw new FileContentException("[ERROR] 가격은 0원 이상이어야 합니다.");
+ }
+ if (price > MAX_PRICE) {
+ throw new FileContentException("[ERROR] 가격은 최대 1억원 이하까지로만 설정할 수 있습니다.");
+ }
+ }
+
+ private void validateQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new FileContentException("[ERROR] 수량은 0개 이상으로만 설정할 수 있습니다.");
+ }
+ if (quantity > MAX_QUANTITY) {
+ throw new FileContentException("[ERROR] 수량은 최대 999개까지 설정할 수 있습니다.");
+ }
+ }
+
+ void decreaseQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new IllegalArgumentException("[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.");
+ }
+ if (this.quantity == 0) {
+ throw new IllegalArgumentException("[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.");
+ }
+ this.quantity -= quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPromotionName() {
+ return promotionName;
+ }
+} | Java | 가격과 수량 제한을 두신 이유가 있으실것 같아요~ 그리고 수치는 어떤 기준으로 정하신건가요 ?? |
@@ -0,0 +1,76 @@
+package store.model.order;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class OrderItem {
+ private static final String DELIMITER = "-";
+ private static final String REGEX = "[\\[\\]]";
+ private static final Pattern EACH_PATTERN = Pattern.compile("\\[([가-힣]+)-(\\d+)]");
+ private static final String EMPTY = "";
+
+ private final String name;
+ private final int quantity;
+ private int promotionAppliedQuantity = 0;
+ private int totalOrderQuantity = 0;
+ private int nonPromotionQuantity = 0;
+ private int price = 0;
+
+ public OrderItem(String item) {
+ validate(item);
+ String[] itemData = parse(item);
+ this.name = itemData[0];
+ this.quantity = Integer.parseInt(itemData[1]);
+ }
+
+ private void validate(String item) {
+ Matcher matcher = EACH_PATTERN.matcher(item);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.");
+ }
+ }
+
+ private String[] parse(String item) {
+ return item.replaceAll(REGEX, EMPTY).split(DELIMITER);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public void increasePromotionAppliedQuantity(int quantity) {
+ promotionAppliedQuantity += quantity;
+ }
+
+ public void increaseNonPromotionQuantity(int quantity) {
+ nonPromotionQuantity += quantity;
+ }
+
+ public int getNonPromotionQuantity() {
+ return nonPromotionQuantity;
+ }
+
+ public int getPromotionAppliedQuantity() {
+ return promotionAppliedQuantity;
+ }
+
+ public void increaseTotalOrderQuantity(int quantity) {
+ totalOrderQuantity += quantity;
+ }
+
+ public int getTotalOrderQuantity() {
+ return totalOrderQuantity;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return this.price;
+ }
+} | Java | 저는 필드가 많아지면 서로 관련이 있는 요소들은 VO로 감싸거든요~
이에 대해서 철원님 생각은 어떠신가요 ?? |
@@ -0,0 +1,23 @@
+package store.utils;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.List;
+
+public final class MarkdownReader {
+ private static final String DELIMITER = ",";
+ private static final int LINES_TO_SKIP = 1;
+
+ private MarkdownReader() {
+ }
+
+ public static List<String[]> readFile(String filePath) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ return br.lines()
+ .skip(LINES_TO_SKIP)
+ .map(line -> line.split(DELIMITER))
+ .toList();
+ }
+ }
+} | Java | 리더를 따로 분리하신거 좋네요 ㅎㅎ |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 저도 수달님꺼 보고 오 이렇게하면 더 좋겠다 싶었어요 ㅎㅎ
연습하겠습니다.! |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 저도 스택오버플로우 때문에 전부 while이지만 딱 이부분만 재귀로 했습니다.
왜냐하면 이 마지막 부분은 빠르게 많이 반복할 수 없습니다.
일단 이 로직은 마지막에 YES를 했을 때만 재귀로 동작하고 나머지는 반복문입니다. 또한 편의점 상품 물량을 제한해두었기 때문에 무한으로 스택이 쌓이지 않습니다.
그렇기 때문에 이 부분만큼은 따로 반복으로 빼기보다는 간단하게 재귀로 나타내면 좋겠다 싶었습니다. |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 아시겠지만 평소처럼 스파게티 코드로 구현한뒤 아예 전면 개조해서 깔끔하게 할 시간이 없어서 스파게티 코드 완성하자마자 부분적으로 리팩터링에 들어가서 원하는 스타일로 설계와 구현을 하지 못했습니다. ㅜ |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import store.dto.ItemDto;
+import store.dto.OrderDto;
+import store.dto.OrderItemDto;
+import store.error.PromotionConfirmationForFreeException;
+import store.error.PurchaseConfirmationWithoutPromotionException;
+import store.model.Answer;
+import store.model.item.Inventory;
+import store.model.item.Item;
+import store.model.order.Order;
+import store.model.order.OrderCalculator;
+import store.model.order.OrderItem;
+import store.model.order.OrderProcessor;
+import store.model.order.PaymentSummary;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final Inventory inventory;
+ private final OrderProcessor orderProcessor;
+
+ public StoreController(Inventory inventory) {
+ this.inventory = inventory;
+ this.orderProcessor = new OrderProcessor(inventory);
+ }
+
+ public void run() {
+ try {
+ printItems(inventory.getItems());
+ Order order = getOrder();
+ printReceipt(order, isMembershipDiscountAccepted());
+ if (isAdditionalPurchaseConfirmed()) {
+ run();
+ }
+ } catch (NoSuchElementException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+
+ private void printItems(List<Item> items) {
+ List<ItemDto> itemsDTO = items.stream()
+ .map(ItemDto::new)
+ .toList();
+ OutputView.printItems(itemsDTO);
+ }
+
+ private Order getOrder() {
+ while (true) {
+ try {
+ String userOrder = InputView.readItem();
+ Order order = new Order(userOrder);
+ fulfillOrder(order);
+ return order;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private void fulfillOrder(Order order) {
+ for (OrderItem orderItem : order.getOrderItems()) {
+ try {
+ orderProcessor.processOrder(orderItem);
+ } catch (PromotionConfirmationForFreeException e) {
+ processPromotionConfirmationForFree(e);
+ } catch (PurchaseConfirmationWithoutPromotionException e) {
+ processPurchaseConfirmationWithoutPromotion(e);
+ }
+ orderProcessor.setPrice(orderItem);
+ }
+ }
+
+ private void processPromotionConfirmationForFree(PromotionConfirmationForFreeException e) {
+ while (true) {
+ try {
+ String userChoice = InputView.readPromotionConfirmationForFree(e.getItem().getName(), e.getShortfall());
+ Answer.validate(userChoice);
+ inventory.parseUserChoiceForFree(userChoice, e.getItem(), e.getOrderItem(), e.getShortfall());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private void processPurchaseConfirmationWithoutPromotion(PurchaseConfirmationWithoutPromotionException e) {
+ while (true) {
+ try {
+ String userChoice = getUserChoice(e);
+ inventory.parseUserChoiceWithoutPromotion(userChoice, e.getOrderItem(),
+ e.getRemainingPromotionQuantity(), e.getRemainingQuantity());
+ break;
+ } catch (IllegalArgumentException ex) {
+ OutputView.printError(ex.getMessage());
+ }
+ }
+ }
+
+ private String getUserChoice(PurchaseConfirmationWithoutPromotionException e) {
+ String userChoice = InputView.readPurchaseConfirmationWithoutPromotion(e.getItemName(),
+ Math.abs(e.getRemainingQuantity()));
+ Answer.validate(userChoice);
+ return userChoice;
+ }
+
+ private void printReceipt(Order order, boolean isMembership) {
+ PaymentSummary paymentSummary = OrderCalculator.calculateAmounts(order.getOrderItems(), isMembership);
+ List<OrderItemDto> orderItems = order.getOrderItems().stream().map(OrderItemDto::new).toList();
+ OutputView.printReceipt(new OrderDto(orderItems), paymentSummary);
+ }
+
+ private boolean isMembershipDiscountAccepted() {
+ while (true) {
+ try {
+ String userMembershipInput = InputView.readMembershipDiscountConfirmation();
+ Answer.validate(userMembershipInput);
+ return Answer.YES.isEqual(userMembershipInput);
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+
+ private boolean isAdditionalPurchaseConfirmed() {
+ String additionalPurchaseConfirmation = getAdditionalPurchaseConfirmation();
+ return Answer.YES.isEqual(additionalPurchaseConfirmation);
+ }
+
+ private String getAdditionalPurchaseConfirmation() {
+ while (true) {
+ try {
+ String userInput = InputView.readAdditionalPurchaseConfirmation();
+ Answer.validate(userInput);
+ return userInput;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e.getMessage());
+ }
+ }
+ }
+} | Java | 깔끔해질 것 같습니다.
느낌은 아래와 같나요?
다만 제 생각에는 깔끔하다는 것외에 혹시 제가 놓친 또 따른 장점이 있을까요?
```java
public StoreController(A a) {
this.inventory = a.inventory;
this.orderProcessor = a.orderProcessor;
}
``` |
@@ -0,0 +1,34 @@
+package store.error;
+
+import store.model.item.Item;
+import store.model.order.OrderItem;
+
+public class PromotionConfirmationForFreeException extends RuntimeException {
+ private Item item;
+ private OrderItem orderItem;
+ private int shortfall;
+
+ public PromotionConfirmationForFreeException(Item item, OrderItem orderItem, int shortfall) {
+ super();
+ this.item = item;
+ this.orderItem = orderItem;
+ this.shortfall = shortfall;
+ }
+
+
+ public Item getItem() {
+ return item;
+ }
+
+ public OrderItem getOrderItem() {
+ return orderItem;
+ }
+
+ public int getOrderQuantity() {
+ return orderItem.getQuantity();
+ }
+
+ public int getShortfall() {
+ return shortfall;
+ }
+} | Java | 제 구조에서는 view는 controller에서만 활동이가능합니다. (사용자 입력 출력 조정)
그렇기 때문에 비즈니스 로직에서 view를 바로 사용한다면 해당 예외가 필요없겠지만 흐름을 controller로 가져오기위해서는 예외밖에 생각이 나지 않았습니다. 그렇기에 view를 써야하는 상황에서 예외를 발생시켜서 흐름을 controller로 가져오고난 controller가 view를 동작시키도록 구현햇습니다.
선택을해야했습니다. 비즈니스 로직에서 view를 사용하느냐? 아님 흐름을 controller로 가져와서 controller가 상황에 맞게 view를 동작하게 하느냐 |
@@ -0,0 +1,23 @@
+package store.model;
+
+import java.util.function.Function;
+
+public enum SalesAmountType {
+ MEMBERSHIP("멤버십할인", Membership::calculateDiscount);
+
+ private final String viewName;
+ private final Function<Long, Long> expression;
+
+ SalesAmountType(String viewName, Function<Long, Long> expression) {
+ this.viewName = viewName;
+ this.expression = expression;
+ }
+
+ public long calculate(long amount) {
+ return expression.apply(amount);
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+} | Java | 이것도 시간 부족으로 남은 잔재입니다.
원래는 처음에는 총구매액/행사할인/멤버십할인을 전부 enum으로 관리할려고 했습니다.
그런데 구현하다보니 그렇게 하면 구현할 수없어서 하나둘씩 리팩터링을 하다보니 멤버십 할인만 남게되었습니다.
처음 생각한 느낌은 아래와 같습니다.
<img width="626" alt="image" src="https://github.com/user-attachments/assets/573f5877-4bb6-4642-882d-98c60c32b49a"> |
@@ -0,0 +1,81 @@
+package store.model.item;
+
+import store.error.FileContentException;
+
+public class Item {
+ private static final String KOREAN_REGEX = "^[가-힣]+$";
+ private static final int MAX_PRICE = 100_000_000;
+ public static final int MAX_QUANTITY = 999;
+
+ private final String name;
+ private final int price;
+ private final String promotionName;
+ private int quantity;
+
+ public Item(String name, int price, int quantity, String promotionName) {
+ validate(name, price, quantity);
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotionName = promotionName;
+ }
+
+ private void validate(String name, int price, int quantity) {
+ validateName(name);
+ validatePrice(price);
+ validateQuantity(quantity);
+ }
+
+ private void validateName(String name) {
+ if (name == null || name.trim().isEmpty()) {
+ throw new FileContentException("[ERROR] 상품 이름이 잘못되었습니다.");
+ }
+ if (!name.matches(KOREAN_REGEX)) {
+ throw new FileContentException("[ERROR] 상품 이름은 한글만 입력할 수 있습니다.");
+ }
+ }
+
+ private void validatePrice(int price) {
+ if (price < 0) {
+ throw new FileContentException("[ERROR] 가격은 0원 이상이어야 합니다.");
+ }
+ if (price > MAX_PRICE) {
+ throw new FileContentException("[ERROR] 가격은 최대 1억원 이하까지로만 설정할 수 있습니다.");
+ }
+ }
+
+ private void validateQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new FileContentException("[ERROR] 수량은 0개 이상으로만 설정할 수 있습니다.");
+ }
+ if (quantity > MAX_QUANTITY) {
+ throw new FileContentException("[ERROR] 수량은 최대 999개까지 설정할 수 있습니다.");
+ }
+ }
+
+ void decreaseQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new IllegalArgumentException("[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.");
+ }
+ if (this.quantity == 0) {
+ throw new IllegalArgumentException("[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.");
+ }
+ this.quantity -= quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPromotionName() {
+ return promotionName;
+ }
+} | Java | 이건 제 실수입니다. ㅜ
인텔리제이에서 단축키로 상수(Command + Option + C)를 만들면 기본값이 public으로 설정되기 때문에 만들고 나서 private으로 수정해주지 않으면 이렇게 됩니다. |
@@ -0,0 +1,81 @@
+package store.model.item;
+
+import store.error.FileContentException;
+
+public class Item {
+ private static final String KOREAN_REGEX = "^[가-힣]+$";
+ private static final int MAX_PRICE = 100_000_000;
+ public static final int MAX_QUANTITY = 999;
+
+ private final String name;
+ private final int price;
+ private final String promotionName;
+ private int quantity;
+
+ public Item(String name, int price, int quantity, String promotionName) {
+ validate(name, price, quantity);
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotionName = promotionName;
+ }
+
+ private void validate(String name, int price, int quantity) {
+ validateName(name);
+ validatePrice(price);
+ validateQuantity(quantity);
+ }
+
+ private void validateName(String name) {
+ if (name == null || name.trim().isEmpty()) {
+ throw new FileContentException("[ERROR] 상품 이름이 잘못되었습니다.");
+ }
+ if (!name.matches(KOREAN_REGEX)) {
+ throw new FileContentException("[ERROR] 상품 이름은 한글만 입력할 수 있습니다.");
+ }
+ }
+
+ private void validatePrice(int price) {
+ if (price < 0) {
+ throw new FileContentException("[ERROR] 가격은 0원 이상이어야 합니다.");
+ }
+ if (price > MAX_PRICE) {
+ throw new FileContentException("[ERROR] 가격은 최대 1억원 이하까지로만 설정할 수 있습니다.");
+ }
+ }
+
+ private void validateQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new FileContentException("[ERROR] 수량은 0개 이상으로만 설정할 수 있습니다.");
+ }
+ if (quantity > MAX_QUANTITY) {
+ throw new FileContentException("[ERROR] 수량은 최대 999개까지 설정할 수 있습니다.");
+ }
+ }
+
+ void decreaseQuantity(int quantity) {
+ if (quantity < 0) {
+ throw new IllegalArgumentException("[ERROR] 잘못된 입력입니다. 다시 입력해 주세요.");
+ }
+ if (this.quantity == 0) {
+ throw new IllegalArgumentException("[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.");
+ }
+ this.quantity -= quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPromotionName() {
+ return promotionName;
+ }
+} | Java | 수량은 스택오버플로우 방지 때문에 했고 가격은 int의 최대값을 안 넘으면서 편의점에서 있을 법한 가격으로 했습니다.
예전에 신문에서 한정판 위스키를 1억원대에 판매한다는 기사를 본적이 있어서 비슷하게 잡아봤습니다.
다만 상품 품목 개수 제한을 두지 않아서 무제한이면 스택오버플로우가 발생합니다. |
@@ -0,0 +1,76 @@
+package store.model.order;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class OrderItem {
+ private static final String DELIMITER = "-";
+ private static final String REGEX = "[\\[\\]]";
+ private static final Pattern EACH_PATTERN = Pattern.compile("\\[([가-힣]+)-(\\d+)]");
+ private static final String EMPTY = "";
+
+ private final String name;
+ private final int quantity;
+ private int promotionAppliedQuantity = 0;
+ private int totalOrderQuantity = 0;
+ private int nonPromotionQuantity = 0;
+ private int price = 0;
+
+ public OrderItem(String item) {
+ validate(item);
+ String[] itemData = parse(item);
+ this.name = itemData[0];
+ this.quantity = Integer.parseInt(itemData[1]);
+ }
+
+ private void validate(String item) {
+ Matcher matcher = EACH_PATTERN.matcher(item);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("올바르지 않은 형식으로 입력했습니다. 다시 입력해 주세요.");
+ }
+ }
+
+ private String[] parse(String item) {
+ return item.replaceAll(REGEX, EMPTY).split(DELIMITER);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public void increasePromotionAppliedQuantity(int quantity) {
+ promotionAppliedQuantity += quantity;
+ }
+
+ public void increaseNonPromotionQuantity(int quantity) {
+ nonPromotionQuantity += quantity;
+ }
+
+ public int getNonPromotionQuantity() {
+ return nonPromotionQuantity;
+ }
+
+ public int getPromotionAppliedQuantity() {
+ return promotionAppliedQuantity;
+ }
+
+ public void increaseTotalOrderQuantity(int quantity) {
+ totalOrderQuantity += quantity;
+ }
+
+ public int getTotalOrderQuantity() {
+ return totalOrderQuantity;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return this.price;
+ }
+} | Java | 그게 더 좋다고 생각합니다. 👍
제가봐도 많습니다. |
@@ -0,0 +1,158 @@
+package store.model.item;
+
+import java.io.IOException;
+import java.util.List;
+import store.error.FileParsingException;
+import store.error.PromotionConfirmationForFreeException;
+import store.model.Answer;
+import store.model.order.OrderItem;
+import store.model.promotion.Promotion;
+import store.model.promotion.PromotionCalculation;
+import store.model.promotion.PromotionManager;
+
+public class Inventory {
+ private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md";
+
+ private final ItemRepository itemRepository;
+ private final PromotionManager promotionManager;
+
+ public Inventory() {
+ this(PRODUCTS_FILE_PATH);
+ }
+
+ public Inventory(String productsFilePath) {
+ try {
+ this.promotionManager = new PromotionManager();
+ promotionManager.loadPromotions();
+ List<Item> items = ItemLoader.getInstance().loadItems(productsFilePath);
+ this.itemRepository = new ItemRepository(items, promotionManager);
+ } catch (IOException e) {
+ throw new FileParsingException(e);
+ }
+ }
+
+ public void validate(String itemName) {
+ itemRepository.validateItemName(itemName);
+ }
+
+ public void setPrice(OrderItem orderItem) {
+ for (Item item : itemRepository.getItems()) {
+ if (item.getName().equals(orderItem.getName())) {
+ orderItem.setPrice(item.getPrice());
+ }
+ }
+ }
+
+ public void consumePromotionItemWithoutPromotion(OrderItem orderItem) {
+ Item promotionItem = itemRepository.findPromotionItemByName(orderItem.getName());
+ int quantity = promotionItem.getQuantity();
+
+ itemRepository.decreaseQuantity(promotionItem, quantity);
+ orderItem.increaseTotalOrderQuantity(quantity);
+ orderItem.increaseNonPromotionQuantity(quantity);
+ }
+
+ public void consumePromotionItemWithoutPromotion(int orderQuantity, OrderItem orderItem) {
+ Item promotionItem = itemRepository.findPromotionItemByName(orderItem.getName());
+
+ itemRepository.decreaseQuantity(promotionItem, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increaseNonPromotionQuantity(orderQuantity);
+ }
+
+ public void consumePromotionItem(int orderQuantity, OrderItem orderItem) {
+ Item itemInInventory = itemRepository.findOnlyActivePromotionItem(orderItem.getName());
+ Promotion promotion = promotionManager.getPromotion(itemInInventory.getPromotionName());
+ PromotionCalculation promotionData = PromotionCalculation.of(promotion, orderQuantity);
+ processPromotionItem(orderQuantity, orderItem, promotionData, itemInInventory);
+ }
+
+ private void processPromotionItem(int orderQuantity, OrderItem orderItem, PromotionCalculation promotionData,
+ Item itemInInventory) {
+ if (promotionData.hasExactPromotionQuantity()) {
+ processPromotion(itemInInventory, orderItem, orderQuantity, promotionData.getPromotionAppliedQuantity());
+ return;
+ }
+ if (promotionData.hasPartialPromotion()) {
+ processNonPromotion(itemInInventory, orderItem, orderQuantity);
+ return;
+ }
+ throw new PromotionConfirmationForFreeException(itemInInventory, orderItem, promotionData.getShortfall());
+ }
+
+ private void processPromotion(Item item, OrderItem orderItem, int orderQuantity, int promotionQuantity) {
+ itemRepository.decreaseQuantity(item, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increasePromotionAppliedQuantity(promotionQuantity);
+ }
+
+ private void processNonPromotion(Item item, OrderItem orderItem, int orderQuantity) {
+ itemRepository.decreaseQuantity(item, orderQuantity);
+ orderItem.increaseTotalOrderQuantity(orderQuantity);
+ orderItem.increaseNonPromotionQuantity(orderQuantity);
+ }
+
+ public void consumeRegularItem(String itemName, int quantity, OrderItem orderItem) {
+ Item regularItem = itemRepository.findItemWithoutPromotionByName(itemName);
+ regularItem.decreaseQuantity(quantity);
+ orderItem.increaseTotalOrderQuantity(quantity);
+ orderItem.increaseNonPromotionQuantity(quantity);
+ }
+
+ public void parseUserChoiceWithoutPromotion(String userChoice, OrderItem orderItem, int remainingPromotionQuantity,
+ int remainingQuantity) {
+ if (Answer.YES.isEqual(userChoice)) {
+ consumePromotionItemWithoutPromotion(remainingPromotionQuantity, orderItem);
+ consumeRegularItem(orderItem.getName(), remainingQuantity - remainingPromotionQuantity, orderItem);
+ }
+ }
+
+ public void parseUserChoiceForFree(String userChoice, Item itemInInventory, OrderItem orderItem, int shortfall) {
+ if (Answer.YES.isEqual(userChoice)) {
+ itemRepository.decreaseQuantity(itemInInventory, orderItem.getQuantity() + shortfall);
+ orderItem.increaseTotalOrderQuantity(orderItem.getQuantity() + shortfall);
+ orderItem.increasePromotionAppliedQuantity(shortfall);
+ return;
+ }
+ itemRepository.decreaseQuantity(itemInInventory, orderItem.getQuantity());
+ orderItem.increaseTotalOrderQuantity(orderItem.getQuantity());
+ }
+
+ public int getApplicablePromotionQuantity(String itemName) {
+ int promotionQuantityForItem = getPromotionQuantityForItem(itemName);
+ int minPromotionQuantity = getMinPromotionQuantity(itemName);
+ if (minPromotionQuantity == 0) {
+ throw new IllegalStateException("일어나면 안되는 에러가 발생했습니다. : Inventory");
+ }
+ int remainder = promotionQuantityForItem % minPromotionQuantity;
+ return promotionQuantityForItem - remainder;
+ }
+
+ public int getMinPromotionQuantity(String itemName) {
+ return itemRepository.findMinPromotionQuantity(itemName);
+ }
+
+ public int getTotalQuantityForItem(String itemName) {
+ return itemRepository.findTotalQuantityForItem(itemName);
+ }
+
+ public int getPromotionQuantityForItem(String itemName) {
+ return itemRepository.findPromotionQuantityForItem(itemName);
+ }
+
+ public int getPromotionItemQuantityByName(String itemName) {
+ return itemRepository.findPromotionItemQuantityByName(itemName);
+ }
+
+ public boolean hasPromotion(String itemName) {
+ return itemRepository.hasPromotion(itemName);
+ }
+
+ public boolean isPromotionInactive(String itemName) {
+ return itemRepository.isPromotionInactive(itemName);
+ }
+
+ public List<Item> getItems() {
+ return itemRepository.getItems();
+ }
+} | Java | 맞습니다. 1,3은 확실히 분리해야합니다.! |
@@ -0,0 +1,77 @@
+package store.view.utils;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import store.common.constants.StringConstants;
+
+public class InputParser {
+ public static String inventoryParser(String name, Long price, Long quantity, String promotion) {
+ StringBuilder stringBuilderWithDash = new StringBuilder(giveBlankToEnd(StringConstants.DASH));
+
+ return appendAll(
+ stringBuilderWithDash,
+ giveBlankToEnd(name),
+ giveBlankToEnd(parsePrice(price)),
+ giveBlankToEnd(parseQuantity(quantity)),
+ parsePromotion(promotion)
+ ).toString();
+ }
+
+ public static Map<String, Long> purchaseInputParser(String[] inputArray) {
+ Map<String, Long> purchaseDetail = new HashMap<>();
+ Arrays.stream(inputArray).forEach(input -> {
+ String bracketsRemoved = input.replace("[", "").replace("]", "");
+ String[] inputSplit = bracketsRemoved.split(StringConstants.DASH);
+ purchaseDetail.put(inputSplit[0], Long.parseLong(inputSplit[1]));
+ });
+ return purchaseDetail;
+ }
+
+ public static StringBuilder giveCommaToPrice(String[] splitPrice) {
+ StringBuilder priceWithComma = new StringBuilder();
+ for (int i = splitPrice.length - 1 ; i >= 0; i--) {
+ priceWithComma.insert(0, splitPrice[i]);
+ if ((splitPrice.length - i) % 3 == 0 && i != 0) {
+ priceWithComma.insert(0, StringConstants.COMMA);
+ }
+ }
+ return priceWithComma;
+ }
+
+ private static String giveBlankToEnd(String name) {
+ return name + StringConstants.BLANK;
+ }
+
+ private static String parsePromotion(String promotion) {
+ String promotionNullConverted = promotion;
+ if (Objects.equals(promotion, "null")) {
+ promotionNullConverted = "";
+ }
+ return promotionNullConverted;
+ }
+
+ private static String parseQuantity(Long quantity) {
+ String quantityWithPieces = quantity.toString() + StringConstants.PIECES;
+ if (quantity == 0) {
+ quantityWithPieces = StringConstants.OUT_OF_STOCK;
+ }
+ return quantityWithPieces;
+ }
+
+ private static String parsePrice(Long price) {
+ if (price >= 1000) {
+ String[] splitPrice = price.toString().split("");
+ return giveCommaToPrice(splitPrice).append(StringConstants.WON).toString();
+ }
+ return price + StringConstants.WON;
+ }
+
+ private static StringBuilder appendAll(StringBuilder stringbuilder, String... strings) {
+ for (String string : strings) {
+ stringbuilder.append(string);
+ }
+ return stringbuilder;
+ }
+} | Java | `parsePrice` 메서드는 숫자에 천 단위 콤마를 추가하는 과정을 진행하고 있습니다.
자바에서 제공하는 `String.format` 의 `%,d` 를 사용하면 좋을 듯 합니다:) |
@@ -0,0 +1,8 @@
+package store.common.constants;
+
+public class AddressConstants {
+ public static final String productFilePath =
+ "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/products.md";
+ public static final String promotionFilePath =
+ "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/promotions.md";
+} | Java | 이 부분이 파일위치에 따라 문제가 발생할 수도 있을 것 같아요!
절대 경로가 아닌 상대 경로로 변경하는 건 어떨까요? |
@@ -0,0 +1,63 @@
+package store.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import java.util.Map;
+import store.common.constants.ErrorConstants;
+import store.common.constants.MessageConstants;
+import store.common.constants.StringConstants;
+import store.view.utils.InputParser;
+import store.view.utils.InputValidation;
+
+public class InputView {
+
+ public static Map<String, Long> askPurchaseProduct() {
+ System.out.println(MessageConstants.PRODUCT_PURCHASE_MESSAGE);
+ while (true) {
+ try {
+ String input = Console.readLine();
+ String[] inputSplit = InputValidation.validatePurchaseInput(input);
+ System.out.println();
+ return InputParser.purchaseInputParser(inputSplit);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ public static String tellPromotionNotApplicable(String name, Long quantity) {
+ System.out.printf(MessageConstants.PROMOTION_NOT_APPLY_MESSAGE, name, quantity);
+ System.out.println();
+ return getYesOrNoAnswer();
+ }
+
+ private static String getYesOrNoAnswer() {
+ while(true) {
+ try {
+ String answer = Console.readLine();
+ System.out.println();
+ if (!(answer.equals(StringConstants.NO) || answer.equals(StringConstants.YES))) {
+ throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE);
+ }
+ return answer;
+ } catch(IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ public static String tellFreeProductProvide(String name, Long quantity) {
+ System.out.printf(MessageConstants.PROMOTION_PROVIDE_FREE_PRODUCT_MESSAGE, name, quantity);
+ System.out.println();
+ return getYesOrNoAnswer();
+ }
+
+ public static String askMembershipDiscount() {
+ System.out.println(MessageConstants.MEMBERSHIP_DISCOUNT_MESSAGE);
+ return getYesOrNoAnswer();
+ }
+
+ public static String buyAnotherProduct() {
+ System.out.println(MessageConstants.EXIT_MESSAGE);
+ return getYesOrNoAnswer();
+ }
+} | Java | validation 로직과 parser 로직을 InputView에서 실행하는 것은 InputView에 너무 많은 책임을 부과하는 것 같습니다!
InputView에서는 안내 메시지 출력과 입력을 받는 부분만 남겨두고, 나머지 부분을 controller에 작성하시는 것은 어떠실까요? |
@@ -0,0 +1,63 @@
+package store.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import java.util.Map;
+import store.common.constants.ErrorConstants;
+import store.common.constants.MessageConstants;
+import store.common.constants.StringConstants;
+import store.view.utils.InputParser;
+import store.view.utils.InputValidation;
+
+public class InputView {
+
+ public static Map<String, Long> askPurchaseProduct() {
+ System.out.println(MessageConstants.PRODUCT_PURCHASE_MESSAGE);
+ while (true) {
+ try {
+ String input = Console.readLine();
+ String[] inputSplit = InputValidation.validatePurchaseInput(input);
+ System.out.println();
+ return InputParser.purchaseInputParser(inputSplit);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ public static String tellPromotionNotApplicable(String name, Long quantity) {
+ System.out.printf(MessageConstants.PROMOTION_NOT_APPLY_MESSAGE, name, quantity);
+ System.out.println();
+ return getYesOrNoAnswer();
+ }
+
+ private static String getYesOrNoAnswer() {
+ while(true) {
+ try {
+ String answer = Console.readLine();
+ System.out.println();
+ if (!(answer.equals(StringConstants.NO) || answer.equals(StringConstants.YES))) {
+ throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE);
+ }
+ return answer;
+ } catch(IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ public static String tellFreeProductProvide(String name, Long quantity) {
+ System.out.printf(MessageConstants.PROMOTION_PROVIDE_FREE_PRODUCT_MESSAGE, name, quantity);
+ System.out.println();
+ return getYesOrNoAnswer();
+ }
+
+ public static String askMembershipDiscount() {
+ System.out.println(MessageConstants.MEMBERSHIP_DISCOUNT_MESSAGE);
+ return getYesOrNoAnswer();
+ }
+
+ public static String buyAnotherProduct() {
+ System.out.println(MessageConstants.EXIT_MESSAGE);
+ return getYesOrNoAnswer();
+ }
+} | Java | 그리고 validation 로직을 parser 로직에 넣으시면 좋을 듯 합니다! |
@@ -0,0 +1,77 @@
+package store.view.utils;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import store.common.constants.StringConstants;
+
+public class InputParser {
+ public static String inventoryParser(String name, Long price, Long quantity, String promotion) {
+ StringBuilder stringBuilderWithDash = new StringBuilder(giveBlankToEnd(StringConstants.DASH));
+
+ return appendAll(
+ stringBuilderWithDash,
+ giveBlankToEnd(name),
+ giveBlankToEnd(parsePrice(price)),
+ giveBlankToEnd(parseQuantity(quantity)),
+ parsePromotion(promotion)
+ ).toString();
+ }
+
+ public static Map<String, Long> purchaseInputParser(String[] inputArray) {
+ Map<String, Long> purchaseDetail = new HashMap<>();
+ Arrays.stream(inputArray).forEach(input -> {
+ String bracketsRemoved = input.replace("[", "").replace("]", "");
+ String[] inputSplit = bracketsRemoved.split(StringConstants.DASH);
+ purchaseDetail.put(inputSplit[0], Long.parseLong(inputSplit[1]));
+ });
+ return purchaseDetail;
+ }
+
+ public static StringBuilder giveCommaToPrice(String[] splitPrice) {
+ StringBuilder priceWithComma = new StringBuilder();
+ for (int i = splitPrice.length - 1 ; i >= 0; i--) {
+ priceWithComma.insert(0, splitPrice[i]);
+ if ((splitPrice.length - i) % 3 == 0 && i != 0) {
+ priceWithComma.insert(0, StringConstants.COMMA);
+ }
+ }
+ return priceWithComma;
+ }
+
+ private static String giveBlankToEnd(String name) {
+ return name + StringConstants.BLANK;
+ }
+
+ private static String parsePromotion(String promotion) {
+ String promotionNullConverted = promotion;
+ if (Objects.equals(promotion, "null")) {
+ promotionNullConverted = "";
+ }
+ return promotionNullConverted;
+ }
+
+ private static String parseQuantity(Long quantity) {
+ String quantityWithPieces = quantity.toString() + StringConstants.PIECES;
+ if (quantity == 0) {
+ quantityWithPieces = StringConstants.OUT_OF_STOCK;
+ }
+ return quantityWithPieces;
+ }
+
+ private static String parsePrice(Long price) {
+ if (price >= 1000) {
+ String[] splitPrice = price.toString().split("");
+ return giveCommaToPrice(splitPrice).append(StringConstants.WON).toString();
+ }
+ return price + StringConstants.WON;
+ }
+
+ private static StringBuilder appendAll(StringBuilder stringbuilder, String... strings) {
+ for (String string : strings) {
+ stringbuilder.append(string);
+ }
+ return stringbuilder;
+ }
+} | Java | 동의합니다 |
@@ -0,0 +1,82 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import store.common.FileReader;
+import store.common.constants.AddressConstants;
+import store.common.constants.StringConstants;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Receipt;
+import store.service.FileService;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final FileService fileService;
+ private final StoreService storeService;
+
+ public StoreController(FileService fileService, StoreService storeService) {
+ this.fileService = fileService;
+ this.storeService = storeService;
+ }
+
+ public void run() {
+ List<Product> inventory = extractProducts(fileService); // 제품 추출
+ List<Promotion> promotions = extractPromotions(fileService); //프로모션 추출
+
+ while (true) {
+ String answerToContinue = processPurchase(inventory, storeService, promotions);
+ if (answerToContinue.equals(StringConstants.NO)) break;
+ }
+ }
+
+ private static List<Promotion> extractPromotions(FileService fileServiceImpl) {
+ Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath);
+ return fileServiceImpl.extractPromotion(promotionFile);
+ }
+
+ private static List<Product> extractProducts(FileService fileServiceImpl) {
+ Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath);
+ return fileServiceImpl.extractProduct(productsFile);
+ }
+
+ private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) {
+ OutputView.printWelcome(); // 환영 인사
+ OutputView.printInventoryDetail(inventory); // 재고 확인
+
+ List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // 구매
+ Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: 총구매 금액, totalReceipts[1]: 총할인 금액
+ Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1];
+ Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // 멤버십 할인 적용
+
+ OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // 영수증 출력
+
+ return InputView.buyAnotherProduct(); // 물건 반복 구매 문의
+ }
+
+ private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) {
+ String answerToApplyMembership = InputView.askMembershipDiscount();
+ return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership);
+ }
+
+ private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory,
+ List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+ while (receipts.isEmpty()) {
+ try {
+ Map<String, Long> productsToBuy = InputView.askPurchaseProduct();
+ productsToBuy.forEach((name, quantity) -> {
+ Receipt receipt = storeService.buy(name, quantity, inventory, promotions);
+ receipts.add(receipt);
+ });
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ return receipts;
+ }
+} | Java | Receipt에 멤버십 할인 적용을 포함 시키면 좋을 것 같습니다! |
@@ -0,0 +1,8 @@
+package store.common.constants;
+
+public class AddressConstants {
+ public static final String productFilePath =
+ "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/products.md";
+ public static final String promotionFilePath =
+ "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/promotions.md";
+} | Java | 동의합니다! |
@@ -0,0 +1,82 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import store.common.FileReader;
+import store.common.constants.AddressConstants;
+import store.common.constants.StringConstants;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Receipt;
+import store.service.FileService;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final FileService fileService;
+ private final StoreService storeService;
+
+ public StoreController(FileService fileService, StoreService storeService) {
+ this.fileService = fileService;
+ this.storeService = storeService;
+ }
+
+ public void run() {
+ List<Product> inventory = extractProducts(fileService); // 제품 추출
+ List<Promotion> promotions = extractPromotions(fileService); //프로모션 추출
+
+ while (true) {
+ String answerToContinue = processPurchase(inventory, storeService, promotions);
+ if (answerToContinue.equals(StringConstants.NO)) break;
+ }
+ }
+
+ private static List<Promotion> extractPromotions(FileService fileServiceImpl) {
+ Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath);
+ return fileServiceImpl.extractPromotion(promotionFile);
+ }
+
+ private static List<Product> extractProducts(FileService fileServiceImpl) {
+ Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath);
+ return fileServiceImpl.extractProduct(productsFile);
+ }
+
+ private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) {
+ OutputView.printWelcome(); // 환영 인사
+ OutputView.printInventoryDetail(inventory); // 재고 확인
+
+ List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // 구매
+ Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: 총구매 금액, totalReceipts[1]: 총할인 금액
+ Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1];
+ Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // 멤버십 할인 적용
+
+ OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // 영수증 출력
+
+ return InputView.buyAnotherProduct(); // 물건 반복 구매 문의
+ }
+
+ private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) {
+ String answerToApplyMembership = InputView.askMembershipDiscount();
+ return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership);
+ }
+
+ private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory,
+ List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+ while (receipts.isEmpty()) {
+ try {
+ Map<String, Long> productsToBuy = InputView.askPurchaseProduct();
+ productsToBuy.forEach((name, quantity) -> {
+ Receipt receipt = storeService.buy(name, quantity, inventory, promotions);
+ receipts.add(receipt);
+ });
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ return receipts;
+ }
+} | Java | 영수증 제작 관련 메서드를 따로 만들고, 해당 메서드를 호출하는 식으로 작성하시면 좀 더 보기 편할 것 같습니다! |
@@ -0,0 +1,82 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import store.common.FileReader;
+import store.common.constants.AddressConstants;
+import store.common.constants.StringConstants;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Receipt;
+import store.service.FileService;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final FileService fileService;
+ private final StoreService storeService;
+
+ public StoreController(FileService fileService, StoreService storeService) {
+ this.fileService = fileService;
+ this.storeService = storeService;
+ }
+
+ public void run() {
+ List<Product> inventory = extractProducts(fileService); // 제품 추출
+ List<Promotion> promotions = extractPromotions(fileService); //프로모션 추출
+
+ while (true) {
+ String answerToContinue = processPurchase(inventory, storeService, promotions);
+ if (answerToContinue.equals(StringConstants.NO)) break;
+ }
+ }
+
+ private static List<Promotion> extractPromotions(FileService fileServiceImpl) {
+ Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath);
+ return fileServiceImpl.extractPromotion(promotionFile);
+ }
+
+ private static List<Product> extractProducts(FileService fileServiceImpl) {
+ Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath);
+ return fileServiceImpl.extractProduct(productsFile);
+ }
+
+ private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) {
+ OutputView.printWelcome(); // 환영 인사
+ OutputView.printInventoryDetail(inventory); // 재고 확인
+
+ List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // 구매
+ Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: 총구매 금액, totalReceipts[1]: 총할인 금액
+ Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1];
+ Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // 멤버십 할인 적용
+
+ OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // 영수증 출력
+
+ return InputView.buyAnotherProduct(); // 물건 반복 구매 문의
+ }
+
+ private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) {
+ String answerToApplyMembership = InputView.askMembershipDiscount();
+ return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership);
+ }
+
+ private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory,
+ List<Promotion> promotions) {
+ List<Receipt> receipts = new ArrayList<>();
+ while (receipts.isEmpty()) {
+ try {
+ Map<String, Long> productsToBuy = InputView.askPurchaseProduct();
+ productsToBuy.forEach((name, quantity) -> {
+ Receipt receipt = storeService.buy(name, quantity, inventory, promotions);
+ receipts.add(receipt);
+ });
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ return receipts;
+ }
+} | Java | 동의합니다! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.