code stringlengths 41 34.3k | lang stringclasses 8 values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,63 @@
+package store;
+
+import store.domain.Stock;
+import store.domain.receipt.Receipt;
+import store.domain.order.OrderItems;
+import store.view.View;
+
+public class StoreController {
+ private final StoreService storeService;
+ private final Stock stock;
+
+ public StoreController(StoreService storeService, Stock stock) {
+ this.storeService = storeService;
+ this.stock = stock;
+ }
+
+ public void run() {
+ do {
+ runStoreProcess();
+ } while (askContinueShopping());
+ }
+
+ private void runStoreProcess() {
+ printGreetingMessage();
+ printStockStatus(stock);
+ OrderItems orderItems = getOrderItems();
+ try {
+ Receipt receipt = proceedPurchase(orderItems);
+ printReceipt(receipt);
+ } catch (Exception e) {
+ printErrorMessage(e.getMessage());
+ }
+ }
+
+ private void printGreetingMessage() {
+ View.getInstance().printGreetingMessage();
+ }
+
+ private void printStockStatus(Stock stock) {
+ View.getInstance().printStockStatus(stock.getProducts());
+ }
+
+ private OrderItems getOrderItems() {
+ String input = View.getInstance().promptBuyItems();
+ return storeService.getOrderItems(input);
+ }
+
+ private Receipt proceedPurchase(OrderItems orderItems) {
+ return storeService.proceedPurchase(stock, orderItems);
+ }
+
+ private void printReceipt(Receipt receipt) {
+ View.getInstance().printReceipt(receipt);
+ }
+
+ private boolean askContinueShopping() {
+ return View.getInstance().promptContinueShopping();
+ }
+
+ private void printErrorMessage(String errorMessage) {
+ View.getInstance().printErrorMessage(errorMessage);
+ }
+} | Java | 헉 감사합니다... ! 아직 부족한 스파게티인데 ... :( |
@@ -1 +1,90 @@
# java-convenience-store-precourse
+## 프로젝트 설명
+구매자의 할인 혜택과 재고 상황을 고려하여 최종 결제 금액을 계산하고 안내하는 결제 시스템을 구현하는 과제입니다.
+
+사용자가 입력한 상품별 가격과 수량을 곱하여 계산하고, 최종 결제 금액을 계산하여 영수증을 출력해야 합니다.
+각 상품의 재고를 고려하여 결제 가능 여부를 파악해야 하고, 프로모션이 적용되어 있는 상품들이 있습니다.
+프로모션은 N개 구매 시 1개 무료 증정의 형태로 진행되고, 오늘 날짜가 프로모션 기간 내라면 할인을 적용합니다.
+멤버십 회원은 프로모션이 적용되지 않은 금액의 30%를 할인받습니다. 최대 할인 한도는 8,000원입니다.
+영수증은 고객의 구매 내역과 할인을 요약하여 보기 좋게 출력해야 합니다.
+
+<br>
+
+## 기능 요구 사항에 기재되지 않아서 스스로 판단한 내용
+이번 과제는 기능 요구 사항에 기재되지 않은 애매한 내용들이 꽤 있었습니다.
+이에 대해 스스로 판단한 요구 사항을 알려드립니다.
+
+1. 프로모션 기간이 아직 시작되지 않았거나 이미 종료되었다면, 해당 상품은 프로모션이 적용되지 않은 일반 상품으로 취급되는 것이지 재고 자체가 사라지진 않습니다. 즉 일반 재고로 취급합니다.
+2. 멤버십 회원은 프로모션 재고 상품의 총 구매가를 제외한 구매 비용의 30%를 할인받습니다.
+3. 프로모션 2+1 콜라가 7개 있고, 사용자가 7개를 구매하길 원한다면 실제로 프로모션을 적용받을 수 있는 콜라는 6개까지이지만, 프로모션 재고가 부족한 것은 아니기에 7개를 모두 구매할 수 있습니다. (우아한테크코스의 예시를 참고하면, 프로모션 재고가 부족하여 일반 재고까지 구매해야 하는 상황에서만 프로모션이 미적용 되는 상품에 대해서 안내를 합니다. 예를 들어서 프로모션 2+1 콜라가 10개 있고, 일반 재고의 콜라가 10개 있는 상황에서 사용자가 12개를 구매하려고 한다면, 프로모션을 적용할 수 있는 실제 재고 개수는 9개 이므로 3개에 대해 프로모션 미적용 안내를 합니다)
+4. 프로모션이 적용된 모든 상품은 프로모션이 적용되지 않은 버전의 상품 정보도 표시해야 하고, 프로모션 미적용 상품이 존재하지 않는다면 "재고 없음" 을 표시해야 합니다.
+
+<br>
+
+## 설계 과정
+객체지향 설계에 있어서 가장 중요한 것은 협력을 위해 어떤 책임과 역할이 필요한지 이해하는 것이라고 생각합니다.
+따라서 설계의 방향을 잡기 위해 필요한 역할과 책임 그리고 메시지를 정리해 봤습니다.
+이후 정리한 내용을 통해 도출한 대략적인 그림을 참고해서 구현할 기능 목록을 하단에 요약했습니다.
+
+
+> 이해한 과제 내용을 대략적으로 정리하는 것은 필요한 역할과 책임을 이해하는 데에 도움이 된다고 생각합니다.
+> 이렇게 정리한 내용에서 영감을 받아 구현할 기능 목록을 대략적으로나마 작성할 수 있었습니다.
+> 물론 구현 중 계획했던 내용이 틀어질 수 있지만, 프로젝트를 시작하는 데에 도움이 되었습니다.
+
+<br>
+
+### 필요한 역할 및 기능
+- [x] 상품의 정보(상품명과 가격)을 가지고 있는 역할이 있어야 한다.
+- [x] 상품별 재고 정보를 가지고 있는 역할이 있어야 한다.
+- [x] 재고 수량을 고려하여 결제 가능 여부를 확인할 수 있어야 한다.
+- [x] 상품이 구입될 때마다, 결제된 수량만큼 해당 상품의 재고에서 차감해야 한다.
+- [x] 상품에 프로모션을 적용할 수 있어야 한다. 오늘 날짜가 프로모션 기간인 경우에만 할인을 적용해야 한다.
+- [x] 프로모션 기간 중이라면 프로모션 재고를 우선적으로 차감해야 한다.
+- [x] 멤버쉽 회원은 프로모션 미적용 금액의 30%를 할인받는다.
+- [x] 멤버쉽 할인의 최대 한도는 8,000원이다.
+- [x] 영수증 기능이 필요하다.
+
+
+### 메시지 정리
+- [x] 환영 문구를 출력하라 -> (출력 역할) -> OutputView
+- [x] 사용자에게 상품의 가격과 수량을 입력받아라 -> (입력 역할) -> InputView
+- [x] 상품 재고를 초기화하라 -> (파일 입출력해서 재고 초기화하는 역할) -> StoreInitializer
+- [x] 상품 재고를 출력하라 -> OutputView -> (상품 재고를 갖고있는 역할) -> StoreStock
+- [x] 결제 가능 여부를 파악하라 -> (상품 재고를 갖고있는 역할) -> StoreStock
+- [x] 프로모션 상품인지 확인하라 -> (상품 역할) -> StoreItem
+- [x] 프로모션 재고가 충분한지 파악하라 -> (상품 역할) -> StoreItem
+
+
+<br>
+
+
+## 구현할 기능 목록
+### 1. 출력 역할
+- [x] 출력 역할의 객체를 만든다
+- [x] 환영 문구를 출력하는 기능
+- [x] 재고 정보를 출력하는 기능
+- [x] 프롬프트 메시지를 출력하는 기능
+- [x] 영수증 내용을 출력하는 기능
+
+### 2. 입력 역할
+- [x] 입력 역할의 객체를 만든다
+- [x] 사용자에게 구매할 상품명과 수량을 입력받는 기능
+- [x] Y/N 형태로 입력받는 기능
+- [x] 입력 값이 잘못되었을 경우 오류 메시지와 함께 재입력 받는 기능
+
+### 3. 파일 입출력 역할
+- [x] 파일 입출력 역할의 객체를 만든다
+- [x] .md 파일을 읽어서 상품 재고를 초기화하는 기능
+
+### 4. 상품 역할
+- [x] 상품의 정보(상품명과 가격 등)을 가지고 있는 객체를 만든다
+- [x] 상품에 프로모션 정보를 포함할 수 있는 기능을 만든다
+
+### 5. 재고 역할
+- [x] 상품의 정보들을 가지고, 재고 역할을 하는 객체를 만든다
+- [x] 재고에서 특정 상품을 찾는 기능
+- [x] 프로모션 상품인지, 비 프로모션 상품인지 구분하는 기능
+
+### 6. 영수증 역할
+- [x] 영수증 역할의 객체를 만든다
+- [x] 구입 내역을 입력받아서 저장하는 기능
\ No newline at end of file | Unknown | 블로그에 회고 글을 작성했는데, 아래 링크에서 설계 과정을 참고하시면 답변이 될 것 같습니다!
https://hacanna42.tistory.com/304 |
@@ -1 +1,90 @@
# java-convenience-store-precourse
+## 프로젝트 설명
+구매자의 할인 혜택과 재고 상황을 고려하여 최종 결제 금액을 계산하고 안내하는 결제 시스템을 구현하는 과제입니다.
+
+사용자가 입력한 상품별 가격과 수량을 곱하여 계산하고, 최종 결제 금액을 계산하여 영수증을 출력해야 합니다.
+각 상품의 재고를 고려하여 결제 가능 여부를 파악해야 하고, 프로모션이 적용되어 있는 상품들이 있습니다.
+프로모션은 N개 구매 시 1개 무료 증정의 형태로 진행되고, 오늘 날짜가 프로모션 기간 내라면 할인을 적용합니다.
+멤버십 회원은 프로모션이 적용되지 않은 금액의 30%를 할인받습니다. 최대 할인 한도는 8,000원입니다.
+영수증은 고객의 구매 내역과 할인을 요약하여 보기 좋게 출력해야 합니다.
+
+<br>
+
+## 기능 요구 사항에 기재되지 않아서 스스로 판단한 내용
+이번 과제는 기능 요구 사항에 기재되지 않은 애매한 내용들이 꽤 있었습니다.
+이에 대해 스스로 판단한 요구 사항을 알려드립니다.
+
+1. 프로모션 기간이 아직 시작되지 않았거나 이미 종료되었다면, 해당 상품은 프로모션이 적용되지 않은 일반 상품으로 취급되는 것이지 재고 자체가 사라지진 않습니다. 즉 일반 재고로 취급합니다.
+2. 멤버십 회원은 프로모션 재고 상품의 총 구매가를 제외한 구매 비용의 30%를 할인받습니다.
+3. 프로모션 2+1 콜라가 7개 있고, 사용자가 7개를 구매하길 원한다면 실제로 프로모션을 적용받을 수 있는 콜라는 6개까지이지만, 프로모션 재고가 부족한 것은 아니기에 7개를 모두 구매할 수 있습니다. (우아한테크코스의 예시를 참고하면, 프로모션 재고가 부족하여 일반 재고까지 구매해야 하는 상황에서만 프로모션이 미적용 되는 상품에 대해서 안내를 합니다. 예를 들어서 프로모션 2+1 콜라가 10개 있고, 일반 재고의 콜라가 10개 있는 상황에서 사용자가 12개를 구매하려고 한다면, 프로모션을 적용할 수 있는 실제 재고 개수는 9개 이므로 3개에 대해 프로모션 미적용 안내를 합니다)
+4. 프로모션이 적용된 모든 상품은 프로모션이 적용되지 않은 버전의 상품 정보도 표시해야 하고, 프로모션 미적용 상품이 존재하지 않는다면 "재고 없음" 을 표시해야 합니다.
+
+<br>
+
+## 설계 과정
+객체지향 설계에 있어서 가장 중요한 것은 협력을 위해 어떤 책임과 역할이 필요한지 이해하는 것이라고 생각합니다.
+따라서 설계의 방향을 잡기 위해 필요한 역할과 책임 그리고 메시지를 정리해 봤습니다.
+이후 정리한 내용을 통해 도출한 대략적인 그림을 참고해서 구현할 기능 목록을 하단에 요약했습니다.
+
+
+> 이해한 과제 내용을 대략적으로 정리하는 것은 필요한 역할과 책임을 이해하는 데에 도움이 된다고 생각합니다.
+> 이렇게 정리한 내용에서 영감을 받아 구현할 기능 목록을 대략적으로나마 작성할 수 있었습니다.
+> 물론 구현 중 계획했던 내용이 틀어질 수 있지만, 프로젝트를 시작하는 데에 도움이 되었습니다.
+
+<br>
+
+### 필요한 역할 및 기능
+- [x] 상품의 정보(상품명과 가격)을 가지고 있는 역할이 있어야 한다.
+- [x] 상품별 재고 정보를 가지고 있는 역할이 있어야 한다.
+- [x] 재고 수량을 고려하여 결제 가능 여부를 확인할 수 있어야 한다.
+- [x] 상품이 구입될 때마다, 결제된 수량만큼 해당 상품의 재고에서 차감해야 한다.
+- [x] 상품에 프로모션을 적용할 수 있어야 한다. 오늘 날짜가 프로모션 기간인 경우에만 할인을 적용해야 한다.
+- [x] 프로모션 기간 중이라면 프로모션 재고를 우선적으로 차감해야 한다.
+- [x] 멤버쉽 회원은 프로모션 미적용 금액의 30%를 할인받는다.
+- [x] 멤버쉽 할인의 최대 한도는 8,000원이다.
+- [x] 영수증 기능이 필요하다.
+
+
+### 메시지 정리
+- [x] 환영 문구를 출력하라 -> (출력 역할) -> OutputView
+- [x] 사용자에게 상품의 가격과 수량을 입력받아라 -> (입력 역할) -> InputView
+- [x] 상품 재고를 초기화하라 -> (파일 입출력해서 재고 초기화하는 역할) -> StoreInitializer
+- [x] 상품 재고를 출력하라 -> OutputView -> (상품 재고를 갖고있는 역할) -> StoreStock
+- [x] 결제 가능 여부를 파악하라 -> (상품 재고를 갖고있는 역할) -> StoreStock
+- [x] 프로모션 상품인지 확인하라 -> (상품 역할) -> StoreItem
+- [x] 프로모션 재고가 충분한지 파악하라 -> (상품 역할) -> StoreItem
+
+
+<br>
+
+
+## 구현할 기능 목록
+### 1. 출력 역할
+- [x] 출력 역할의 객체를 만든다
+- [x] 환영 문구를 출력하는 기능
+- [x] 재고 정보를 출력하는 기능
+- [x] 프롬프트 메시지를 출력하는 기능
+- [x] 영수증 내용을 출력하는 기능
+
+### 2. 입력 역할
+- [x] 입력 역할의 객체를 만든다
+- [x] 사용자에게 구매할 상품명과 수량을 입력받는 기능
+- [x] Y/N 형태로 입력받는 기능
+- [x] 입력 값이 잘못되었을 경우 오류 메시지와 함께 재입력 받는 기능
+
+### 3. 파일 입출력 역할
+- [x] 파일 입출력 역할의 객체를 만든다
+- [x] .md 파일을 읽어서 상품 재고를 초기화하는 기능
+
+### 4. 상품 역할
+- [x] 상품의 정보(상품명과 가격 등)을 가지고 있는 객체를 만든다
+- [x] 상품에 프로모션 정보를 포함할 수 있는 기능을 만든다
+
+### 5. 재고 역할
+- [x] 상품의 정보들을 가지고, 재고 역할을 하는 객체를 만든다
+- [x] 재고에서 특정 상품을 찾는 기능
+- [x] 프로모션 상품인지, 비 프로모션 상품인지 구분하는 기능
+
+### 6. 영수증 역할
+- [x] 영수증 역할의 객체를 만든다
+- [x] 구입 내역을 입력받아서 저장하는 기능
\ No newline at end of file | Unknown | 추가로 설계는 전체적인 틀을 텍스트로 써내려가는 것이 아닌, 제가 스스로 감을 잡는식으로 하고 나머지는 구현 과정에서 채워 나갔습니다.
물론 이 방법으로 구현할 때 조금의 착오가 있긴했지만 나쁘지 않은 설계 방식 같습니다. |
@@ -0,0 +1,120 @@
+package store.view;
+
+import java.util.List;
+import store.domain.product.Product;
+import store.domain.receipt.BuyItem;
+import store.domain.receipt.FreeItem;
+import store.domain.receipt.Receipt;
+import store.messages.ReceiptForm;
+import store.messages.StoreMessage;
+
+class OutputView {
+ protected void printGreetingMessage() {
+ System.out.println(StoreMessage.GREETING.getMessage());
+ }
+
+ protected void printContinueShoppingMessage() {
+ System.out.println(StoreMessage.ASK_CONTINUE_SHOPPING.getMessage());
+ }
+
+ protected void printReceipt(Receipt receipt) {
+ printReceiptHeader();
+ printReceiptItems(receipt);
+ printReceiptFinals(receipt);
+ }
+
+ private void printReceiptHeader() {
+ newLine();
+ System.out.println(ReceiptForm.HEADER.getMessage());
+ System.out.printf(ReceiptForm.TITLES.getMessage(), ReceiptForm.WORD_ITEM_NAME.getMessage(),
+ ReceiptForm.WORD_ITEM_QUANTITY.getMessage(), ReceiptForm.WORD_ITEM_PRICE.getMessage());
+ }
+
+ private void printReceiptItems(Receipt receipt) {
+ // 구매한 상품 출력
+ for (BuyItem item : receipt.getBuyItems()) {
+ System.out.printf(ReceiptForm.BUY_ITEMS.getMessage(), item.getName(), item.getQuantity(),
+ item.getTotalPrice());
+ }
+ if (receipt.hasFreeItem()) {
+ System.out.println(ReceiptForm.PROMOTION_DIVIDER.getMessage());
+ // 증정 상품 출력
+ for (FreeItem item : receipt.getFreeItems()) {
+ System.out.printf(ReceiptForm.PROMOTION_ITEMS.getMessage(), item.getName(), item.getQuantity());
+ }
+ }
+ }
+
+ private void printReceiptFinals(Receipt receipt) {
+ System.out.println(ReceiptForm.FINAL_DIVIDER.getMessage());
+ // 총 구매액, 행사할인, 멤버십 할인, 내실 돈 출력
+ System.out.printf(ReceiptForm.TOTAL_PRICE.getMessage(), ReceiptForm.WORD_TOTAL_PRICE.getMessage(),
+ receipt.getTotalQuantity(), receipt.getTotalPrice());
+ System.out.printf(ReceiptForm.PROMOTION_DISCOUNT.getMessage(), ReceiptForm.WORD_PROMOTION_DISCOUNT.getMessage(),
+ receipt.getTotalPromotionDiscount());
+ System.out.printf(ReceiptForm.MEMBERSHIP_DISCOUNT.getMessage(),
+ ReceiptForm.WORD_MEMBERSHIP_DISCOUNT.getMessage(), receipt.getMembershipDiscount());
+ System.out.printf(ReceiptForm.FINAL_PRICE.getMessage(), ReceiptForm.WORD_FINAL_PRICE.getMessage(),
+ receipt.getFinalPrice());
+ newLine();
+ }
+
+ protected void printNoReceiptNotice() {
+ System.out.println(StoreMessage.NO_PURCHASE_NOTICE.getMessage());
+ }
+
+ protected void printBuyRequestMessage() {
+ newLine();
+ System.out.println(StoreMessage.BUY_REQUEST.getMessage());
+ }
+
+ protected void printStockStatus(List<Product> products) {
+ printStockNoticeMessage();
+ printStockItems(products);
+ }
+
+ private void printStockItems(List<Product> products) {
+ newLine();
+ for (Product product : products) {
+ if (product.getQuantity() != 0) {
+ System.out.printf(StoreMessage.STOCK_STATUS.getMessage(), product.getName(), product.getPrice(),
+ product.getQuantity(),
+ product.getPromotionName());
+ continue;
+ }
+ System.out.printf(StoreMessage.STOCK_STATUS_NO_STOCK.getMessage(), product.getName(), product.getPrice(),
+ product.getPromotionName());
+ }
+ System.out.flush();
+ }
+
+ protected void printFreePromotionNotice(String itemName, int freeItemCount) {
+ newLine();
+ System.out.printf(StoreMessage.ASK_FREE_PROMOTION.getMessage(), itemName, freeItemCount);
+ System.out.flush();
+ }
+
+ protected void printInsufficientPromotionNotice(String itemName, int notAppliedItemCount) {
+ newLine();
+ System.out.printf(StoreMessage.ASK_INSUFFICIENT_PROMOTION.getMessage(), itemName, notAppliedItemCount);
+ System.out.flush();
+ }
+
+ protected void printMembershipDiscountNotice() {
+ newLine();
+ System.out.println(StoreMessage.ASK_MEMBERSHIP_DISCOUNT.getMessage());
+ }
+
+ private void printStockNoticeMessage() {
+ System.out.println(StoreMessage.STOCK_NOTICE.getMessage());
+ }
+
+ protected void printErrorMessage(String errorMessage) {
+ newLine();
+ System.out.println(errorMessage);
+ }
+
+ protected void newLine() {
+ System.out.println();
+ }
+} | Java | 혹시 아무리 찾아도 안보이는데 와일드 카드가 어디 있을까요..? |
@@ -0,0 +1,120 @@
+package store.view;
+
+import java.util.List;
+import store.domain.product.Product;
+import store.domain.receipt.BuyItem;
+import store.domain.receipt.FreeItem;
+import store.domain.receipt.Receipt;
+import store.messages.ReceiptForm;
+import store.messages.StoreMessage;
+
+class OutputView {
+ protected void printGreetingMessage() {
+ System.out.println(StoreMessage.GREETING.getMessage());
+ }
+
+ protected void printContinueShoppingMessage() {
+ System.out.println(StoreMessage.ASK_CONTINUE_SHOPPING.getMessage());
+ }
+
+ protected void printReceipt(Receipt receipt) {
+ printReceiptHeader();
+ printReceiptItems(receipt);
+ printReceiptFinals(receipt);
+ }
+
+ private void printReceiptHeader() {
+ newLine();
+ System.out.println(ReceiptForm.HEADER.getMessage());
+ System.out.printf(ReceiptForm.TITLES.getMessage(), ReceiptForm.WORD_ITEM_NAME.getMessage(),
+ ReceiptForm.WORD_ITEM_QUANTITY.getMessage(), ReceiptForm.WORD_ITEM_PRICE.getMessage());
+ }
+
+ private void printReceiptItems(Receipt receipt) {
+ // 구매한 상품 출력
+ for (BuyItem item : receipt.getBuyItems()) {
+ System.out.printf(ReceiptForm.BUY_ITEMS.getMessage(), item.getName(), item.getQuantity(),
+ item.getTotalPrice());
+ }
+ if (receipt.hasFreeItem()) {
+ System.out.println(ReceiptForm.PROMOTION_DIVIDER.getMessage());
+ // 증정 상품 출력
+ for (FreeItem item : receipt.getFreeItems()) {
+ System.out.printf(ReceiptForm.PROMOTION_ITEMS.getMessage(), item.getName(), item.getQuantity());
+ }
+ }
+ }
+
+ private void printReceiptFinals(Receipt receipt) {
+ System.out.println(ReceiptForm.FINAL_DIVIDER.getMessage());
+ // 총 구매액, 행사할인, 멤버십 할인, 내실 돈 출력
+ System.out.printf(ReceiptForm.TOTAL_PRICE.getMessage(), ReceiptForm.WORD_TOTAL_PRICE.getMessage(),
+ receipt.getTotalQuantity(), receipt.getTotalPrice());
+ System.out.printf(ReceiptForm.PROMOTION_DISCOUNT.getMessage(), ReceiptForm.WORD_PROMOTION_DISCOUNT.getMessage(),
+ receipt.getTotalPromotionDiscount());
+ System.out.printf(ReceiptForm.MEMBERSHIP_DISCOUNT.getMessage(),
+ ReceiptForm.WORD_MEMBERSHIP_DISCOUNT.getMessage(), receipt.getMembershipDiscount());
+ System.out.printf(ReceiptForm.FINAL_PRICE.getMessage(), ReceiptForm.WORD_FINAL_PRICE.getMessage(),
+ receipt.getFinalPrice());
+ newLine();
+ }
+
+ protected void printNoReceiptNotice() {
+ System.out.println(StoreMessage.NO_PURCHASE_NOTICE.getMessage());
+ }
+
+ protected void printBuyRequestMessage() {
+ newLine();
+ System.out.println(StoreMessage.BUY_REQUEST.getMessage());
+ }
+
+ protected void printStockStatus(List<Product> products) {
+ printStockNoticeMessage();
+ printStockItems(products);
+ }
+
+ private void printStockItems(List<Product> products) {
+ newLine();
+ for (Product product : products) {
+ if (product.getQuantity() != 0) {
+ System.out.printf(StoreMessage.STOCK_STATUS.getMessage(), product.getName(), product.getPrice(),
+ product.getQuantity(),
+ product.getPromotionName());
+ continue;
+ }
+ System.out.printf(StoreMessage.STOCK_STATUS_NO_STOCK.getMessage(), product.getName(), product.getPrice(),
+ product.getPromotionName());
+ }
+ System.out.flush();
+ }
+
+ protected void printFreePromotionNotice(String itemName, int freeItemCount) {
+ newLine();
+ System.out.printf(StoreMessage.ASK_FREE_PROMOTION.getMessage(), itemName, freeItemCount);
+ System.out.flush();
+ }
+
+ protected void printInsufficientPromotionNotice(String itemName, int notAppliedItemCount) {
+ newLine();
+ System.out.printf(StoreMessage.ASK_INSUFFICIENT_PROMOTION.getMessage(), itemName, notAppliedItemCount);
+ System.out.flush();
+ }
+
+ protected void printMembershipDiscountNotice() {
+ newLine();
+ System.out.println(StoreMessage.ASK_MEMBERSHIP_DISCOUNT.getMessage());
+ }
+
+ private void printStockNoticeMessage() {
+ System.out.println(StoreMessage.STOCK_NOTICE.getMessage());
+ }
+
+ protected void printErrorMessage(String errorMessage) {
+ newLine();
+ System.out.println(errorMessage);
+ }
+
+ protected void newLine() {
+ System.out.println();
+ }
+} | Java | static으로 선언하지 않은것은 다양한 이유가 있는데..! 각각의 장단점이 있다고 생각합니다 :) |
@@ -0,0 +1,63 @@
+package store;
+
+import store.domain.Stock;
+import store.domain.receipt.Receipt;
+import store.domain.order.OrderItems;
+import store.view.View;
+
+public class StoreController {
+ private final StoreService storeService;
+ private final Stock stock;
+
+ public StoreController(StoreService storeService, Stock stock) {
+ this.storeService = storeService;
+ this.stock = stock;
+ }
+
+ public void run() {
+ do {
+ runStoreProcess();
+ } while (askContinueShopping());
+ }
+
+ private void runStoreProcess() {
+ printGreetingMessage();
+ printStockStatus(stock);
+ OrderItems orderItems = getOrderItems();
+ try {
+ Receipt receipt = proceedPurchase(orderItems);
+ printReceipt(receipt);
+ } catch (Exception e) {
+ printErrorMessage(e.getMessage());
+ }
+ }
+
+ private void printGreetingMessage() {
+ View.getInstance().printGreetingMessage();
+ }
+
+ private void printStockStatus(Stock stock) {
+ View.getInstance().printStockStatus(stock.getProducts());
+ }
+
+ private OrderItems getOrderItems() {
+ String input = View.getInstance().promptBuyItems();
+ return storeService.getOrderItems(input);
+ }
+
+ private Receipt proceedPurchase(OrderItems orderItems) {
+ return storeService.proceedPurchase(stock, orderItems);
+ }
+
+ private void printReceipt(Receipt receipt) {
+ View.getInstance().printReceipt(receipt);
+ }
+
+ private boolean askContinueShopping() {
+ return View.getInstance().promptContinueShopping();
+ }
+
+ private void printErrorMessage(String errorMessage) {
+ View.getInstance().printErrorMessage(errorMessage);
+ }
+} | Java | View를 싱글톤으로 관리하는 이유가 있으신지 여쭤보고 싶습니다 |
@@ -0,0 +1,19 @@
+package store.domain.order;
+
+import java.util.List;
+
+/**
+ * OrderItems 는 OrderItem 의 일급 컬렉션입니다.
+ * @see OrderItem
+ */
+public class OrderItems {
+ private final List<OrderItem> orderItems;
+
+ public OrderItems(List<OrderItem> orderItems) {
+ this.orderItems = List.copyOf(orderItems);
+ }
+
+ public List<OrderItem> getOrderItems() {
+ return orderItems;
+ }
+} | Java | OrderItems는 별도의 로직 없이 리스트를 필드로만 가지고 있는 것 같은데, 이런 구조는 의도된 설계인가요?
일반적으로 일급 컬렉션에서는 컬렉션을 직접 반환하는 getter 사용이 지양되는 것으로 알고 있습니다.
getter만 있는 경우, 외부에서 컬렉션을 직접 조작하거나, 관련 로직이 분산될 가능성이 있어 보여 질문드립니다. |
@@ -2,11 +2,16 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.type.filter.AnnotationTypeFilter;
+import org.springframework.stereotype.Controller;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
@@ -18,6 +23,8 @@
@Configuration
public class OpenApiConfig {
+ private static final String BASE_PACKAGE = "org.example.commerce_site.representation";
+
@Value("${springdoc.server-url}")
private String serverUrl;
@@ -46,56 +53,34 @@ public OpenAPI openAPI() {
}
@Bean
- public GroupedOpenApi userOpenApi() {
- String[] paths = {"/users/**"};
- return GroupedOpenApi.builder().group("USER API").pathsToMatch(paths).build();
- }
+ public List<GroupedOpenApi> groupedOpenApisByPackage() {
+ List<GroupedOpenApi> groupedApis = new ArrayList<>();
- @Bean
- public GroupedOpenApi partnerOpenApi() {
- String[] paths = {"/partners/**"};
- return GroupedOpenApi.builder().group("PARTNER API").pathsToMatch(paths).build();
- }
+ Set<String> subPackages = discoverControllerGroups(BASE_PACKAGE);
- @Bean
- public GroupedOpenApi productOpenApi() {
- String[] paths = {"/products/**"};
- return GroupedOpenApi.builder().group("PRODUCT API").pathsToMatch(paths).build();
- }
+ for (String pkg : subPackages) {
+ String groupName = pkg.substring(pkg.lastIndexOf('.') + 1).toUpperCase() + " API";
- @Bean
- public GroupedOpenApi categoryOpenApi() {
- String[] paths = {"/categories/**"};
- return GroupedOpenApi.builder().group("CATEGORY API").pathsToMatch(paths).build();
- }
+ groupedApis.add(GroupedOpenApi.builder()
+ .group(groupName)
+ .packagesToScan(pkg)
+ .build());
+ }
- @Bean
- public GroupedOpenApi addressOpenApi() {
- String[] paths = {"/addresses/**"};
- return GroupedOpenApi.builder().group("ADDRESS API").pathsToMatch(paths).build();
+ return groupedApis;
}
- @Bean
- public GroupedOpenApi cartOpenApi() {
- String[] paths = {"/carts/**"};
- return GroupedOpenApi.builder().group("CART API").pathsToMatch(paths).build();
- }
-
- @Bean
- public GroupedOpenApi orderOpenApi() {
- String[] paths = {"/orders/**"};
- return GroupedOpenApi.builder().group("ORDER API").pathsToMatch(paths).build();
- }
+ private Set<String> discoverControllerGroups(String basePackage) {
+ ClassPathScanningCandidateComponentProvider scanner =
+ new ClassPathScanningCandidateComponentProvider(false);
- @Bean
- public GroupedOpenApi paymentsOpenApi() {
- String[] paths = {"/payments/**"};
- return GroupedOpenApi.builder().group("PAYMENT API").pathsToMatch(paths).build();
- }
+ scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
- @Bean
- public GroupedOpenApi shipmentsOpenApi() {
- String[] paths = {"/shipments/**"};
- return GroupedOpenApi.builder().group("SHIPMENT API").pathsToMatch(paths).build();
+ return scanner.findCandidateComponents(basePackage).stream()
+ .map(beanDefinition -> {
+ String className = beanDefinition.getBeanClassName();
+ return className.substring(0, className.lastIndexOf('.'));
+ })
+ .collect(Collectors.toSet());
}
} | Java | url이 추가될때마다 매번 관리하는건 번거로운 일인데 매번 추가하지 않고 관리할 수 있는 방법은 없을까요? |
@@ -2,11 +2,16 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.type.filter.AnnotationTypeFilter;
+import org.springframework.stereotype.Controller;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
@@ -18,6 +23,8 @@
@Configuration
public class OpenApiConfig {
+ private static final String BASE_PACKAGE = "org.example.commerce_site.representation";
+
@Value("${springdoc.server-url}")
private String serverUrl;
@@ -46,56 +53,34 @@ public OpenAPI openAPI() {
}
@Bean
- public GroupedOpenApi userOpenApi() {
- String[] paths = {"/users/**"};
- return GroupedOpenApi.builder().group("USER API").pathsToMatch(paths).build();
- }
+ public List<GroupedOpenApi> groupedOpenApisByPackage() {
+ List<GroupedOpenApi> groupedApis = new ArrayList<>();
- @Bean
- public GroupedOpenApi partnerOpenApi() {
- String[] paths = {"/partners/**"};
- return GroupedOpenApi.builder().group("PARTNER API").pathsToMatch(paths).build();
- }
+ Set<String> subPackages = discoverControllerGroups(BASE_PACKAGE);
- @Bean
- public GroupedOpenApi productOpenApi() {
- String[] paths = {"/products/**"};
- return GroupedOpenApi.builder().group("PRODUCT API").pathsToMatch(paths).build();
- }
+ for (String pkg : subPackages) {
+ String groupName = pkg.substring(pkg.lastIndexOf('.') + 1).toUpperCase() + " API";
- @Bean
- public GroupedOpenApi categoryOpenApi() {
- String[] paths = {"/categories/**"};
- return GroupedOpenApi.builder().group("CATEGORY API").pathsToMatch(paths).build();
- }
+ groupedApis.add(GroupedOpenApi.builder()
+ .group(groupName)
+ .packagesToScan(pkg)
+ .build());
+ }
- @Bean
- public GroupedOpenApi addressOpenApi() {
- String[] paths = {"/addresses/**"};
- return GroupedOpenApi.builder().group("ADDRESS API").pathsToMatch(paths).build();
+ return groupedApis;
}
- @Bean
- public GroupedOpenApi cartOpenApi() {
- String[] paths = {"/carts/**"};
- return GroupedOpenApi.builder().group("CART API").pathsToMatch(paths).build();
- }
-
- @Bean
- public GroupedOpenApi orderOpenApi() {
- String[] paths = {"/orders/**"};
- return GroupedOpenApi.builder().group("ORDER API").pathsToMatch(paths).build();
- }
+ private Set<String> discoverControllerGroups(String basePackage) {
+ ClassPathScanningCandidateComponentProvider scanner =
+ new ClassPathScanningCandidateComponentProvider(false);
- @Bean
- public GroupedOpenApi paymentsOpenApi() {
- String[] paths = {"/payments/**"};
- return GroupedOpenApi.builder().group("PAYMENT API").pathsToMatch(paths).build();
- }
+ scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
- @Bean
- public GroupedOpenApi shipmentsOpenApi() {
- String[] paths = {"/shipments/**"};
- return GroupedOpenApi.builder().group("SHIPMENT API").pathsToMatch(paths).build();
+ return scanner.findCandidateComponents(basePackage).stream()
+ .map(beanDefinition -> {
+ String className = beanDefinition.getBeanClassName();
+ return className.substring(0, className.lastIndexOf('.'));
+ })
+ .collect(Collectors.toSet());
}
} | Java | representation 하위에 있는 패키지의 controller 들을 자동으로 등록하는 방식으로 수정했습니다! |
@@ -2,11 +2,16 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.type.filter.AnnotationTypeFilter;
+import org.springframework.stereotype.Controller;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
@@ -18,6 +23,8 @@
@Configuration
public class OpenApiConfig {
+ private static final String BASE_PACKAGE = "org.example.commerce_site.representation";
+
@Value("${springdoc.server-url}")
private String serverUrl;
@@ -46,56 +53,34 @@ public OpenAPI openAPI() {
}
@Bean
- public GroupedOpenApi userOpenApi() {
- String[] paths = {"/users/**"};
- return GroupedOpenApi.builder().group("USER API").pathsToMatch(paths).build();
- }
+ public List<GroupedOpenApi> groupedOpenApisByPackage() {
+ List<GroupedOpenApi> groupedApis = new ArrayList<>();
- @Bean
- public GroupedOpenApi partnerOpenApi() {
- String[] paths = {"/partners/**"};
- return GroupedOpenApi.builder().group("PARTNER API").pathsToMatch(paths).build();
- }
+ Set<String> subPackages = discoverControllerGroups(BASE_PACKAGE);
- @Bean
- public GroupedOpenApi productOpenApi() {
- String[] paths = {"/products/**"};
- return GroupedOpenApi.builder().group("PRODUCT API").pathsToMatch(paths).build();
- }
+ for (String pkg : subPackages) {
+ String groupName = pkg.substring(pkg.lastIndexOf('.') + 1).toUpperCase() + " API";
- @Bean
- public GroupedOpenApi categoryOpenApi() {
- String[] paths = {"/categories/**"};
- return GroupedOpenApi.builder().group("CATEGORY API").pathsToMatch(paths).build();
- }
+ groupedApis.add(GroupedOpenApi.builder()
+ .group(groupName)
+ .packagesToScan(pkg)
+ .build());
+ }
- @Bean
- public GroupedOpenApi addressOpenApi() {
- String[] paths = {"/addresses/**"};
- return GroupedOpenApi.builder().group("ADDRESS API").pathsToMatch(paths).build();
+ return groupedApis;
}
- @Bean
- public GroupedOpenApi cartOpenApi() {
- String[] paths = {"/carts/**"};
- return GroupedOpenApi.builder().group("CART API").pathsToMatch(paths).build();
- }
-
- @Bean
- public GroupedOpenApi orderOpenApi() {
- String[] paths = {"/orders/**"};
- return GroupedOpenApi.builder().group("ORDER API").pathsToMatch(paths).build();
- }
+ private Set<String> discoverControllerGroups(String basePackage) {
+ ClassPathScanningCandidateComponentProvider scanner =
+ new ClassPathScanningCandidateComponentProvider(false);
- @Bean
- public GroupedOpenApi paymentsOpenApi() {
- String[] paths = {"/payments/**"};
- return GroupedOpenApi.builder().group("PAYMENT API").pathsToMatch(paths).build();
- }
+ scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
- @Bean
- public GroupedOpenApi shipmentsOpenApi() {
- String[] paths = {"/shipments/**"};
- return GroupedOpenApi.builder().group("SHIPMENT API").pathsToMatch(paths).build();
+ return scanner.findCandidateComponents(basePackage).stream()
+ .map(beanDefinition -> {
+ String className = beanDefinition.getBeanClassName();
+ return className.substring(0, className.lastIndexOf('.'));
+ })
+ .collect(Collectors.toSet());
}
} | Java | 함수의 이름이 적절할지 한번더 고민해보시면 좋을 것 같습니다. |
@@ -2,11 +2,16 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
+import org.springframework.core.type.filter.AnnotationTypeFilter;
+import org.springframework.stereotype.Controller;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
@@ -18,6 +23,8 @@
@Configuration
public class OpenApiConfig {
+ private static final String BASE_PACKAGE = "org.example.commerce_site.representation";
+
@Value("${springdoc.server-url}")
private String serverUrl;
@@ -46,56 +53,34 @@ public OpenAPI openAPI() {
}
@Bean
- public GroupedOpenApi userOpenApi() {
- String[] paths = {"/users/**"};
- return GroupedOpenApi.builder().group("USER API").pathsToMatch(paths).build();
- }
+ public List<GroupedOpenApi> groupedOpenApisByPackage() {
+ List<GroupedOpenApi> groupedApis = new ArrayList<>();
- @Bean
- public GroupedOpenApi partnerOpenApi() {
- String[] paths = {"/partners/**"};
- return GroupedOpenApi.builder().group("PARTNER API").pathsToMatch(paths).build();
- }
+ Set<String> subPackages = discoverControllerGroups(BASE_PACKAGE);
- @Bean
- public GroupedOpenApi productOpenApi() {
- String[] paths = {"/products/**"};
- return GroupedOpenApi.builder().group("PRODUCT API").pathsToMatch(paths).build();
- }
+ for (String pkg : subPackages) {
+ String groupName = pkg.substring(pkg.lastIndexOf('.') + 1).toUpperCase() + " API";
- @Bean
- public GroupedOpenApi categoryOpenApi() {
- String[] paths = {"/categories/**"};
- return GroupedOpenApi.builder().group("CATEGORY API").pathsToMatch(paths).build();
- }
+ groupedApis.add(GroupedOpenApi.builder()
+ .group(groupName)
+ .packagesToScan(pkg)
+ .build());
+ }
- @Bean
- public GroupedOpenApi addressOpenApi() {
- String[] paths = {"/addresses/**"};
- return GroupedOpenApi.builder().group("ADDRESS API").pathsToMatch(paths).build();
+ return groupedApis;
}
- @Bean
- public GroupedOpenApi cartOpenApi() {
- String[] paths = {"/carts/**"};
- return GroupedOpenApi.builder().group("CART API").pathsToMatch(paths).build();
- }
-
- @Bean
- public GroupedOpenApi orderOpenApi() {
- String[] paths = {"/orders/**"};
- return GroupedOpenApi.builder().group("ORDER API").pathsToMatch(paths).build();
- }
+ private Set<String> discoverControllerGroups(String basePackage) {
+ ClassPathScanningCandidateComponentProvider scanner =
+ new ClassPathScanningCandidateComponentProvider(false);
- @Bean
- public GroupedOpenApi paymentsOpenApi() {
- String[] paths = {"/payments/**"};
- return GroupedOpenApi.builder().group("PAYMENT API").pathsToMatch(paths).build();
- }
+ scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
- @Bean
- public GroupedOpenApi shipmentsOpenApi() {
- String[] paths = {"/shipments/**"};
- return GroupedOpenApi.builder().group("SHIPMENT API").pathsToMatch(paths).build();
+ return scanner.findCandidateComponents(basePackage).stream()
+ .map(beanDefinition -> {
+ String className = beanDefinition.getBeanClassName();
+ return className.substring(0, className.lastIndexOf('.'));
+ })
+ .collect(Collectors.toSet());
}
} | Java | sub package를 구하고 등록하는 형태가 불안정한 것 같아요. package 네이밍 규칙 변경 등, 여러 요소에 따라 깨지기 쉬운 것 같은데, 이를 좀 더 안정적으로 관리할 수 있는 방법은 없을까요? |
@@ -0,0 +1,29 @@
+package subway.config;
+
+import java.util.Scanner;
+import subway.controller.SubwayController;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public enum AppConfig {
+
+ INSTANCE;
+
+ private final Scanner scanner = new Scanner(System.in);
+ private final InputView inputView = new InputView(scanner);
+ private final OutputView outputView = new OutputView();
+ private final MainService mainService = new MainService();
+ private final StationService stationService = new StationService();
+ private final LineService lineService = new LineService();
+ private final SectionService sectionService = new SectionService();
+ private final SubwayController subwayController = new SubwayController(inputView, outputView, mainService,
+ stationService, lineService, sectionService);
+
+ public SubwayController getController() {
+ return subwayController;
+ }
+} | Java | enum을 활용하여 controller에 대해 singleton을 보장하는 방식이 인상 깊습니다~! |
@@ -0,0 +1,31 @@
+package subway.constants;
+
+import subway.exception.ErrorMessage;
+
+public enum MainFeature {
+ SELECT_ONE("1"),
+ SELECT_TWO("2"),
+ SELECT_THREE("3"),
+ SELECT_FOUR("4"),
+ QUIT("Q");
+
+ final String message;
+
+ MainFeature(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return message;
+ }
+
+ public static MainFeature getFeatureFromInput(String input) {
+ for (MainFeature feature : MainFeature.values()) {
+ if (feature.toString().equalsIgnoreCase(input)) {
+ return feature;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FEATURE.toString());
+ }
+} | Java | "Q"와 같은 경우 "QUIT" 이라는 의미를 명확하게 부여했지만, 1이나 2와 같은 경우에 상대적으로 명확하지 않은 것 같습니다.
이를 더 명확하게 할 방법에 대해 더 고민해보면 좋을 것 같습니다. |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | 프로그램의 종료 값을 멤버변수로 관리하여 코드 간소화의 장점이 있지만, 단점이 더 많은 방법이라고 생각합니다.
어느 시점에 isRunning이 변경되는지를 추적해야하며, 그 과정에서 가독성에도 문제가 생길 수 있을거라고 생각합니다.
`handledMain`의 입력과 반환값을 더 명확히 하거나, 주석을 통해 설명을 적어둔다면 더 괜찮을 것 같습니다. 어떻게 생각하시나요? |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | Controller의 내용이 많은 것 같습니다. 클래스 분리를 해도 괜찮을 것 같아요..! |
@@ -0,0 +1,31 @@
+package subway.constants;
+
+import subway.exception.ErrorMessage;
+
+public enum MainFeature {
+ SELECT_ONE("1"),
+ SELECT_TWO("2"),
+ SELECT_THREE("3"),
+ SELECT_FOUR("4"),
+ QUIT("Q");
+
+ final String message;
+
+ MainFeature(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return message;
+ }
+
+ public static MainFeature getFeatureFromInput(String input) {
+ for (MainFeature feature : MainFeature.values()) {
+ if (feature.toString().equalsIgnoreCase(input)) {
+ return feature;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FEATURE.toString());
+ }
+} | Java | 감사합니다! 노선 관리와 역 관리를 한 번에 처리하다 보니 더 명확하지 않은 것도 있는 것 같습니당...
수정한다면 ADD, DELETE, SHOW 등으로 수정할 것 같습니다! |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | 음 이 부분도 고민이 됐던 부분입니다.
boolean 값을 매번 넘겨주고 반환하는 것이 효율적이지 못하다는 생각이 들어 멤버 변수로 관리하였습니다.
수정한다면 주석을 추가할 것 같습니다! |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | 이 부분도 고민됐던 부분입니다 ㅜ.ㅜ
service는 view에 의존하지 않아야 한다는 조건을 지키려다 보니 controller가 역할이 커졌습니다.
또, controller가 controller를 의존하게 하고 싶지 않아 고민하다 하나의 controller에서 처리하게 두었습니다.
결과적으로 아쉬움이 많이 남는 코드입니당... |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | 프로그램사용자가 잘못된 입력을 하면 예외처리를 하고 다시 입력하기 때문에 action은 항상 유효하다고 생각해서(null이 안들어오기에) 지워도 될 것 같습니다! |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | runnable이라는 걸 배우고 갑니다 신기하네요! |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | 멤버변수로 빼는건 어떻게 생각하시나요? |
@@ -0,0 +1,29 @@
+package subway.config;
+
+import java.util.Scanner;
+import subway.controller.SubwayController;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public enum AppConfig {
+
+ INSTANCE;
+
+ private final Scanner scanner = new Scanner(System.in);
+ private final InputView inputView = new InputView(scanner);
+ private final OutputView outputView = new OutputView();
+ private final MainService mainService = new MainService();
+ private final StationService stationService = new StationService();
+ private final LineService lineService = new LineService();
+ private final SectionService sectionService = new SectionService();
+ private final SubwayController subwayController = new SubwayController(inputView, outputView, mainService,
+ stationService, lineService, sectionService);
+
+ public SubwayController getController() {
+ return subwayController;
+ }
+} | Java | 저도 프리코스 기간동안 코드리뷰를 하며 알게된 사실인데, 함수 매개변수의 개수가 3개가 넘어가면 안좋다고 합니다. 3개 이하로 줄여보는 것은 어떨까요? |
@@ -0,0 +1,31 @@
+package subway.constants;
+
+import subway.exception.ErrorMessage;
+
+public enum MainFeature {
+ SELECT_ONE("1"),
+ SELECT_TWO("2"),
+ SELECT_THREE("3"),
+ SELECT_FOUR("4"),
+ QUIT("Q");
+
+ final String message;
+
+ MainFeature(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return message;
+ }
+
+ public static MainFeature getFeatureFromInput(String input) {
+ for (MainFeature feature : MainFeature.values()) {
+ if (feature.toString().equalsIgnoreCase(input)) {
+ return feature;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FEATURE.toString());
+ }
+} | Java | 저는 getter를 사용하는 것이 메서드 이름을 통해 명확히 "어떤 값(message)을 가져오는지" 드러낼 수 있어 의도에 맞는 함수라고 생각했기 때문에 getter 대신에 toString을 재정의하셔서 사용한 이유가 궁금합니다. |
@@ -0,0 +1,65 @@
+package subway.exception;
+
+import java.util.List;
+import java.util.Objects;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+
+public class InputValidator {
+
+ public static void validateInput(String input) {
+ ValidatorBuilder.from(input)
+ .validate(Objects::isNull, ErrorMessage.INVALID_INPUT)
+ .validate(String::isBlank, ErrorMessage.INVALID_INPUT);
+ }
+
+ public static void validateNameLength(String input) {
+ ValidatorBuilder.from(input)
+ .validate(value -> value.length() < 2, ErrorMessage.INVALID_NAME_LENGTH);
+ }
+
+ public static void validateStationsIsLessThanTwo(String[] stations) {
+ ValidatorBuilder.from(stations)
+ .validate(value -> value.length < 2, ErrorMessage.STATIONS_SHORTAGE);
+ }
+
+ public static void validateStationExists(String name) {
+ ValidatorBuilder.from(name)
+ .validate(value -> StationRepository.findStation(value).isEmpty()
+ , ErrorMessage.STATION_NOT_EXISTS);
+ }
+
+ public static void validateLineExists(String name) {
+ ValidatorBuilder.from(name)
+ .validate(value -> LineRepository.findLine(value).isEmpty()
+ , ErrorMessage.LINE_NOT_EXISTS);
+ }
+
+ public static void validateDuplicateInput(Station upperStation, String lowerStationName) {
+ ValidatorBuilder.from(lowerStationName)
+ .validate(value -> upperStation.getName().equals(value)
+ , ErrorMessage.DUPLICATE_STATION_INPUT_FOR_LINE);
+ }
+
+ public static int validateOrder(Line line, String input) {
+ List<Station> stations = line.getStations();
+
+ return ValidatorBuilder.from(input)
+ .validateIsInteger()
+ .validateInteger(value -> value < 1 && value > stations.size() - 1
+ , ErrorMessage.INVALID_SECTION_ORDER)
+ .getNumericValue();
+ }
+
+ public static void validateIsInLine(String findStation) {
+ ValidatorBuilder.from(findStation)
+ .validate(
+ station -> LineRepository.lines().stream()
+ .flatMap(line -> line.getStations().stream())
+ .anyMatch(existingStation -> existingStation.getName().equals(station))
+ , ErrorMessage.ALREADY_IN_LINE
+ );
+ }
+} | Java | 2와 같은 매직넘버는 상수로 관리하는 것이 좋아보여요 |
@@ -0,0 +1,89 @@
+package subway.repository;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+
+public class LineRepository {
+ private static final int LEAST_STATION_COUNT = 2;
+ private static final List<Line> lines = new ArrayList<>();
+
+ public static List<Line> lines() {
+ return Collections.unmodifiableList(lines);
+ }
+
+ public static void addLine(Line line) {
+ if (isDuplicate(line.getName())) {
+ throw new IllegalArgumentException(ErrorMessage.DUPLICATE_LINE_NAME.toString());
+ }
+
+ lines.add(line);
+ }
+
+ public static void deleteLineByName(String name) {
+ if (findLine(name).isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_NOT_EXISTS.toString());
+ }
+
+ lines.removeIf(line -> Objects.equals(line.getName(), name));
+ }
+
+ public static void addSection(Line line, Station station, int order) {
+ if (containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_ALREADY_HAS_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+ stations.add(order - 1, station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static void deleteSection(Line line, Station station) {
+ if (!containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_DOES_NOT_HAVE_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+
+ if (stations.size() <= LEAST_STATION_COUNT) {
+ throw new IllegalArgumentException(ErrorMessage.STATIONS_SHORTAGE.toString());
+ }
+
+ stations.remove(station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static Optional<Line> findLine(String name) {
+ return lines.stream()
+ .filter(line -> line.getName().equals(name))
+ .findFirst();
+ }
+
+ public static boolean containsStation(Line line, Station station) {
+ return line.getStations()
+ .contains(station);
+ }
+
+ public static void clearLines() {
+ lines.clear();
+ }
+
+ private static boolean isDuplicate(String name) {
+ return lines.stream()
+ .anyMatch(station -> Objects.equals(station.getName(), name));
+ }
+} | Java | 이런 검증 조건은, 저장소에서 처리하기 보다는 Line 이라는 객체를 생성하는 시점에 막아야 한다고 생각하는데 이에 대해서는 어떻게 생각하시나요? |
@@ -0,0 +1,89 @@
+package subway.repository;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+
+public class LineRepository {
+ private static final int LEAST_STATION_COUNT = 2;
+ private static final List<Line> lines = new ArrayList<>();
+
+ public static List<Line> lines() {
+ return Collections.unmodifiableList(lines);
+ }
+
+ public static void addLine(Line line) {
+ if (isDuplicate(line.getName())) {
+ throw new IllegalArgumentException(ErrorMessage.DUPLICATE_LINE_NAME.toString());
+ }
+
+ lines.add(line);
+ }
+
+ public static void deleteLineByName(String name) {
+ if (findLine(name).isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_NOT_EXISTS.toString());
+ }
+
+ lines.removeIf(line -> Objects.equals(line.getName(), name));
+ }
+
+ public static void addSection(Line line, Station station, int order) {
+ if (containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_ALREADY_HAS_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+ stations.add(order - 1, station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static void deleteSection(Line line, Station station) {
+ if (!containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_DOES_NOT_HAVE_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+
+ if (stations.size() <= LEAST_STATION_COUNT) {
+ throw new IllegalArgumentException(ErrorMessage.STATIONS_SHORTAGE.toString());
+ }
+
+ stations.remove(station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static Optional<Line> findLine(String name) {
+ return lines.stream()
+ .filter(line -> line.getName().equals(name))
+ .findFirst();
+ }
+
+ public static boolean containsStation(Line line, Station station) {
+ return line.getStations()
+ .contains(station);
+ }
+
+ public static void clearLines() {
+ lines.clear();
+ }
+
+ private static boolean isDuplicate(String name) {
+ return lines.stream()
+ .anyMatch(station -> Objects.equals(station.getName(), name));
+ }
+} | Java | 하나의 함수가 너무 많은 역할을 하는 것 같아요! 함수를 분리해보시는 건 어떨까요? |
@@ -0,0 +1,89 @@
+package subway.repository;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+
+public class LineRepository {
+ private static final int LEAST_STATION_COUNT = 2;
+ private static final List<Line> lines = new ArrayList<>();
+
+ public static List<Line> lines() {
+ return Collections.unmodifiableList(lines);
+ }
+
+ public static void addLine(Line line) {
+ if (isDuplicate(line.getName())) {
+ throw new IllegalArgumentException(ErrorMessage.DUPLICATE_LINE_NAME.toString());
+ }
+
+ lines.add(line);
+ }
+
+ public static void deleteLineByName(String name) {
+ if (findLine(name).isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_NOT_EXISTS.toString());
+ }
+
+ lines.removeIf(line -> Objects.equals(line.getName(), name));
+ }
+
+ public static void addSection(Line line, Station station, int order) {
+ if (containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_ALREADY_HAS_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+ stations.add(order - 1, station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static void deleteSection(Line line, Station station) {
+ if (!containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_DOES_NOT_HAVE_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+
+ if (stations.size() <= LEAST_STATION_COUNT) {
+ throw new IllegalArgumentException(ErrorMessage.STATIONS_SHORTAGE.toString());
+ }
+
+ stations.remove(station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static Optional<Line> findLine(String name) {
+ return lines.stream()
+ .filter(line -> line.getName().equals(name))
+ .findFirst();
+ }
+
+ public static boolean containsStation(Line line, Station station) {
+ return line.getStations()
+ .contains(station);
+ }
+
+ public static void clearLines() {
+ lines.clear();
+ }
+
+ private static boolean isDuplicate(String name) {
+ return lines.stream()
+ .anyMatch(station -> Objects.equals(station.getName(), name));
+ }
+} | Java | Optional로 반환하기 보다는, 해당 메서드에서 Line객체가 null 일 경우, 예외를 터뜨리도록 구현하는 것은 어떨까요?
해당 함수에서 처리한다면, findLine 메서드를 호출하는 다른 메서들에서 null 값을 반복적으로 처리해야하는 중복 작업을 줄일 수 있을 것 같습니다. |
@@ -0,0 +1,49 @@
+package subway.service;
+
+import subway.constants.StationLineFeature;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.StationRepository;
+
+public class StationService {
+
+ public StationLineFeature selectStationFeature(String selectedFeature) {
+ InputValidator.validateInput(selectedFeature);
+
+ return StationLineFeature.getFeatureFromInput(selectedFeature);
+ }
+
+ public void addStation(String stationName) {
+ InputValidator.validateInput(stationName);
+ InputValidator.validateNameLength(stationName);
+
+ StationRepository.addStation(new Station(stationName));
+ }
+
+ public void deleteStation(String stationName) {
+ InputValidator.validateInput(stationName);
+ InputValidator.validateNameLength(stationName);
+ InputValidator.validateIsInLine(stationName);
+
+ StationRepository.deleteStation(stationName);
+ }
+
+ public Station getStation(String stationName) {
+ InputValidator.validateInput(stationName);
+ InputValidator.validateNameLength(stationName);
+ InputValidator.validateStationExists(stationName);
+
+ return StationRepository.findStation(stationName)
+ .orElseThrow();
+ }
+
+ public Station getLowerStation(Station upperStation, String lowerStation) {
+ InputValidator.validateInput(lowerStation);
+ InputValidator.validateNameLength(lowerStation);
+ InputValidator.validateStationExists(lowerStation);
+ InputValidator.validateDuplicateInput(upperStation, lowerStation);
+
+ return StationRepository.findStation(lowerStation)
+ .orElseThrow();
+ }
+} | Java | 기본적으로, orElseThrow()는 NoSuchElementException을 던지도록 설계되어있기 때문에 새로운 예외인 `IllegalArgumentExcepion`을 던지도록 하는 작업이 필요해보여요. 그렇지 않을 경우, RetryHandler가 해당 예외를 잡지 못할 것 같습니다. |
@@ -0,0 +1,90 @@
+package subway.util;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+
+public class FileLoader {
+
+ private static final String STATION_FILEPATH = "src/main/resources/stations.md";
+ private static final String LINE_FILEPATH = "src/main/resources/lines.md";
+ private static final String LINE_SPLITTER = "-";
+ private static final String STATION_SPLITTER = ",";
+ private static final int LINE_INDEX = 0;
+ private static final int STATIONS_INDEX = 1;
+
+ public static void loadSettings() {
+ loadStations();
+ loadLines();
+ }
+
+ private static void loadStations() {
+ try (BufferedReader br = new BufferedReader(new FileReader(STATION_FILEPATH))) {
+ br.lines()
+ .forEach(FileLoader::handleStation);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FILE_LOAD.toString());
+ }
+ }
+
+ static void handleStation(String input) {
+ InputValidator.validateInput(input);
+ InputValidator.validateNameLength(input);
+
+ Station station = new Station(input);
+ StationRepository.addStation(station);
+ }
+
+ private static void loadLines() {
+ try (BufferedReader br = new BufferedReader(new FileReader(LINE_FILEPATH))) {
+ br.lines()
+ .forEach(FileLoader::handleLine);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FILE_LOAD.toString());
+ }
+ }
+
+ static void handleLine(String input) {
+ InputValidator.validateInput(input);
+
+ String[] parts = input.split(LINE_SPLITTER);
+ String lineName = parts[LINE_INDEX];
+ String[] stations = parts[STATIONS_INDEX].split(STATION_SPLITTER);
+
+ InputValidator.validateNameLength(lineName);
+ Arrays.stream(stations)
+ .forEach(station -> {
+ InputValidator.validateInput(station);
+ InputValidator.validateNameLength(station);
+ });
+
+ Line line = new Line(lineName, handleStationsOfLine(stations));
+ LineRepository.addLine(line);
+ }
+
+ static LinkedList<Station> handleStationsOfLine(String[] stations) {
+ InputValidator.validateStationsIsLessThanTwo(stations);
+ LinkedList<Station> stationsOfLine = new LinkedList<>();
+
+ Arrays.stream(stations)
+ .forEach(stationName -> {
+ Optional<Station> station = StationRepository.findStation(stationName);
+
+ if (station.isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.STATION_NOT_EXISTS.toString());
+ }
+
+ stationsOfLine.add(station.get());
+ });
+
+ return stationsOfLine;
+ }
+} | Java | 이 부분 Optional이 제공하는 api(`isPresent`)를 사용한다면 더 간단히 정리할 수 있을 것 같아요. |
@@ -0,0 +1,29 @@
+package subway.config;
+
+import java.util.Scanner;
+import subway.controller.SubwayController;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public enum AppConfig {
+
+ INSTANCE;
+
+ private final Scanner scanner = new Scanner(System.in);
+ private final InputView inputView = new InputView(scanner);
+ private final OutputView outputView = new OutputView();
+ private final MainService mainService = new MainService();
+ private final StationService stationService = new StationService();
+ private final LineService lineService = new LineService();
+ private final SectionService sectionService = new SectionService();
+ private final SubwayController subwayController = new SubwayController(inputView, outputView, mainService,
+ stationService, lineService, sectionService);
+
+ public SubwayController getController() {
+ return subwayController;
+ }
+} | Java | 해당 코드는 의존성 주입을 위한 부분이라고 생각되는데, DI를 적용하지 않고 클래스 내부에서 의존성을 직접 생성하는 것을 지향하시는걸까요?? |
@@ -0,0 +1,29 @@
+package subway.config;
+
+import java.util.Scanner;
+import subway.controller.SubwayController;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public enum AppConfig {
+
+ INSTANCE;
+
+ private final Scanner scanner = new Scanner(System.in);
+ private final InputView inputView = new InputView(scanner);
+ private final OutputView outputView = new OutputView();
+ private final MainService mainService = new MainService();
+ private final StationService stationService = new StationService();
+ private final LineService lineService = new LineService();
+ private final SectionService sectionService = new SectionService();
+ private final SubwayController subwayController = new SubwayController(inputView, outputView, mainService,
+ stationService, lineService, sectionService);
+
+ public SubwayController getController() {
+ return subwayController;
+ }
+} | Java | 저도 이 부분 의견이 궁금합니다! @kgy1008 |
@@ -0,0 +1,31 @@
+package subway.constants;
+
+import subway.exception.ErrorMessage;
+
+public enum MainFeature {
+ SELECT_ONE("1"),
+ SELECT_TWO("2"),
+ SELECT_THREE("3"),
+ SELECT_FOUR("4"),
+ QUIT("Q");
+
+ final String message;
+
+ MainFeature(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return message;
+ }
+
+ public static MainFeature getFeatureFromInput(String input) {
+ for (MainFeature feature : MainFeature.values()) {
+ if (feature.toString().equalsIgnoreCase(input)) {
+ return feature;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FEATURE.toString());
+ }
+} | Java | 다른 코드에서 이렇게 활용하시는 걸 봐서 따라해 본 것인데, 말씀해주신 부분을 생각해보니 getXXX로 사용하는 편이 의도가 확실할 것 같습니다. |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | 앗 그렇네요! 감사합니다 :) |
@@ -0,0 +1,267 @@
+package subway.controller;
+
+import java.util.EnumMap;
+import subway.constants.MainFeature;
+import subway.constants.SectionFeature;
+import subway.constants.StationLineFeature;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.MainService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.util.FileLoader;
+import subway.util.RetryHandler;
+import subway.view.InputView;
+import subway.view.OutputView;
+
+public class SubwayController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final MainService mainService;
+ private final StationService stationService;
+ private final LineService lineService;
+ private final SectionService sectionService;
+
+ private boolean isRunning = true;
+
+ public SubwayController(InputView inputView, OutputView outputView, MainService mainService,
+ StationService stationService, LineService lineService, SectionService sectionService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.mainService = mainService;
+ this.stationService = stationService;
+ this.lineService = lineService;
+ this.sectionService = sectionService;
+ }
+
+ public void start() {
+ FileLoader.loadSettings();
+
+ while (isRunning) {
+ handledMain(selectMainFeature());
+ outputView.printBlank();
+ }
+ }
+
+ private MainFeature selectMainFeature() {
+ outputView.printMain();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return mainService.selectMainFeature(selectedFeature);
+ });
+ }
+
+ private void handledMain(MainFeature selectedFeature) {
+ EnumMap<MainFeature, Runnable> actions = new EnumMap<>(MainFeature.class);
+ actions.put(MainFeature.SELECT_ONE, () -> processStationManagement(selectStationFeature()));
+ actions.put(MainFeature.SELECT_TWO, () -> processLineManagement(selectLineFeature()));
+ actions.put(MainFeature.SELECT_THREE, () -> processSectionManagement(selectSectionFeature()));
+ actions.put(MainFeature.SELECT_FOUR, this::showSubwayLines);
+ actions.put(MainFeature.QUIT, this::quitProgram);
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void executeAction(Runnable action) {
+ if (action != null) {
+ action.run();
+ }
+ }
+
+ private StationLineFeature selectStationFeature() {
+ outputView.printStationManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return stationService.selectStationFeature(selectedFeature);
+ });
+ }
+
+ private void processStationManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::enrollStation);
+ actions.put(StationLineFeature.SELECT_TWO, this::deleteStation);
+ actions.put(StationLineFeature.SELECT_THREE, this::showStations);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationEnroll();
+ stationService.addStation(stationName);
+ outputView.printEnrollStationSuccess();
+ });
+ }
+
+ private void deleteStation() {
+ RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationDelete();
+ stationService.deleteStation(stationName);
+ outputView.printDeleteStationSuccess();
+ });
+ }
+
+ private void showStations() {
+ outputView.printStations(StationRepository.stations());
+ }
+
+ private StationLineFeature selectLineFeature() {
+ outputView.printLineManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return lineService.selectLineFeature(selectedFeature);
+ });
+ }
+
+ private void processLineManagement(StationLineFeature selectedFeature) {
+ EnumMap<StationLineFeature, Runnable> actions = new EnumMap<>(StationLineFeature.class);
+ actions.put(StationLineFeature.SELECT_ONE, this::handleEnrollLine);
+ actions.put(StationLineFeature.SELECT_TWO, () -> deleteLine(getLDeleteLine()));
+ actions.put(StationLineFeature.SELECT_THREE, this::showLines);
+ actions.put(StationLineFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void handleEnrollLine() {
+ String lineName = getLEnrollLineName();
+ Station upperStation = getUpperStation();
+ Station lowerStation = getLowerStation(upperStation);
+ enrollLine(lineName, upperStation, lowerStation);
+ }
+
+ private void enrollLine(String lineName, Station upperStation, Station lowerStation) {
+ lineService.enrollLine(lineName, upperStation, lowerStation);
+ outputView.printEnrollLineSuccess();
+ }
+
+ private void deleteLine(String lineName) {
+ LineRepository.deleteLineByName(lineName);
+ outputView.printDeleteLineSuccess();
+ }
+
+ private void showLines() {
+ outputView.printLines(LineRepository.lines());
+ }
+
+ private String getLEnrollLineName() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineEnroll();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private Station getUpperStation() {
+ return RetryHandler.handleRetry(() -> {
+ String upperStation = inputView.askUpperStation();
+ return stationService.getStation(upperStation);
+ });
+ }
+
+ private Station getLowerStation(Station upperStation) {
+ return RetryHandler.handleRetry(() -> {
+ String lowerStation = inputView.askLowerStation();
+ return stationService.getLowerStation(upperStation, lowerStation);
+ });
+ }
+
+ private String getLDeleteLine() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineDelete();
+ return lineService.getValidLineName(lineName);
+ });
+ }
+
+ private SectionFeature selectSectionFeature() {
+ outputView.printSectionManagement();
+ return RetryHandler.handleRetry(() -> {
+ String selectedFeature = inputView.askFeature();
+ return sectionService.selectSectionFeature(selectedFeature);
+ });
+ }
+
+ private void processSectionManagement(SectionFeature selectedFeature) {
+ EnumMap<SectionFeature, Runnable> actions = new EnumMap<>(SectionFeature.class);
+ actions.put(SectionFeature.SELECT_ONE, this::enrollSection);
+ actions.put(SectionFeature.SELECT_TWO, this::deleteSection);
+ actions.put(SectionFeature.BACK, () -> {
+ });
+
+ Runnable action = actions.get(selectedFeature);
+ executeAction(action);
+ }
+
+ private void enrollSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getEnrollLineOfSection();
+ Station station = getStationOfSection();
+ int order = getOrderOfSection(line);
+
+ LineRepository.addSection(line, station, order);
+ outputView.printEnrollSectionSuccess();
+ });
+ }
+
+ private void deleteSection() {
+ RetryHandler.handleRetry(() -> {
+ Line line = getDeleteLineOfSection();
+ Station station = getDeleteStationOfSection();
+
+ LineRepository.deleteSection(line, station);
+ outputView.printDeleteSectionSuccess();
+ });
+ }
+
+ private Line getEnrollLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askLineNameOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askStationNameOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private int getOrderOfSection(Line line) {
+ return RetryHandler.handleRetry(() -> {
+ return InputValidator.validateOrder(line, inputView.askOrderOfSection());
+ });
+ }
+
+ private Line getDeleteLineOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String lineName = inputView.askDeleteLineOfSection();
+ return lineService.getLine(lineName);
+ });
+ }
+
+ private Station getDeleteStationOfSection() {
+ return RetryHandler.handleRetry(() -> {
+ String stationName = inputView.askDeleteStationOfSection();
+ return stationService.getStation(stationName);
+ });
+ }
+
+ private void showSubwayLines() {
+ outputView.printSubwayLinesInformation(LineRepository.lines());
+ }
+
+ private void quitProgram() {
+ isRunning = false;
+ }
+} | Java | StationLineFeature 과 MainFeature, SectionFeature를 각각 key로 사용하기에 애매해서 매번 생성하였습니다ㅜ
하지만 로직이 겹치는 부분이긴 합니다... 좀 더 고민하면 멤버변수로 뺄 수 있을 것 같습니닷 |
@@ -0,0 +1,65 @@
+package subway.exception;
+
+import java.util.List;
+import java.util.Objects;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+
+public class InputValidator {
+
+ public static void validateInput(String input) {
+ ValidatorBuilder.from(input)
+ .validate(Objects::isNull, ErrorMessage.INVALID_INPUT)
+ .validate(String::isBlank, ErrorMessage.INVALID_INPUT);
+ }
+
+ public static void validateNameLength(String input) {
+ ValidatorBuilder.from(input)
+ .validate(value -> value.length() < 2, ErrorMessage.INVALID_NAME_LENGTH);
+ }
+
+ public static void validateStationsIsLessThanTwo(String[] stations) {
+ ValidatorBuilder.from(stations)
+ .validate(value -> value.length < 2, ErrorMessage.STATIONS_SHORTAGE);
+ }
+
+ public static void validateStationExists(String name) {
+ ValidatorBuilder.from(name)
+ .validate(value -> StationRepository.findStation(value).isEmpty()
+ , ErrorMessage.STATION_NOT_EXISTS);
+ }
+
+ public static void validateLineExists(String name) {
+ ValidatorBuilder.from(name)
+ .validate(value -> LineRepository.findLine(value).isEmpty()
+ , ErrorMessage.LINE_NOT_EXISTS);
+ }
+
+ public static void validateDuplicateInput(Station upperStation, String lowerStationName) {
+ ValidatorBuilder.from(lowerStationName)
+ .validate(value -> upperStation.getName().equals(value)
+ , ErrorMessage.DUPLICATE_STATION_INPUT_FOR_LINE);
+ }
+
+ public static int validateOrder(Line line, String input) {
+ List<Station> stations = line.getStations();
+
+ return ValidatorBuilder.from(input)
+ .validateIsInteger()
+ .validateInteger(value -> value < 1 && value > stations.size() - 1
+ , ErrorMessage.INVALID_SECTION_ORDER)
+ .getNumericValue();
+ }
+
+ public static void validateIsInLine(String findStation) {
+ ValidatorBuilder.from(findStation)
+ .validate(
+ station -> LineRepository.lines().stream()
+ .flatMap(line -> line.getStations().stream())
+ .anyMatch(existingStation -> existingStation.getName().equals(station))
+ , ErrorMessage.ALREADY_IN_LINE
+ );
+ }
+} | Java | 감사합니다! |
@@ -0,0 +1,89 @@
+package subway.repository;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+
+public class LineRepository {
+ private static final int LEAST_STATION_COUNT = 2;
+ private static final List<Line> lines = new ArrayList<>();
+
+ public static List<Line> lines() {
+ return Collections.unmodifiableList(lines);
+ }
+
+ public static void addLine(Line line) {
+ if (isDuplicate(line.getName())) {
+ throw new IllegalArgumentException(ErrorMessage.DUPLICATE_LINE_NAME.toString());
+ }
+
+ lines.add(line);
+ }
+
+ public static void deleteLineByName(String name) {
+ if (findLine(name).isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_NOT_EXISTS.toString());
+ }
+
+ lines.removeIf(line -> Objects.equals(line.getName(), name));
+ }
+
+ public static void addSection(Line line, Station station, int order) {
+ if (containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_ALREADY_HAS_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+ stations.add(order - 1, station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static void deleteSection(Line line, Station station) {
+ if (!containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_DOES_NOT_HAVE_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+
+ if (stations.size() <= LEAST_STATION_COUNT) {
+ throw new IllegalArgumentException(ErrorMessage.STATIONS_SHORTAGE.toString());
+ }
+
+ stations.remove(station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static Optional<Line> findLine(String name) {
+ return lines.stream()
+ .filter(line -> line.getName().equals(name))
+ .findFirst();
+ }
+
+ public static boolean containsStation(Line line, Station station) {
+ return line.getStations()
+ .contains(station);
+ }
+
+ public static void clearLines() {
+ lines.clear();
+ }
+
+ private static boolean isDuplicate(String name) {
+ return lines.stream()
+ .anyMatch(station -> Objects.equals(station.getName(), name));
+ }
+} | Java | 확실히 그렇네요. Line 도메인이 하는 역할이 너무 적어 고민이었는데 검증을 내부에서 처리한다면 해결될 것 같습니다! |
@@ -0,0 +1,89 @@
+package subway.repository;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+
+public class LineRepository {
+ private static final int LEAST_STATION_COUNT = 2;
+ private static final List<Line> lines = new ArrayList<>();
+
+ public static List<Line> lines() {
+ return Collections.unmodifiableList(lines);
+ }
+
+ public static void addLine(Line line) {
+ if (isDuplicate(line.getName())) {
+ throw new IllegalArgumentException(ErrorMessage.DUPLICATE_LINE_NAME.toString());
+ }
+
+ lines.add(line);
+ }
+
+ public static void deleteLineByName(String name) {
+ if (findLine(name).isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_NOT_EXISTS.toString());
+ }
+
+ lines.removeIf(line -> Objects.equals(line.getName(), name));
+ }
+
+ public static void addSection(Line line, Station station, int order) {
+ if (containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_ALREADY_HAS_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+ stations.add(order - 1, station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static void deleteSection(Line line, Station station) {
+ if (!containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_DOES_NOT_HAVE_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+
+ if (stations.size() <= LEAST_STATION_COUNT) {
+ throw new IllegalArgumentException(ErrorMessage.STATIONS_SHORTAGE.toString());
+ }
+
+ stations.remove(station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static Optional<Line> findLine(String name) {
+ return lines.stream()
+ .filter(line -> line.getName().equals(name))
+ .findFirst();
+ }
+
+ public static boolean containsStation(Line line, Station station) {
+ return line.getStations()
+ .contains(station);
+ }
+
+ public static void clearLines() {
+ lines.clear();
+ }
+
+ private static boolean isDuplicate(String name) {
+ return lines.stream()
+ .anyMatch(station -> Objects.equals(station.getName(), name));
+ }
+} | Java | 감사합니다! |
@@ -0,0 +1,89 @@
+package subway.repository;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+
+public class LineRepository {
+ private static final int LEAST_STATION_COUNT = 2;
+ private static final List<Line> lines = new ArrayList<>();
+
+ public static List<Line> lines() {
+ return Collections.unmodifiableList(lines);
+ }
+
+ public static void addLine(Line line) {
+ if (isDuplicate(line.getName())) {
+ throw new IllegalArgumentException(ErrorMessage.DUPLICATE_LINE_NAME.toString());
+ }
+
+ lines.add(line);
+ }
+
+ public static void deleteLineByName(String name) {
+ if (findLine(name).isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_NOT_EXISTS.toString());
+ }
+
+ lines.removeIf(line -> Objects.equals(line.getName(), name));
+ }
+
+ public static void addSection(Line line, Station station, int order) {
+ if (containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_ALREADY_HAS_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+ stations.add(order - 1, station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static void deleteSection(Line line, Station station) {
+ if (!containsStation(line, station)) {
+ throw new IllegalArgumentException(ErrorMessage.LINE_DOES_NOT_HAVE_THIS_STATION.toString());
+ }
+
+ LinkedList<Station> stations = new LinkedList<>(line.getStations());
+
+ if (stations.size() <= LEAST_STATION_COUNT) {
+ throw new IllegalArgumentException(ErrorMessage.STATIONS_SHORTAGE.toString());
+ }
+
+ stations.remove(station);
+
+ deleteLineByName(line.getName());
+
+ Line newLine = new Line(line.getName(), stations);
+ lines.add(newLine);
+ }
+
+ public static Optional<Line> findLine(String name) {
+ return lines.stream()
+ .filter(line -> line.getName().equals(name))
+ .findFirst();
+ }
+
+ public static boolean containsStation(Line line, Station station) {
+ return line.getStations()
+ .contains(station);
+ }
+
+ public static void clearLines() {
+ lines.clear();
+ }
+
+ private static boolean isDuplicate(String name) {
+ return lines.stream()
+ .anyMatch(station -> Objects.equals(station.getName(), name));
+ }
+} | Java | 확실히 더 나은 방법인 것 같습니다! 감사합니다 :) |
@@ -0,0 +1,49 @@
+package subway.service;
+
+import subway.constants.StationLineFeature;
+import subway.domain.Station;
+import subway.exception.InputValidator;
+import subway.repository.StationRepository;
+
+public class StationService {
+
+ public StationLineFeature selectStationFeature(String selectedFeature) {
+ InputValidator.validateInput(selectedFeature);
+
+ return StationLineFeature.getFeatureFromInput(selectedFeature);
+ }
+
+ public void addStation(String stationName) {
+ InputValidator.validateInput(stationName);
+ InputValidator.validateNameLength(stationName);
+
+ StationRepository.addStation(new Station(stationName));
+ }
+
+ public void deleteStation(String stationName) {
+ InputValidator.validateInput(stationName);
+ InputValidator.validateNameLength(stationName);
+ InputValidator.validateIsInLine(stationName);
+
+ StationRepository.deleteStation(stationName);
+ }
+
+ public Station getStation(String stationName) {
+ InputValidator.validateInput(stationName);
+ InputValidator.validateNameLength(stationName);
+ InputValidator.validateStationExists(stationName);
+
+ return StationRepository.findStation(stationName)
+ .orElseThrow();
+ }
+
+ public Station getLowerStation(Station upperStation, String lowerStation) {
+ InputValidator.validateInput(lowerStation);
+ InputValidator.validateNameLength(lowerStation);
+ InputValidator.validateStationExists(lowerStation);
+ InputValidator.validateDuplicateInput(upperStation, lowerStation);
+
+ return StationRepository.findStation(lowerStation)
+ .orElseThrow();
+ }
+} | Java | 생각지 못한 부분인데 감사합니다! 따로 처리를 꼭 해야 할 것 같습니다 |
@@ -0,0 +1,90 @@
+package subway.util;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.Optional;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ErrorMessage;
+import subway.exception.InputValidator;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+
+public class FileLoader {
+
+ private static final String STATION_FILEPATH = "src/main/resources/stations.md";
+ private static final String LINE_FILEPATH = "src/main/resources/lines.md";
+ private static final String LINE_SPLITTER = "-";
+ private static final String STATION_SPLITTER = ",";
+ private static final int LINE_INDEX = 0;
+ private static final int STATIONS_INDEX = 1;
+
+ public static void loadSettings() {
+ loadStations();
+ loadLines();
+ }
+
+ private static void loadStations() {
+ try (BufferedReader br = new BufferedReader(new FileReader(STATION_FILEPATH))) {
+ br.lines()
+ .forEach(FileLoader::handleStation);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FILE_LOAD.toString());
+ }
+ }
+
+ static void handleStation(String input) {
+ InputValidator.validateInput(input);
+ InputValidator.validateNameLength(input);
+
+ Station station = new Station(input);
+ StationRepository.addStation(station);
+ }
+
+ private static void loadLines() {
+ try (BufferedReader br = new BufferedReader(new FileReader(LINE_FILEPATH))) {
+ br.lines()
+ .forEach(FileLoader::handleLine);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_FILE_LOAD.toString());
+ }
+ }
+
+ static void handleLine(String input) {
+ InputValidator.validateInput(input);
+
+ String[] parts = input.split(LINE_SPLITTER);
+ String lineName = parts[LINE_INDEX];
+ String[] stations = parts[STATIONS_INDEX].split(STATION_SPLITTER);
+
+ InputValidator.validateNameLength(lineName);
+ Arrays.stream(stations)
+ .forEach(station -> {
+ InputValidator.validateInput(station);
+ InputValidator.validateNameLength(station);
+ });
+
+ Line line = new Line(lineName, handleStationsOfLine(stations));
+ LineRepository.addLine(line);
+ }
+
+ static LinkedList<Station> handleStationsOfLine(String[] stations) {
+ InputValidator.validateStationsIsLessThanTwo(stations);
+ LinkedList<Station> stationsOfLine = new LinkedList<>();
+
+ Arrays.stream(stations)
+ .forEach(stationName -> {
+ Optional<Station> station = StationRepository.findStation(stationName);
+
+ if (station.isEmpty()) {
+ throw new IllegalArgumentException(ErrorMessage.STATION_NOT_EXISTS.toString());
+ }
+
+ stationsOfLine.add(station.get());
+ });
+
+ return stationsOfLine;
+ }
+} | Java | 감사합니다! |
@@ -0,0 +1,35 @@
+package controller;
+
+import java.util.Objects;
+import model.Orders;
+import model.Receipts;
+import view.InputView;
+import view.OutputView;
+
+public final class ApplicationController {
+ public void run() {
+ LoadDataController.loadData();
+ do {
+ runTurn();
+ } while (!exitCheck());
+ }
+
+ public void runTurn() {
+ clear();
+ OutputView.outputInventory();
+ OrderController.order();
+ PurchaseController.purchaseExec();
+ MembershipController.membership();
+ OutputView.outputReceipts(Receipts.getPurchases());
+ }
+
+ public static void clear() {
+ Orders.clearOrders();
+ Receipts.clear();
+ }
+
+ public boolean exitCheck() {
+ String input = InputView.exitCheck();
+ return Objects.equals(input, "N");
+ }
+} | Java | static으로 설정하신 이유가 있을까요? |
@@ -0,0 +1,35 @@
+package controller;
+
+import config.PathConfig;
+import dto.ProductDTO;
+import java.util.List;
+import model.Inventory;
+import model.Promotion;
+import model.Promotions;
+import util.FileUtil;
+import util.SplitUtil;
+
+public final class LoadDataController {
+ public static void loadData() {
+ promotionsData();
+ productsData();
+ }
+
+ public static void productsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PRODUCTS_FILE_PATH.getFilePath());
+ for(String content: fileContents) {
+ ProductDTO productDTO = SplitUtil.createProductDTOFromContent(content);
+ Inventory.productAdd(productDTO);
+ }
+ }
+
+ public static void promotionsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PROMOTIONS_FILE_PATH.getFilePath());
+ fileContents.stream()
+ .map(SplitUtil::createPromotionFromContent)
+ // 처음 promotions.promotion에 현재 기간에 행사 진행하는 것만 넣을 건지 다 넣을 건지 filter
+ .filter(promotion -> Promotion.currentPromotion(promotion.startTime(), promotion.endTime()))
+ .forEach(Promotions::add);
+ }
+}
+ | Java | 메소드 명은 동사나 전치사로 시작하는 걸 추천드립니다 |
@@ -0,0 +1,35 @@
+package controller;
+
+import config.PathConfig;
+import dto.ProductDTO;
+import java.util.List;
+import model.Inventory;
+import model.Promotion;
+import model.Promotions;
+import util.FileUtil;
+import util.SplitUtil;
+
+public final class LoadDataController {
+ public static void loadData() {
+ promotionsData();
+ productsData();
+ }
+
+ public static void productsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PRODUCTS_FILE_PATH.getFilePath());
+ for(String content: fileContents) {
+ ProductDTO productDTO = SplitUtil.createProductDTOFromContent(content);
+ Inventory.productAdd(productDTO);
+ }
+ }
+
+ public static void promotionsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PROMOTIONS_FILE_PATH.getFilePath());
+ fileContents.stream()
+ .map(SplitUtil::createPromotionFromContent)
+ // 처음 promotions.promotion에 현재 기간에 행사 진행하는 것만 넣을 건지 다 넣을 건지 filter
+ .filter(promotion -> Promotion.currentPromotion(promotion.startTime(), promotion.endTime()))
+ .forEach(Promotions::add);
+ }
+}
+ | Java | 외부에서 사용하지 않기 때문에 private으로 닫아도 될 것 같습니다 |
@@ -0,0 +1,35 @@
+package controller;
+
+import java.util.Objects;
+import model.Orders;
+import model.Receipts;
+import view.InputView;
+import view.OutputView;
+
+public final class ApplicationController {
+ public void run() {
+ LoadDataController.loadData();
+ do {
+ runTurn();
+ } while (!exitCheck());
+ }
+
+ public void runTurn() {
+ clear();
+ OutputView.outputInventory();
+ OrderController.order();
+ PurchaseController.purchaseExec();
+ MembershipController.membership();
+ OutputView.outputReceipts(Receipts.getPurchases());
+ }
+
+ public static void clear() {
+ Orders.clearOrders();
+ Receipts.clear();
+ }
+
+ public boolean exitCheck() {
+ String input = InputView.exitCheck();
+ return Objects.equals(input, "N");
+ }
+} | Java | 사용자로부터 받는 Y,N은 상수나 이넘으로 빼는건 어떨까요? |
@@ -0,0 +1,21 @@
+package io;
+
+import camp.nextstep.edu.missionutils.Console;
+import validation.InputValidation;
+import view.OutputView;
+
+public final class Input {
+ public static String inputMessage() {
+ return Console.readLine();
+ }
+
+ public static String inputYOrN() {
+ while(true) {
+ try {
+ return InputValidation.isYorN(inputMessage());
+ } catch (IllegalArgumentException error){
+ OutputView.outputErrorMessage(error);
+ }
+ }
+ }
+} | Java | 저는 사용자로부터 입력을 받는 거 자체가 inputView의 역할이라 생각이 되어 Console.readLine()을 사용한 사용자 입력부분을 inputView에 담아뒀습니다. 혹시 Input이라는 클래스로 역할을 나누신 이유가 있을까요?? 제가 모르는 부분이 있다면 배우고 싶어 여쭤봅니다! |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | 저는 final 키워드를 앞에 붙이는걸 완전 까먹고 있었는데, 활용하시다니 놀랍습니다!! |
@@ -0,0 +1,35 @@
+package controller;
+
+import java.util.Objects;
+import model.Orders;
+import model.Receipts;
+import view.InputView;
+import view.OutputView;
+
+public final class ApplicationController {
+ public void run() {
+ LoadDataController.loadData();
+ do {
+ runTurn();
+ } while (!exitCheck());
+ }
+
+ public void runTurn() {
+ clear();
+ OutputView.outputInventory();
+ OrderController.order();
+ PurchaseController.purchaseExec();
+ MembershipController.membership();
+ OutputView.outputReceipts(Receipts.getPurchases());
+ }
+
+ public static void clear() {
+ Orders.clearOrders();
+ Receipts.clear();
+ }
+
+ public boolean exitCheck() {
+ String input = InputView.exitCheck();
+ return Objects.equals(input, "N");
+ }
+} | Java | clear() 함수 안에 있는 Orders.clearOrders(); Receipts.clear(); 2개의 명령이 주문 내역과 영수증 내역을 초기화하는 명령입니다.
이 내역들은 static List로 구현되어 있고 함수 자체가 static이라서 static 함수로 만들었습니다. |
@@ -0,0 +1,35 @@
+package controller;
+
+import config.PathConfig;
+import dto.ProductDTO;
+import java.util.List;
+import model.Inventory;
+import model.Promotion;
+import model.Promotions;
+import util.FileUtil;
+import util.SplitUtil;
+
+public final class LoadDataController {
+ public static void loadData() {
+ promotionsData();
+ productsData();
+ }
+
+ public static void productsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PRODUCTS_FILE_PATH.getFilePath());
+ for(String content: fileContents) {
+ ProductDTO productDTO = SplitUtil.createProductDTOFromContent(content);
+ Inventory.productAdd(productDTO);
+ }
+ }
+
+ public static void promotionsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PROMOTIONS_FILE_PATH.getFilePath());
+ fileContents.stream()
+ .map(SplitUtil::createPromotionFromContent)
+ // 처음 promotions.promotion에 현재 기간에 행사 진행하는 것만 넣을 건지 다 넣을 건지 filter
+ .filter(promotion -> Promotion.currentPromotion(promotion.startTime(), promotion.endTime()))
+ .forEach(Promotions::add);
+ }
+}
+ | Java | 오 감사합니다!! 놓쳤던 부분 발견해 주셔서 감사합니다.!! |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | 감사합니다!! |
@@ -0,0 +1,35 @@
+package controller;
+
+import java.util.Objects;
+import model.Orders;
+import model.Receipts;
+import view.InputView;
+import view.OutputView;
+
+public final class ApplicationController {
+ public void run() {
+ LoadDataController.loadData();
+ do {
+ runTurn();
+ } while (!exitCheck());
+ }
+
+ public void runTurn() {
+ clear();
+ OutputView.outputInventory();
+ OrderController.order();
+ PurchaseController.purchaseExec();
+ MembershipController.membership();
+ OutputView.outputReceipts(Receipts.getPurchases());
+ }
+
+ public static void clear() {
+ Orders.clearOrders();
+ Receipts.clear();
+ }
+
+ public boolean exitCheck() {
+ String input = InputView.exitCheck();
+ return Objects.equals(input, "N");
+ }
+} | Java | 좋은 것 같습니다!! |
@@ -0,0 +1,21 @@
+package io;
+
+import camp.nextstep.edu.missionutils.Console;
+import validation.InputValidation;
+import view.OutputView;
+
+public final class Input {
+ public static String inputMessage() {
+ return Console.readLine();
+ }
+
+ public static String inputYOrN() {
+ while(true) {
+ try {
+ return InputValidation.isYorN(inputMessage());
+ } catch (IllegalArgumentException error){
+ OutputView.outputErrorMessage(error);
+ }
+ }
+ }
+} | Java | 이 Input 클래스의 inputMessage함수는 Console.readLine() 받아오는 부분을 유지보수성 높이고 싶어서 만들었습니다.
inputYOrN 함수는 많이 사용되는 함수라서 InputView클래스 보다는 Input에 선언해서 더 가독성을 높이고 싶어서 나누어서 개발했습니다.
InputView에 Console.readLine()을 사용하지 않고 Input에 개발함으로써 나중에 검증 코드나 다른 코드의 추가가 있을때 한번에 변환할 수 있어서 좋다고 생각합니다.
Input은 사용자 입력 처리 역할
InputView는 사용자와의 인터페이스 역할 |
@@ -0,0 +1,35 @@
+package controller;
+
+import java.util.Objects;
+import model.Orders;
+import model.Receipts;
+import view.InputView;
+import view.OutputView;
+
+public final class ApplicationController {
+ public void run() {
+ LoadDataController.loadData();
+ do {
+ runTurn();
+ } while (!exitCheck());
+ }
+
+ public void runTurn() {
+ clear();
+ OutputView.outputInventory();
+ OrderController.order();
+ PurchaseController.purchaseExec();
+ MembershipController.membership();
+ OutputView.outputReceipts(Receipts.getPurchases());
+ }
+
+ public static void clear() {
+ Orders.clearOrders();
+ Receipts.clear();
+ }
+
+ public boolean exitCheck() {
+ String input = InputView.exitCheck();
+ return Objects.equals(input, "N");
+ }
+} | Java | `retryCheck`로 네이밍하고, 입력이 `Y`인지 확인한다면, Not 연산자는 사용하지 않을 수 있을 것 같아요! 아니면 메서드 내에서 Not 연산자를 적용해서 반환하면 좋을 것 같아요 |
@@ -0,0 +1,24 @@
+package controller;
+
+import java.util.Objects;
+import model.Membership;
+import model.Receipts;
+import view.InputView;
+
+public final class MembershipController {
+ public static final int MAX_LIMIT = 8000;
+
+ public static void membership() {
+ String input = InputView.membershipDiscount();
+ if (Objects.equals(input, "Y")){
+ Membership.setMembershipDiscount(membershipCalculate());
+ return;
+ }
+ Membership.setMembershipDiscount(0);
+ }
+
+ public static int membershipCalculate() {
+ int discountPrice = (Receipts.membershipDiscountEligiblePrice() * 30) / 100;
+ return Math.min(discountPrice, MAX_LIMIT);
+ }
+} | Java | `30`은 멤버십 계산에서 핵심 내용이니 상수 처리하면 어떨까요? |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | `forEach`문을 사용하지 않고 for문을 직접 작성하신 이유가 있나요?
`forEach`문을 작성하면 한 줄로 줄일 수 있을 것 같아요! |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | else 사용을 지향하는 것이 좋습니다!
이 경우는 호출되는 메서드가 다르기 때문에 다음과 같이 작성할 수 있을 것 같아요.
```
//...
if (product.getPromotion() != null) {
purchasePromotion(product, order);
return;
}
processPurchase(product, order.purchaseCount(), 0, 0);
}
``` |
@@ -0,0 +1,20 @@
+package message;
+
+public enum IOMessage {
+ INVENTORY_STATUS_MESSAGE("안녕하세요. W편의점입니다.\n현재 보유하고 있는 상품입니다.\n"),
+ ORDER_MESSAGE("구매하실 상품명과 수량을 입력해 주세요. (예: [사이다-2],[감자칩-1])"),
+ PARTIAL_PROMOTION_MESSAGE("현재 %s %d개는 프로모션 할인이 적용되지 않습니다. 그래도 구매하시겠습니까? (Y/N)"),
+ ADDITIONAL_PROMOTION_QUANTITY_MESSAGE("현재 %s은(는) 1개를 무료로 더 받을 수 있습니다. 추가하시겠습니까? (Y/N)"),
+ MEMBERSHIP_DISCOUNT_MESSAGE("멤버십 할인을 받으시겠습니까? (Y/N)"),
+ EXIT_CHECK_MESSAGE("감사합니다. 구매하고 싶은 다른 상품이 있나요? (Y/N)");
+
+ private final String ioMessage;
+
+ IOMessage(final String ioMessage) {
+ this.ioMessage = ioMessage;
+ }
+
+ public String getMessage() {
+ return ioMessage;
+ }
+}
\ No newline at end of file | Java | 기능에 따라 enum을 구분하셨군요 ! 추후에 관리하기 좋을 것 같네요 배워갑니다 👍 |
@@ -0,0 +1,32 @@
+package model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public final class Receipts {
+ private static final List<Purchase> receipts = new ArrayList<>();
+
+ private Receipts() {}
+
+ public static void clear() {
+ receipts.clear();
+ }
+
+ public static void add(Purchase purchase) {
+ receipts.add(purchase);
+ }
+
+ public static int membershipDiscountEligiblePrice() {
+ int price = 0;
+ for (Purchase purchase : receipts) {
+ int discountEligiblePrice = (purchase.price() * purchase.quantity())
+ - (purchase.promotionQuantity() * purchase.buyPlusGet() * purchase.price());
+ price += discountEligiblePrice;
+ }
+ return price;
+ }
+
+ public static List<Purchase> getPurchases() {
+ return receipts;
+ }
+}
\ No newline at end of file | Java | 해당 연산은 따로 메서드로 분리하면 어떨까요?
`purchase`를 받아 연산한 결과를 반환하면 좋을 것 같아요 |
@@ -0,0 +1,16 @@
+package config;
+
+public enum PathConfig {
+ PRODUCTS_FILE_PATH("src/main/resources/products.md"),
+ PROMOTIONS_FILE_PATH("src/main/resources/promotions.md");
+
+ private final String filePath;
+
+ PathConfig(final String filePath) {
+ this.filePath = filePath;
+ }
+
+ public final String getFilePath() {
+ return this.filePath;
+ }
+}
\ No newline at end of file | Java | 파일을 enum클래스로 만들어서 관리하는거 좋은거 같아요! |
@@ -0,0 +1,24 @@
+package controller;
+
+import java.util.Objects;
+import model.Membership;
+import model.Receipts;
+import view.InputView;
+
+public final class MembershipController {
+ public static final int MAX_LIMIT = 8000;
+
+ public static void membership() {
+ String input = InputView.membershipDiscount();
+ if (Objects.equals(input, "Y")){
+ Membership.setMembershipDiscount(membershipCalculate());
+ return;
+ }
+ Membership.setMembershipDiscount(0);
+ }
+
+ public static int membershipCalculate() {
+ int discountPrice = (Receipts.membershipDiscountEligiblePrice() * 30) / 100;
+ return Math.min(discountPrice, MAX_LIMIT);
+ }
+} | Java | 저도 잘은 모르지만 계산하는 로직은 컨트롤러에 있는것보다 다른 클래스로 분리하는게 컨트롤러 기능에 맞지 않을까 싶어서 적어봅니다..! |
@@ -0,0 +1,23 @@
+package controller;
+
+import validation.InputOrderValidation;
+import view.InputView;
+import view.OutputView;
+
+public final class OrderController {
+ public static void order() {
+ while (true) {
+ try {
+ orderInput();
+ return;
+ } catch (IllegalArgumentException error) {
+ OutputView.outputErrorMessage(error);
+ }
+ }
+ }
+
+ private static void orderInput() throws IllegalArgumentException {
+ String inputOrder = InputView.inputOrder();
+ InputOrderValidation.inputOrderValidation(inputOrder);
+ }
+} | Java | 무한반복을 돌리는것보다 횟수제한을 둔다던가 하는 방식이 코드 기능면이나 사용자 측면에서 더 좋을거같다는 피드백을 저도 받아서 적어봅니다! |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | 1이 증정상품인가요? 확장성을 고려해서 추후에는 증정상품이 1개 이상일때도 있을 수 있으니 buy나 get을 사용해서 표현하는 것도 좋을 거같다는 생각이 들어 적어봅니다! |
@@ -0,0 +1,35 @@
+package controller;
+
+import config.PathConfig;
+import dto.ProductDTO;
+import java.util.List;
+import model.Inventory;
+import model.Promotion;
+import model.Promotions;
+import util.FileUtil;
+import util.SplitUtil;
+
+public final class LoadDataController {
+ public static void loadData() {
+ promotionsData();
+ productsData();
+ }
+
+ public static void productsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PRODUCTS_FILE_PATH.getFilePath());
+ for(String content: fileContents) {
+ ProductDTO productDTO = SplitUtil.createProductDTOFromContent(content);
+ Inventory.productAdd(productDTO);
+ }
+ }
+
+ public static void promotionsData() {
+ List<String> fileContents = FileUtil.readFile(PathConfig.PROMOTIONS_FILE_PATH.getFilePath());
+ fileContents.stream()
+ .map(SplitUtil::createPromotionFromContent)
+ // 처음 promotions.promotion에 현재 기간에 행사 진행하는 것만 넣을 건지 다 넣을 건지 filter
+ .filter(promotion -> Promotion.currentPromotion(promotion.startTime(), promotion.endTime()))
+ .forEach(Promotions::add);
+ }
+}
+ | Java | loadPromotionsData 이렇게 말인가요? |
@@ -0,0 +1,24 @@
+package controller;
+
+import java.util.Objects;
+import model.Membership;
+import model.Receipts;
+import view.InputView;
+
+public final class MembershipController {
+ public static final int MAX_LIMIT = 8000;
+
+ public static void membership() {
+ String input = InputView.membershipDiscount();
+ if (Objects.equals(input, "Y")){
+ Membership.setMembershipDiscount(membershipCalculate());
+ return;
+ }
+ Membership.setMembershipDiscount(0);
+ }
+
+ public static int membershipCalculate() {
+ int discountPrice = (Receipts.membershipDiscountEligiblePrice() * 30) / 100;
+ return Math.min(discountPrice, MAX_LIMIT);
+ }
+} | Java | model.Membership 클래스로 옮겨도 좋을 것 같네요. |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | +1 부분을 get을 사용하면 확장성에 도움이 되겠네요. 감사합니다! |
@@ -0,0 +1,32 @@
+package model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public final class Receipts {
+ private static final List<Purchase> receipts = new ArrayList<>();
+
+ private Receipts() {}
+
+ public static void clear() {
+ receipts.clear();
+ }
+
+ public static void add(Purchase purchase) {
+ receipts.add(purchase);
+ }
+
+ public static int membershipDiscountEligiblePrice() {
+ int price = 0;
+ for (Purchase purchase : receipts) {
+ int discountEligiblePrice = (purchase.price() * purchase.quantity())
+ - (purchase.promotionQuantity() * purchase.buyPlusGet() * purchase.price());
+ price += discountEligiblePrice;
+ }
+ return price;
+ }
+
+ public static List<Purchase> getPurchases() {
+ return receipts;
+ }
+}
\ No newline at end of file | Java | 말씀하신대로 해당 연산을 Purchase 클래스로 분할하면 더 좋을 것 같네요 |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | 이 부분에서는 Promotion 상품을 구매한다면 purchasePromotion함수 실행 아니면 processPurchase 함수 실행이라 else를 사용하는 것이 더 깔끔해 보인다고 생각해서 else를 사용하였습니다.
하지만 확장성과 유지보수를 위해서는 여기서 사용하지 않는 것이 더 좋을 것 같네요. 감사합니다!! |
@@ -0,0 +1,24 @@
+package controller;
+
+import java.util.Objects;
+import model.Membership;
+import model.Receipts;
+import view.InputView;
+
+public final class MembershipController {
+ public static final int MAX_LIMIT = 8000;
+
+ public static void membership() {
+ String input = InputView.membershipDiscount();
+ if (Objects.equals(input, "Y")){
+ Membership.setMembershipDiscount(membershipCalculate());
+ return;
+ }
+ Membership.setMembershipDiscount(0);
+ }
+
+ public static int membershipCalculate() {
+ int discountPrice = (Receipts.membershipDiscountEligiblePrice() * 30) / 100;
+ return Math.min(discountPrice, MAX_LIMIT);
+ }
+} | Java | 상수 처리 하면 더 좋은 코드가 될 것 같아요~ 감사합니다. |
@@ -0,0 +1,94 @@
+package controller;
+
+import java.util.Objects;
+import model.Inventory;
+import model.Order;
+import model.Orders;
+import model.Product;
+import model.Purchase;
+import model.Receipts;
+import view.InputView;
+
+public final class PurchaseController {
+ public static void purchaseExec() {
+ for (Order order : Orders.getOrders()) {
+ purchaseProduct(order);
+ }
+ }
+
+ public static void purchaseProduct(final Order order) {
+ Product product = Inventory.getProduct(order.orderProductName());
+ if (product.getPromotion() != null) {
+ purchasePromotion(product, order);
+ } else {
+ processPurchase(product, order.purchaseCount(), 0, 0);
+ }
+ }
+
+ private static void purchasePromotion(final Product product, final Order order) {
+ if (order.purchaseCount() > product.getPromotionQuantity()) {
+ purchasePartialPromotion(product, order);
+ return;
+ }
+ purchaseAllPromotion(product, order);
+ }
+
+ private static void purchaseAllPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = order.purchaseCount() / buyPlusGet * buyPlusGet;
+ if (shouldOfferAdditionalPromotion(order, product, buyPlusGet)) {
+ handleAdditionalPromotionOption(product, order, buyPlusGet);
+ return;
+ }
+ processPurchase(product, 0, order.purchaseCount(), promotionGet / buyPlusGet);
+ }
+
+ private static boolean shouldOfferAdditionalPromotion(final Order order, final Product product,
+ final int buyPlusGet) {
+ return order.purchaseCount() % buyPlusGet == product.getPromotion().buy() &&
+ product.getPromotionQuantity() >= (order.purchaseCount() + 1);
+ }
+
+ private static void handleAdditionalPromotionOption(final Product product, final Order order,
+ final int buyPlusGet) {
+ String inputValue = InputView.additionalPromotionQuantity(product.getProductName());
+ int newQuantity = order.purchaseCount();
+ if (Objects.equals(inputValue, "Y")) {
+ newQuantity = order.purchaseCount() + 1;
+ }
+ processPurchase(product, 0, newQuantity, newQuantity / buyPlusGet);
+ }
+
+ private static void purchasePartialPromotion(final Product product, final Order order) {
+ int buyPlusGet = product.getPromotion().buyPlusGet();
+ int promotionGet = product.getPromotionQuantity() / buyPlusGet * buyPlusGet;
+ String inputValue = InputView.partialPromotion(product.getProductName(), order.purchaseCount() - promotionGet);
+ if (Objects.equals(inputValue, "Y")) {
+ yPartialPromotion(product, order, buyPlusGet);
+ return;
+ }
+ nPartialPromotion(product, buyPlusGet, promotionGet);
+ }
+
+ private static void yPartialPromotion(final Product product, final Order order, final int buyPlusGet) {
+ processPurchase(product, order.purchaseCount() - product.getPromotionQuantity(),
+ product.getPromotionQuantity(), product.getPromotionQuantity() / buyPlusGet);
+ }
+
+ private static void nPartialPromotion(final Product product, final int buyPlusGet, final int promotionGet) {
+ if (promotionGet != 0) {
+ processPurchase(product, 0, promotionGet, promotionGet / buyPlusGet);
+ }
+ }
+
+ private static void processPurchase(final Product product, final int quantity, final int promotionQuantity,
+ final int giftQuantity) {
+ product.purchaseProduct(quantity, promotionQuantity);
+ int buyPlusGet = 0;
+ if (product.getPromotion() != null) {
+ buyPlusGet = product.getPromotion().buyPlusGet();
+ }
+ Receipts.add(new Purchase(product.getProductName(), quantity + promotionQuantity,
+ giftQuantity, product.getPrice(), buyPlusGet));
+ }
+} | Java | 좋은 피드백 감사합니다. 여기에 forEach문을 사용할 생각을 못했습니다.
추후에는 forEach문을 적극적으로 사용하겠습니다. |
@@ -0,0 +1,67 @@
+package subway.controller;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import subway.command.Command;
+import subway.command.MainCommand;
+import subway.controller.handler.Handler;
+import subway.controller.handler.LineHandler;
+import subway.controller.handler.SectionHandler;
+import subway.controller.handler.StationHandler;
+import subway.controller.retryInputUtil.RetryInputUtil;
+import subway.dto.LineDto;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class SubwayController {
+ private final LineService lineService;
+ private final Map<MainCommand, Handler> commandHandlers;
+
+ public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) {
+ this.lineService = lineService;
+
+ this.commandHandlers = new HashMap<>();
+ this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService));
+ this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService));
+ this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService));
+ }
+
+ public void run() {
+ int state = 0;
+
+ while (state == 0) {
+ try {
+ OutputView.printMainMenu();
+ MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values());
+
+ state = mainLogic(mainCommand);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ }
+ }
+ }
+
+ private int mainLogic(MainCommand mainCommand) {
+ if (mainCommand == MainCommand.QUIT) {
+ return 1;
+ }
+
+ if (this.commandHandlers.containsKey(mainCommand)) {
+ this.commandHandlers.get(mainCommand).handle();
+ }
+ if (mainCommand == MainCommand.LINE_PRINT) {
+ printLineMap();
+ }
+
+ return 0;
+ }
+
+ private void printLineMap() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLineMap(lines);
+ }
+
+} | Java | c에서는 뒤늦게 bool이 들어와서 어쩔 수 없지만 자바에는 boolean이 있으니 boolean을 쓰는게 더 직관적인것 같습니당 |
@@ -0,0 +1,54 @@
+package subway.controller.handler;
+
+import java.util.List;
+import subway.command.Command;
+import subway.command.StationCommand;
+import subway.controller.retryInputUtil.StationRetryInput;
+import subway.dto.StationDto;
+import subway.dto.StationRegisterDto.StationRegisterInputDto;
+import subway.dto.StationRemoveDto.StationRemoveInputDto;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class StationHandler implements Handler {
+ private final StationService stationService;
+
+ public StationHandler(StationService stationService) {
+ this.stationService = stationService;
+ }
+
+ @Override
+ public void handle() {
+ OutputView.printStationManageMenu();
+ StationCommand stationCommand = Command.findCommand(StationRetryInput.getCommand(), StationCommand.values());
+
+ if (stationCommand == StationCommand.REGISTER) {
+ registerStation();
+ }
+ if (stationCommand == StationCommand.REMOVE) {
+ removeStation();
+ }
+ if (stationCommand == StationCommand.RETRIEVE) {
+ retrieveStation();
+ }
+ if (stationCommand == StationCommand.BACK) {
+ // nothing to do.
+ }
+ }
+
+ private void registerStation() {
+ String stationName = StationRetryInput.getStationName();
+ stationService.register(new StationRegisterInputDto(stationName));
+ }
+
+ private void removeStation() {
+ String stationName = StationRetryInput.getRemoveStationName();
+ stationService.remove(new StationRemoveInputDto(stationName));
+ OutputView.printStationRemovedMessage();
+ }
+
+ private void retrieveStation() {
+ List<StationDto> stations = stationService.retrieve().stations();
+ OutputView.printStations(stations);
+ }
+} | Java | 이부분을 지우고 상단의 if문 2개에 return을 넣으면 코드수를 줄일 수 있을 것 같네요! |
@@ -0,0 +1,52 @@
+package subway.config;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import subway.controller.SubwayController;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.utils.CsvReader;
+import subway.utils.LineParser;
+import subway.utils.StationParser;
+
+public class DependencyInjector {
+ public SubwayController createSubwayController() {
+ StationRepository stationRepository = new StationRepository();
+ LineRepository lineRepository = new LineRepository();
+
+ StationService stationService = new StationService(stationRepository);
+ SectionService sectionService = new SectionService(lineRepository, stationRepository);
+ LineService lineService = new LineService(lineRepository, stationRepository);
+
+ SubwayFileInitializer subwayFileInitializer = createSubwayFileInitializer(stationRepository, lineRepository,
+ stationService, sectionService);
+ subwayFileInitializer.init();
+
+ return new SubwayController(stationService, lineService, sectionService);
+ }
+
+ public SubwayFileInitializer createSubwayFileInitializer(StationRepository stationRepository,
+ LineRepository lineRepository,
+ StationService stationService,
+ SectionService sectionService) {
+ StationParser stationParser = new StationParser(
+ new CsvReader(this.createBufferedReader(Configuration.STATION_FILE_NAME.getString()),
+ false));
+ LineParser lineParser = new LineParser(
+ new CsvReader(this.createBufferedReader(Configuration.LINE_FILE_NAME.getString()), false));
+
+ return new SubwayFileInitializer(
+ stationParser, lineParser, stationRepository, lineRepository
+ );
+ }
+
+
+ private BufferedReader createBufferedReader(String fileName) {
+ return new BufferedReader(new InputStreamReader(
+ DependencyInjector.class.getClassLoader().getResourceAsStream(fileName)
+ ));
+ }
+} | Java | 이 메서드를 나눌 수 있지 않았나 싶습니다. 여기서 new로 새로 할당한 개체들을 싱글톤으로 만들었으면 어떨까요? |
@@ -0,0 +1,16 @@
+package subway.command;
+
+public interface Command {
+ static <T extends Command> T findCommand(String input, T[] commands) {
+ for (T command : commands) {
+ if (command.getCommand().equals(input)) {
+ return command;
+ }
+ }
+ throw new IllegalArgumentException("선택할 수 없는 기능입니다.");
+ }
+
+ String getCommand();
+
+ String getDescription();
+} | Java | 기능 선택을 인터페이스로 관리하는 방법도 있군요.
로직이 반복되는 것 같아 고민했는데 좋은 방법이네요!
이렇게 하면 controller에서 해당 static 메소드를 호출하면 되니 역할 분리도 챙길 수 있네요.
배워갑니다👍 |
@@ -0,0 +1,16 @@
+package subway.command;
+
+public interface Command {
+ static <T extends Command> T findCommand(String input, T[] commands) {
+ for (T command : commands) {
+ if (command.getCommand().equals(input)) {
+ return command;
+ }
+ }
+ throw new IllegalArgumentException("선택할 수 없는 기능입니다.");
+ }
+
+ String getCommand();
+
+ String getDescription();
+} | Java | 에러메세지를 따로 관리하지 않고 직접 작성하신 이유가 있으실까요? |
@@ -0,0 +1,27 @@
+package subway.command;
+
+public enum LineCommand implements Command {
+ REGISTER("1", "노선 등록"),
+ REMOVE("2", "노선 삭제"),
+ RETRIEVE("3", "노선 조회"),
+ BACK("B", "돌아가기");
+
+ private final String command;
+ private final String description;
+
+ LineCommand(String command, String description) {
+ this.command = command;
+ this.description = description;
+ }
+
+ @Override
+ public String getCommand() {
+ return command;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+} | Java | 저는 enum에서 "1", "2" 라는 선택지 번호(또는 문자)만 관리했었는데, 출력 문구까지 작성하는게 더 깔끔하네요. |
@@ -0,0 +1,24 @@
+package subway.config;
+
+public enum Configuration {
+ STATION_FILE_NAME("stations.md"),
+ LINE_FILE_NAME("lines.md"),
+ LINE_NAME_MIN_LENGTH(2),
+ STATION_NAME_MIN_LENGTH(2),
+ ORDER_MIN_NUMBER(1),
+ ;
+
+ private final Object value;
+
+ Configuration(Object value) {
+ this.value = value;
+ }
+
+ public int getInt() {
+ return (int) value;
+ }
+
+ public String getString() {
+ return (String) value;
+ }
+} | Java | '순서는 최소 1이어야 한다'인 것 같은데 맞을까요?
저는 설명 중에 구간에 대해 '역과 역 사이'라는 설명이 있어서 구간 등록 시 최소 2로 이해했었는데, 어떻게 생각하느냐에 따라 다를 수 있을 것 같아요.
아래는 제가 이해한 구간에 대한 예시입니다.
1호선 : ㅇㅇ역 - ㅁㅁ역 - ㅂㅂ역
- 구간 1 : ㅇㅇ역과 ㅁㅁ역 사이
- 구간 2 : ㅁㅁ역과 ㅂㅂ역 사이 |
@@ -0,0 +1,52 @@
+package subway.config;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import subway.controller.SubwayController;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.utils.CsvReader;
+import subway.utils.LineParser;
+import subway.utils.StationParser;
+
+public class DependencyInjector {
+ public SubwayController createSubwayController() {
+ StationRepository stationRepository = new StationRepository();
+ LineRepository lineRepository = new LineRepository();
+
+ StationService stationService = new StationService(stationRepository);
+ SectionService sectionService = new SectionService(lineRepository, stationRepository);
+ LineService lineService = new LineService(lineRepository, stationRepository);
+
+ SubwayFileInitializer subwayFileInitializer = createSubwayFileInitializer(stationRepository, lineRepository,
+ stationService, sectionService);
+ subwayFileInitializer.init();
+
+ return new SubwayController(stationService, lineService, sectionService);
+ }
+
+ public SubwayFileInitializer createSubwayFileInitializer(StationRepository stationRepository,
+ LineRepository lineRepository,
+ StationService stationService,
+ SectionService sectionService) {
+ StationParser stationParser = new StationParser(
+ new CsvReader(this.createBufferedReader(Configuration.STATION_FILE_NAME.getString()),
+ false));
+ LineParser lineParser = new LineParser(
+ new CsvReader(this.createBufferedReader(Configuration.LINE_FILE_NAME.getString()), false));
+
+ return new SubwayFileInitializer(
+ stationParser, lineParser, stationRepository, lineRepository
+ );
+ }
+
+
+ private BufferedReader createBufferedReader(String fileName) {
+ return new BufferedReader(new InputStreamReader(
+ DependencyInjector.class.getClassLoader().getResourceAsStream(fileName)
+ ));
+ }
+} | Java | BufferedReader를 이렇게 처리할 수도 있군요👍 |
@@ -0,0 +1,78 @@
+package subway.config;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ReaderException;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.utils.LineFieldsDto;
+import subway.utils.LineParser;
+import subway.utils.StationFieldsDto;
+import subway.utils.StationParser;
+
+public class SubwayFileInitializer {
+ private final StationParser stationParser;
+ private final LineParser lineParser;
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public SubwayFileInitializer(StationParser stationParser, LineParser lineParser,
+ StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationParser = stationParser;
+ this.lineParser = lineParser;
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public void init() {
+ try {
+ initStations();
+ initLines();
+ } catch (IOException e) {
+ throw new ReaderException();
+ } catch (IllegalArgumentException error) {
+ throw new IllegalArgumentException(error.getMessage());
+ }
+ }
+
+ private void initStations() throws IOException {
+ while (true) {
+ StationFieldsDto stationFieldsDto = stationParser.nextStation();
+ if (stationFieldsDto == null) {
+ break;
+ }
+
+ stationRepository.add(new Station(stationFieldsDto.stationName()));
+ }
+ }
+
+ private void initLines() throws IOException {
+ while (true) {
+ LineFieldsDto lineFieldsDto = lineParser.nextLine();
+ if (lineFieldsDto == null) {
+ break;
+ }
+
+ List<Station> stations = new ArrayList<>();
+ for (String stationName : lineFieldsDto.stationNames()) {
+ Station station = stationRepository.findByName(stationName);
+ if (station == null) {
+ throw new IllegalArgumentException();
+ }
+
+ stations.add(station);
+ }
+
+ Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast());
+ lineRepository.add(line);
+ for (int i = 1; i < stations.size() - 1; i++) {
+ Station station = stations.get(i);
+ lineRepository.addStation(line, station, i);
+ }
+ }
+ }
+
+} | Java | 해당 메소드의 길이가 15 이상인 것 같습니다!
미션의 프로그래밍 요구사항 중 메소드 길이가 15 이하여야 한다는 조건이 있었습니당 |
@@ -0,0 +1,67 @@
+package subway.controller;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import subway.command.Command;
+import subway.command.MainCommand;
+import subway.controller.handler.Handler;
+import subway.controller.handler.LineHandler;
+import subway.controller.handler.SectionHandler;
+import subway.controller.handler.StationHandler;
+import subway.controller.retryInputUtil.RetryInputUtil;
+import subway.dto.LineDto;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class SubwayController {
+ private final LineService lineService;
+ private final Map<MainCommand, Handler> commandHandlers;
+
+ public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) {
+ this.lineService = lineService;
+
+ this.commandHandlers = new HashMap<>();
+ this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService));
+ this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService));
+ this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService));
+ }
+
+ public void run() {
+ int state = 0;
+
+ while (state == 0) {
+ try {
+ OutputView.printMainMenu();
+ MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values());
+
+ state = mainLogic(mainCommand);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ }
+ }
+ }
+
+ private int mainLogic(MainCommand mainCommand) {
+ if (mainCommand == MainCommand.QUIT) {
+ return 1;
+ }
+
+ if (this.commandHandlers.containsKey(mainCommand)) {
+ this.commandHandlers.get(mainCommand).handle();
+ }
+ if (mainCommand == MainCommand.LINE_PRINT) {
+ printLineMap();
+ }
+
+ return 0;
+ }
+
+ private void printLineMap() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLineMap(lines);
+ }
+
+} | Java | 깔끔한 구조네요👍 |
@@ -0,0 +1,67 @@
+package subway.controller;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import subway.command.Command;
+import subway.command.MainCommand;
+import subway.controller.handler.Handler;
+import subway.controller.handler.LineHandler;
+import subway.controller.handler.SectionHandler;
+import subway.controller.handler.StationHandler;
+import subway.controller.retryInputUtil.RetryInputUtil;
+import subway.dto.LineDto;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class SubwayController {
+ private final LineService lineService;
+ private final Map<MainCommand, Handler> commandHandlers;
+
+ public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) {
+ this.lineService = lineService;
+
+ this.commandHandlers = new HashMap<>();
+ this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService));
+ this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService));
+ this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService));
+ }
+
+ public void run() {
+ int state = 0;
+
+ while (state == 0) {
+ try {
+ OutputView.printMainMenu();
+ MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values());
+
+ state = mainLogic(mainCommand);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ }
+ }
+ }
+
+ private int mainLogic(MainCommand mainCommand) {
+ if (mainCommand == MainCommand.QUIT) {
+ return 1;
+ }
+
+ if (this.commandHandlers.containsKey(mainCommand)) {
+ this.commandHandlers.get(mainCommand).handle();
+ }
+ if (mainCommand == MainCommand.LINE_PRINT) {
+ printLineMap();
+ }
+
+ return 0;
+ }
+
+ private void printLineMap() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLineMap(lines);
+ }
+
+} | Java | 확실히 boolean이 메모리 절약이 될 것 같습니다 |
@@ -0,0 +1,67 @@
+package subway.controller;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import subway.command.Command;
+import subway.command.MainCommand;
+import subway.controller.handler.Handler;
+import subway.controller.handler.LineHandler;
+import subway.controller.handler.SectionHandler;
+import subway.controller.handler.StationHandler;
+import subway.controller.retryInputUtil.RetryInputUtil;
+import subway.dto.LineDto;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class SubwayController {
+ private final LineService lineService;
+ private final Map<MainCommand, Handler> commandHandlers;
+
+ public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) {
+ this.lineService = lineService;
+
+ this.commandHandlers = new HashMap<>();
+ this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService));
+ this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService));
+ this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService));
+ }
+
+ public void run() {
+ int state = 0;
+
+ while (state == 0) {
+ try {
+ OutputView.printMainMenu();
+ MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values());
+
+ state = mainLogic(mainCommand);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ }
+ }
+ }
+
+ private int mainLogic(MainCommand mainCommand) {
+ if (mainCommand == MainCommand.QUIT) {
+ return 1;
+ }
+
+ if (this.commandHandlers.containsKey(mainCommand)) {
+ this.commandHandlers.get(mainCommand).handle();
+ }
+ if (mainCommand == MainCommand.LINE_PRINT) {
+ printLineMap();
+ }
+
+ return 0;
+ }
+
+ private void printLineMap() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLineMap(lines);
+ }
+
+} | Java | 말씀해주신 내용이 이렇게 처리하는 것이었군요! |
@@ -0,0 +1,67 @@
+package subway.controller;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import subway.command.Command;
+import subway.command.MainCommand;
+import subway.controller.handler.Handler;
+import subway.controller.handler.LineHandler;
+import subway.controller.handler.SectionHandler;
+import subway.controller.handler.StationHandler;
+import subway.controller.retryInputUtil.RetryInputUtil;
+import subway.dto.LineDto;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class SubwayController {
+ private final LineService lineService;
+ private final Map<MainCommand, Handler> commandHandlers;
+
+ public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) {
+ this.lineService = lineService;
+
+ this.commandHandlers = new HashMap<>();
+ this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService));
+ this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService));
+ this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService));
+ }
+
+ public void run() {
+ int state = 0;
+
+ while (state == 0) {
+ try {
+ OutputView.printMainMenu();
+ MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values());
+
+ state = mainLogic(mainCommand);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ }
+ }
+ }
+
+ private int mainLogic(MainCommand mainCommand) {
+ if (mainCommand == MainCommand.QUIT) {
+ return 1;
+ }
+
+ if (this.commandHandlers.containsKey(mainCommand)) {
+ this.commandHandlers.get(mainCommand).handle();
+ }
+ if (mainCommand == MainCommand.LINE_PRINT) {
+ printLineMap();
+ }
+
+ return 0;
+ }
+
+ private void printLineMap() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLineMap(lines);
+ }
+
+} | Java | Handler를 사용하니 controller의 역할이 분리되어 좋아보입니당 |
@@ -0,0 +1,57 @@
+package subway.controller.handler;
+
+import java.util.List;
+import subway.command.Command;
+import subway.command.LineCommand;
+import subway.controller.retryInputUtil.LineRetryInput;
+import subway.dto.LineDto;
+import subway.dto.LineRegisterDto.LineRegisterInputDto;
+import subway.dto.LineRemoveDto.LineRemoveInputDto;
+import subway.service.LineService;
+import subway.view.OutputView;
+
+public class LineHandler implements Handler {
+ private final LineService lineService;
+
+ public LineHandler(LineService lineService) {
+ this.lineService = lineService;
+ }
+
+ @Override
+ public void handle() {
+ OutputView.printLineManageMenu();
+ LineCommand lineCommand = Command.findCommand(LineRetryInput.getCommand(), LineCommand.values());
+
+ if (lineCommand == LineCommand.REGISTER) {
+ registerLine();
+ }
+ if (lineCommand == LineCommand.REMOVE) {
+ removeLine();
+ }
+ if (lineCommand == LineCommand.RETRIEVE) {
+ retrieveLine();
+ }
+ if (lineCommand == LineCommand.BACK) {
+ // nothing to do.
+ }
+
+ }
+
+ private void registerLine() {
+ String lineName = LineRetryInput.getRegisterLineName();
+ String startStationName = LineRetryInput.getRegisterLineStartStationName();
+ String endStationName = LineRetryInput.getRegisterLineEndStationName();
+ lineService.register(new LineRegisterInputDto(lineName, startStationName, endStationName));
+ }
+
+ private void removeLine() {
+ String lineName = LineRetryInput.getRemoveLineName();
+ lineService.remove(new LineRemoveInputDto(lineName));
+ OutputView.printLineRemovedMessage();
+ }
+
+ private void retrieveLine() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLines(lines);
+ }
+} | Java | view의 메소드들을 static으로 처리하면, 의존하지 않아도 되니 제가 고민하던 부분이 풀리는군요. |
@@ -0,0 +1,30 @@
+package subway.controller.retryInputUtil;
+
+import subway.command.Command;
+import subway.command.LineCommand;
+import subway.validator.InputValidator;
+import subway.view.InputView;
+import subway.view.LineInputView;
+
+public class LineRetryInput {
+
+ public static String getCommand() {
+ return RetryInputUtil.retryLogics(InputView::getCommand, (input) -> Command.findCommand(input, LineCommand.values()));
+ }
+
+ public static String getRegisterLineName() {
+ return RetryInputUtil.retryLogics(LineInputView::getRegisterLineName, InputValidator::nullValidate);
+ }
+
+ public static String getRegisterLineStartStationName() {
+ return RetryInputUtil.retryLogics(LineInputView::getRegisterLineStartStationName, InputValidator::nullValidate);
+ }
+
+ public static String getRegisterLineEndStationName() {
+ return RetryInputUtil.retryLogics(LineInputView::getRegisterLineEndStationName, InputValidator::nullValidate);
+ }
+
+ public static String getRemoveLineName() {
+ return RetryInputUtil.retryLogics(LineInputView::getRemoveLineName, InputValidator::nullValidate);
+ }
+} | Java | 공백을 추가하면 가독성이 더 좋을 것 같습니당 |
@@ -1,15 +1,45 @@
package subway.domain;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import subway.validator.LineValidator;
+
public class Line {
private String name;
+ private List<Station> stations;
- public Line(String name) {
+ public Line(String name, Station startStation, Station endStation) {
+ LineValidator.validate(name, startStation, endStation);
this.name = name;
+ this.stations = new ArrayList<>(List.of(startStation, endStation));
+ }
+
+ public void addStation(Station station) {
+ stations.add(station);
+ }
+
+ public void addStation(Station station, int index) {
+ stations.add(index, station);
+ }
+
+ public void removeStation(Station station) {
+ stations.remove(station);
+ }
+
+ public List<Station> getStations() {
+ return stations;
+ }
+
+ public int getStationCount() {
+ return stations.size();
+ }
+
+ public List<String> getStationNames() {
+ return stations.stream().map(Station::getName).collect(Collectors.toList());
}
public String getName() {
return name;
}
-
- // 추가 기능 구현
} | Java | 저는 객체의 불변성을 위해 등록이나 삭제 등이 일어날 경우 기존 객체를 대체할 새로운 객체를 생성하는 식으로 구현했습니다.
또, getStations()가 리스트를 복사하지 않고 그대로 반환하고 있는 것 같습니다!
unmodifiableList에 대해 알아보시면 좋을 것 같아요! |
@@ -0,0 +1,27 @@
+package subway.command;
+
+public enum LineCommand implements Command {
+ REGISTER("1", "노선 등록"),
+ REMOVE("2", "노선 삭제"),
+ RETRIEVE("3", "노선 조회"),
+ BACK("B", "돌아가기");
+
+ private final String command;
+ private final String description;
+
+ LineCommand(String command, String description) {
+ this.command = command;
+ this.description = description;
+ }
+
+ @Override
+ public String getCommand() {
+ return command;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+} | Java | view 객체의 출력을 확인해보니 여기서 생성한 문자열을 그대로 받아서 출력하고 있는 것 같습니다. 그렇다면 도메인이 UI 생성 로직에도 관여하고 있는 설계가 아닐까요? |
@@ -0,0 +1,78 @@
+package subway.config;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ReaderException;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.utils.LineFieldsDto;
+import subway.utils.LineParser;
+import subway.utils.StationFieldsDto;
+import subway.utils.StationParser;
+
+public class SubwayFileInitializer {
+ private final StationParser stationParser;
+ private final LineParser lineParser;
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public SubwayFileInitializer(StationParser stationParser, LineParser lineParser,
+ StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationParser = stationParser;
+ this.lineParser = lineParser;
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public void init() {
+ try {
+ initStations();
+ initLines();
+ } catch (IOException e) {
+ throw new ReaderException();
+ } catch (IllegalArgumentException error) {
+ throw new IllegalArgumentException(error.getMessage());
+ }
+ }
+
+ private void initStations() throws IOException {
+ while (true) {
+ StationFieldsDto stationFieldsDto = stationParser.nextStation();
+ if (stationFieldsDto == null) {
+ break;
+ }
+
+ stationRepository.add(new Station(stationFieldsDto.stationName()));
+ }
+ }
+
+ private void initLines() throws IOException {
+ while (true) {
+ LineFieldsDto lineFieldsDto = lineParser.nextLine();
+ if (lineFieldsDto == null) {
+ break;
+ }
+
+ List<Station> stations = new ArrayList<>();
+ for (String stationName : lineFieldsDto.stationNames()) {
+ Station station = stationRepository.findByName(stationName);
+ if (station == null) {
+ throw new IllegalArgumentException();
+ }
+
+ stations.add(station);
+ }
+
+ Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast());
+ lineRepository.add(line);
+ for (int i = 1; i < stations.size() - 1; i++) {
+ Station station = stations.get(i);
+ lineRepository.addStation(line, station, i);
+ }
+ }
+ }
+
+} | Java | 다시 새로운 예외를 던지기 보다는 `throw error` 이런식으로 기존 예외를 그대로 넘기는 것이 어떨까요? |
@@ -0,0 +1,78 @@
+package subway.config;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ReaderException;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.utils.LineFieldsDto;
+import subway.utils.LineParser;
+import subway.utils.StationFieldsDto;
+import subway.utils.StationParser;
+
+public class SubwayFileInitializer {
+ private final StationParser stationParser;
+ private final LineParser lineParser;
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public SubwayFileInitializer(StationParser stationParser, LineParser lineParser,
+ StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationParser = stationParser;
+ this.lineParser = lineParser;
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public void init() {
+ try {
+ initStations();
+ initLines();
+ } catch (IOException e) {
+ throw new ReaderException();
+ } catch (IllegalArgumentException error) {
+ throw new IllegalArgumentException(error.getMessage());
+ }
+ }
+
+ private void initStations() throws IOException {
+ while (true) {
+ StationFieldsDto stationFieldsDto = stationParser.nextStation();
+ if (stationFieldsDto == null) {
+ break;
+ }
+
+ stationRepository.add(new Station(stationFieldsDto.stationName()));
+ }
+ }
+
+ private void initLines() throws IOException {
+ while (true) {
+ LineFieldsDto lineFieldsDto = lineParser.nextLine();
+ if (lineFieldsDto == null) {
+ break;
+ }
+
+ List<Station> stations = new ArrayList<>();
+ for (String stationName : lineFieldsDto.stationNames()) {
+ Station station = stationRepository.findByName(stationName);
+ if (station == null) {
+ throw new IllegalArgumentException();
+ }
+
+ stations.add(station);
+ }
+
+ Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast());
+ lineRepository.add(line);
+ for (int i = 1; i < stations.size() - 1; i++) {
+ Station station = stations.get(i);
+ lineRepository.addStation(line, station, i);
+ }
+ }
+ }
+
+} | Java | Optional을 이용한다면 가독성이 더 좋아질 것 같습니다! |
@@ -0,0 +1,78 @@
+package subway.config;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import subway.domain.Line;
+import subway.domain.Station;
+import subway.exception.ReaderException;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.utils.LineFieldsDto;
+import subway.utils.LineParser;
+import subway.utils.StationFieldsDto;
+import subway.utils.StationParser;
+
+public class SubwayFileInitializer {
+ private final StationParser stationParser;
+ private final LineParser lineParser;
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public SubwayFileInitializer(StationParser stationParser, LineParser lineParser,
+ StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationParser = stationParser;
+ this.lineParser = lineParser;
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public void init() {
+ try {
+ initStations();
+ initLines();
+ } catch (IOException e) {
+ throw new ReaderException();
+ } catch (IllegalArgumentException error) {
+ throw new IllegalArgumentException(error.getMessage());
+ }
+ }
+
+ private void initStations() throws IOException {
+ while (true) {
+ StationFieldsDto stationFieldsDto = stationParser.nextStation();
+ if (stationFieldsDto == null) {
+ break;
+ }
+
+ stationRepository.add(new Station(stationFieldsDto.stationName()));
+ }
+ }
+
+ private void initLines() throws IOException {
+ while (true) {
+ LineFieldsDto lineFieldsDto = lineParser.nextLine();
+ if (lineFieldsDto == null) {
+ break;
+ }
+
+ List<Station> stations = new ArrayList<>();
+ for (String stationName : lineFieldsDto.stationNames()) {
+ Station station = stationRepository.findByName(stationName);
+ if (station == null) {
+ throw new IllegalArgumentException();
+ }
+
+ stations.add(station);
+ }
+
+ Line line = new Line(lineFieldsDto.lineName(), stations.getFirst(), stations.getLast());
+ lineRepository.add(line);
+ for (int i = 1; i < stations.size() - 1; i++) {
+ Station station = stations.get(i);
+ lineRepository.addStation(line, station, i);
+ }
+ }
+ }
+
+} | Java | Stream을 이용하여 indent를 줄여보는 것은 어떨까요? |
@@ -0,0 +1,49 @@
+package subway.controller.handler;
+
+import subway.command.Command;
+import subway.command.SectionCommand;
+import subway.controller.retryInputUtil.SectionRetryInput;
+import subway.dto.SectionRegisterDto.SectionRegisterInputDto;
+import subway.dto.SectionRemoveDto.SectionRemoveInputDto;
+import subway.service.SectionService;
+import subway.view.OutputView;
+
+public class SectionHandler implements Handler {
+ private final SectionService sectionService;
+
+ public SectionHandler(SectionService sectionService) {
+ this.sectionService = sectionService;
+ }
+
+ @Override
+ public void handle() {
+ OutputView.printSectionManageMenu();
+ SectionCommand sectionCommand = Command.findCommand(SectionRetryInput.getCommand(),
+ SectionCommand.values());
+
+ if (sectionCommand == SectionCommand.REGISTER) {
+ registerSection();
+ }
+ if (sectionCommand == SectionCommand.REMOVE) {
+ removeSection();
+ }
+ if (sectionCommand == SectionCommand.BACK) {
+ // nothing to do.
+ }
+
+ }
+
+ private void registerSection() {
+ String lineName = SectionRetryInput.getLineName();
+ String stationName = SectionRetryInput.getStationName();
+ int orderNumber = SectionRetryInput.getOrderNumber();
+ sectionService.register(new SectionRegisterInputDto(lineName, stationName, orderNumber));
+ }
+
+ private void removeSection() {
+ String lineName = SectionRetryInput.getRemoveLineName();
+ String stationName = SectionRetryInput.getRemoveStationName();
+ sectionService.remove(new SectionRemoveInputDto(lineName, stationName));
+ OutputView.printSectionRemovedMessage();
+ }
+} | Java | 이 조건문을 굳이 작성하신 이유가 있을까요? 저는 BACK일 경우, 아무 기능도 수행하지 않기 때문에 따로 조건문으로 분리하지 않았기 때문에 궁금합니다. |
@@ -1,15 +1,45 @@
package subway.domain;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import subway.validator.LineValidator;
+
public class Line {
private String name;
+ private List<Station> stations;
- public Line(String name) {
+ public Line(String name, Station startStation, Station endStation) {
+ LineValidator.validate(name, startStation, endStation);
this.name = name;
+ this.stations = new ArrayList<>(List.of(startStation, endStation));
+ }
+
+ public void addStation(Station station) {
+ stations.add(station);
+ }
+
+ public void addStation(Station station, int index) {
+ stations.add(index, station);
+ }
+
+ public void removeStation(Station station) {
+ stations.remove(station);
+ }
+
+ public List<Station> getStations() {
+ return stations;
+ }
+
+ public int getStationCount() {
+ return stations.size();
+ }
+
+ public List<String> getStationNames() {
+ return stations.stream().map(Station::getName).collect(Collectors.toList());
}
public String getName() {
return name;
}
-
- // 추가 기능 구현
} | Java | 불변 리스트로 반환하는 것이 어떨까요? |
@@ -0,0 +1,67 @@
+package subway.controller;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import subway.command.Command;
+import subway.command.MainCommand;
+import subway.controller.handler.Handler;
+import subway.controller.handler.LineHandler;
+import subway.controller.handler.SectionHandler;
+import subway.controller.handler.StationHandler;
+import subway.controller.retryInputUtil.RetryInputUtil;
+import subway.dto.LineDto;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class SubwayController {
+ private final LineService lineService;
+ private final Map<MainCommand, Handler> commandHandlers;
+
+ public SubwayController(StationService stationService, LineService lineService, SectionService sectionService) {
+ this.lineService = lineService;
+
+ this.commandHandlers = new HashMap<>();
+ this.commandHandlers.put(MainCommand.STATION, new StationHandler(stationService));
+ this.commandHandlers.put(MainCommand.LINE, new LineHandler(lineService));
+ this.commandHandlers.put(MainCommand.SECTION, new SectionHandler(sectionService));
+ }
+
+ public void run() {
+ int state = 0;
+
+ while (state == 0) {
+ try {
+ OutputView.printMainMenu();
+ MainCommand mainCommand = Command.findCommand(RetryInputUtil.getMainCommand(), MainCommand.values());
+
+ state = mainLogic(mainCommand);
+ } catch (IllegalArgumentException error) {
+ OutputView.printError(error.getMessage());
+ }
+ }
+ }
+
+ private int mainLogic(MainCommand mainCommand) {
+ if (mainCommand == MainCommand.QUIT) {
+ return 1;
+ }
+
+ if (this.commandHandlers.containsKey(mainCommand)) {
+ this.commandHandlers.get(mainCommand).handle();
+ }
+ if (mainCommand == MainCommand.LINE_PRINT) {
+ printLineMap();
+ }
+
+ return 0;
+ }
+
+ private void printLineMap() {
+ List<LineDto> lines = lineService.retrieve().lines();
+ OutputView.printLineMap(lines);
+ }
+
+} | Java | 피드백 감사합니다! C를 많이 해서 그런지 습관적으로 int를 사용했네요! boolean으로 해도 좋을 것 같습니다! |
@@ -0,0 +1,54 @@
+package subway.controller.handler;
+
+import java.util.List;
+import subway.command.Command;
+import subway.command.StationCommand;
+import subway.controller.retryInputUtil.StationRetryInput;
+import subway.dto.StationDto;
+import subway.dto.StationRegisterDto.StationRegisterInputDto;
+import subway.dto.StationRemoveDto.StationRemoveInputDto;
+import subway.service.StationService;
+import subway.view.OutputView;
+
+public class StationHandler implements Handler {
+ private final StationService stationService;
+
+ public StationHandler(StationService stationService) {
+ this.stationService = stationService;
+ }
+
+ @Override
+ public void handle() {
+ OutputView.printStationManageMenu();
+ StationCommand stationCommand = Command.findCommand(StationRetryInput.getCommand(), StationCommand.values());
+
+ if (stationCommand == StationCommand.REGISTER) {
+ registerStation();
+ }
+ if (stationCommand == StationCommand.REMOVE) {
+ removeStation();
+ }
+ if (stationCommand == StationCommand.RETRIEVE) {
+ retrieveStation();
+ }
+ if (stationCommand == StationCommand.BACK) {
+ // nothing to do.
+ }
+ }
+
+ private void registerStation() {
+ String stationName = StationRetryInput.getStationName();
+ stationService.register(new StationRegisterInputDto(stationName));
+ }
+
+ private void removeStation() {
+ String stationName = StationRetryInput.getRemoveStationName();
+ stationService.remove(new StationRemoveInputDto(stationName));
+ OutputView.printStationRemovedMessage();
+ }
+
+ private void retrieveStation() {
+ List<StationDto> stations = stationService.retrieve().stations();
+ OutputView.printStations(stations);
+ }
+} | Java | 리뷰 감사합니다. BACK부분은 처리하는 것이 없기 때문에 굳이 작성하지 않아도 흐름상 문제가 없습니다. 다만 아무런 처리를 하지 않더라도 "아무것도 처리하지 않는다"라는 메시지를 주고 싶었기 때문에 남겨두었습니다. 명시적으로 "BACK이라는 명령이 있는데 아무것도 처리하지 않고 종료할거야"라는 메시지를 주고 싶었습니다! |
@@ -0,0 +1,52 @@
+package subway.config;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import subway.controller.SubwayController;
+import subway.repository.LineRepository;
+import subway.repository.StationRepository;
+import subway.service.LineService;
+import subway.service.SectionService;
+import subway.service.StationService;
+import subway.utils.CsvReader;
+import subway.utils.LineParser;
+import subway.utils.StationParser;
+
+public class DependencyInjector {
+ public SubwayController createSubwayController() {
+ StationRepository stationRepository = new StationRepository();
+ LineRepository lineRepository = new LineRepository();
+
+ StationService stationService = new StationService(stationRepository);
+ SectionService sectionService = new SectionService(lineRepository, stationRepository);
+ LineService lineService = new LineService(lineRepository, stationRepository);
+
+ SubwayFileInitializer subwayFileInitializer = createSubwayFileInitializer(stationRepository, lineRepository,
+ stationService, sectionService);
+ subwayFileInitializer.init();
+
+ return new SubwayController(stationService, lineService, sectionService);
+ }
+
+ public SubwayFileInitializer createSubwayFileInitializer(StationRepository stationRepository,
+ LineRepository lineRepository,
+ StationService stationService,
+ SectionService sectionService) {
+ StationParser stationParser = new StationParser(
+ new CsvReader(this.createBufferedReader(Configuration.STATION_FILE_NAME.getString()),
+ false));
+ LineParser lineParser = new LineParser(
+ new CsvReader(this.createBufferedReader(Configuration.LINE_FILE_NAME.getString()), false));
+
+ return new SubwayFileInitializer(
+ stationParser, lineParser, stationRepository, lineRepository
+ );
+ }
+
+
+ private BufferedReader createBufferedReader(String fileName) {
+ return new BufferedReader(new InputStreamReader(
+ DependencyInjector.class.getClassLoader().getResourceAsStream(fileName)
+ ));
+ }
+} | Java | 싱글톤으로 만든다는게 static으로 선언하는 것을 말씀하시는건가요?? |
@@ -0,0 +1,16 @@
+package subway.command;
+
+public interface Command {
+ static <T extends Command> T findCommand(String input, T[] commands) {
+ for (T command : commands) {
+ if (command.getCommand().equals(input)) {
+ return command;
+ }
+ }
+ throw new IllegalArgumentException("선택할 수 없는 기능입니다.");
+ }
+
+ String getCommand();
+
+ String getDescription();
+} | Java | 이유는... 없습니다. 최대한 빠르게 개발하는 것을 목표로 해서 디테일한 부분은 가져가지 못한 것 같습니다 ㅠㅠ |
@@ -1,7 +1,65 @@
package store;
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Map;
+import store.constant.YesOrNo;
+import store.controller.PurchaseController;
+import store.dto.StockResponse;
+import store.entity.Product;
+import store.entity.Promotion;
+import store.entity.Stock;
+import store.service.CartService;
+import store.service.StockService;
+import store.util.parse.PromotionParser;
+import store.util.parse.ProductParser;
+import store.view.InputView;
+import store.view.OutputView;
+
public class Application {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+ private static final String FILE_ERROR_MESSAGE = ERROR_PREFIX + "파일을 읽는데 실패했습니다.";
+
public static void main(String[] args) {
- // TODO: 프로그램 구현
+ List<Product> items = getInitProducts();
+ Stock stock = new Stock(items);
+ StockService stockService = new StockService(stock);
+ initializeApplication(stock, stockService);
+ }
+
+ private static void initializeApplication(Stock stock, StockService stockService) {
+ YesOrNo continueShopping = YesOrNo.YES;
+ while (continueShopping == YesOrNo.YES) {
+ CartService cartService = new CartService(stock);
+ PurchaseController purchaseController = new PurchaseController(cartService, stockService);
+ List<StockResponse> stockResult = purchaseController.getStock();
+ OutputView.printStartMessage(stockResult);
+ purchaseController.purchase();
+ continueShopping = InputView.askForAdditionalPurchase();
+ }
+ }
+
+ private static List<Product> getInitProducts() {
+ List<String> products = readFile(PRODUCT_FILE_PATH);
+ List<String> promotions = readFile(PROMOTION_FILE_PATH);
+ Map<String, Promotion> parsePromotions = PromotionParser.parse(promotions);
+ List<Product> items = ProductParser.parse(products, parsePromotions);
+ return items;
+ }
+
+ private static List<String> readFile(String filePath) {
+ try {
+ Path path = Paths.get(filePath);
+ return Files.readAllLines(path);
+ } catch (IOException e) {
+ throw new UncheckedIOException(FILE_ERROR_MESSAGE, e);
+ }
}
} | Java | 여기서 추가구매에 대한 응답으로 'Y'를 입력하면 매 반복마다 CarService와 PurchaseController가 새로 생성되는 문제가
있을 것 같습니다. |
@@ -0,0 +1,5 @@
+package store.constant;
+
+public class Constant {
+ public static final String ERROR_PREFIX = "[ERROR] ";
+} | Java | `ERROR_PREFIX` 같이 반복되는 부분을 상수로 정의해주신게 좋은 것 같습니다. |
@@ -0,0 +1,7 @@
+package store.entity;
+
+import java.time.LocalDate;
+
+public interface DateProvider {
+ LocalDate now();
+} | Java | 날짜에 대한 정보를 제공해주는 인터페이스를 따로 생성하신 이유를 알 수 있을까요? |
@@ -0,0 +1,11 @@
+package store.entity;
+
+public class Membership {
+ private static final int discountPercent = 30;
+ private static final int maxDiscountAmount = 8000;
+
+ public int discount(Cart nonDiscountedCart) {
+ int discountAmount = nonDiscountedCart.getTotalPrice() * discountPercent / 100;
+ return Math.min(discountAmount, maxDiscountAmount);
+ }
+} | Java | `Math.min()`을 사용해서 할인최대치가 초과되지 않도록 깔끔하게 잘 구현해주신 것 같습니다. |
@@ -0,0 +1,57 @@
+package store.entity;
+
+import java.time.LocalDate;
+import java.util.Objects;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(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 boolean isPromotionValid(LocalDate currentDate) {
+ return !currentDate.isBefore(startDate) && !currentDate.isAfter(endDate);
+ }
+
+ public boolean isInsufficientPromotion(Integer value) {
+ return value % (buy + get) >= buy;
+ }
+
+ public Integer getInsufficientPromotionQuantity(Integer value) {
+ return (buy + get) - value % (buy + get);
+ }
+
+ public Integer getCycle() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Promotion promotion = (Promotion) o;
+ return buy == promotion.buy &&
+ get == promotion.get &&
+ Objects.equals(name, promotion.name) &&
+ Objects.equals(startDate, promotion.startDate) &&
+ Objects.equals(endDate, promotion.endDate);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, buy, get, startDate, endDate);
+ }
+} | Java | 개인적인 생각으로 앞에 !연산자가 들어가게 되면 코드를 읽는 도중 한번 더 생각을 하게 만드는 것 같습니다.
`currentDate.isAfter(startDate) && currentDate.isBefore(endDate);`과 같은 방법도 있을 것 같습니다! |
@@ -0,0 +1,61 @@
+package store.entity;
+
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.util.List;
+import java.util.Map;
+
+public class Stock {
+ private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "존재하지 않는 상품입니다. 다시 입력해 주세요.";
+ private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.";
+
+ private final List<Product> stock;
+
+ public Stock(List<Product> stock) {
+ this.stock = stock;
+ }
+
+ public Product findByName(String name) {
+ return stock.stream()
+ .filter(product -> product.getName().equals(name))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE));
+ }
+
+ public void validateAll(Map<String, Integer> items) {
+ items.forEach(this::validate);
+ }
+
+ public void update(Map<Product, Integer> cartItem) {
+ cartItem.forEach((product, quantity) -> {
+ Product stockProduct = findByName(product.getName());
+ if (product.isPromotionEligible()) {
+ stockProduct.reducePromotionQuantity(quantity);
+ } else {
+ stockProduct.reduceQuantity(quantity);
+ }
+ });
+ }
+
+ private void validate(String productName, Integer quantity) {
+ if (!isValidName(productName)) {
+ throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE);
+ }
+ if (!isStockAvailable(productName, quantity)) {
+ throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean isValidName(String name) {
+ return stock.stream().anyMatch(product -> product.getName().equals(name));
+ }
+
+ private boolean isStockAvailable(String productName, Integer quantity) {
+ Product product = findByName(productName);
+ return product.isStockAvailable(quantity);
+ }
+
+ public List<Product> getStock() {
+ return stock.stream().toList();
+ }
+} | Java | else문 사용은 가급적이면 지양해주시는 게 좋다고 들었습니다 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.