code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,84 @@ +import { Console } from '@woowacourse/mission-utils'; +import { PROMOTION_CATEGORIES } from '../constant/index.js'; + +const MESSAGE = { + GREETINGS: '안녕하세요! 우테코 식당 12월 이벤트 플래너입니다.', + INTRO_PREVIEW: '12월 26일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!\n', + ORDER_MENU_TITLE: '<주문 메뉴>', + TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE: '<할인 전 총주문 금액>', + BENEFIT_DETAILS_TITLE: '<혜택 내역>', + TOTAL_PRICE_WITH_DISCOUNT_TITLE: '<할인 후 예상 결제 금액>', + GIFT_TITLE: '<증정 메뉴>', + BENEFIT_TOTAL_PRICE_TITLE: '<총혜택 금액>', + BADGE_TITLE: '<12월 이벤트 배지>', + NONE: '없음', + MENU: (name, count) => `${name} ${count}개`, + PRICE: (price) => `${price.toLocaleString()}원`, + GIFT: (name, count) => `${name} ${count}개`, + DISCOUNT: (name, price) => `${name} 할인: -${price.toLocaleString()}원`, + TOTAL_BENEFIT_PRICE: (price) => (price > 0 ? `-${price.toLocaleString()}원` : '0원'), +}; + +const OutputView = { + printGreetings() { + Console.print(MESSAGE.GREETINGS); + }, + printPreviewMessage() { + Console.print(MESSAGE.INTRO_PREVIEW); + Console.print(''); + }, + printOrderMenus(orders) { + Console.print(MESSAGE.ORDER_MENU_TITLE); + + orders.forEach((order) => { + Console.print(MESSAGE.MENU(order.name, order.count)); + }); + + Console.print(''); + }, + printTotalPriceWithoutDiscount(totalPrice) { + Console.print(MESSAGE.TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPrice)); + Console.print(''); + }, + printBenefitDetails(promotions) { + Console.print(MESSAGE.BENEFIT_DETAILS_TITLE); + + const printData = []; + + promotions.forEach((promotion) => { + const { NAME, promotionBenefitPrice } = promotion; + const isApplied = promotionBenefitPrice > 0; + if (isApplied) printData.push(MESSAGE.DISCOUNT(NAME, promotionBenefitPrice)); + }); + if (printData.length === 0) printData.push(MESSAGE.NONE); + + Console.print(printData.join('\n')); + Console.print(''); + }, + printTotalPriceWithDiscount(totalPriceWithDiscount) { + Console.print(MESSAGE.TOTAL_PRICE_WITH_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPriceWithDiscount)); + Console.print(''); + }, + printGiveWayMenu(promotions) { + const giftMenu = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + const { PRODUCT, promotionBenefitPrice } = giftMenu; + const isApplied = promotionBenefitPrice > 0; + + Console.print(MESSAGE.GIFT_TITLE); + Console.print(isApplied ? MESSAGE.GIFT(PRODUCT.NAME, 1) : MESSAGE.NONE); + Console.print(''); + }, + printTotalBenefitPrice(totalBenefitPrice) { + Console.print(MESSAGE.BENEFIT_TOTAL_PRICE_TITLE); + Console.print(MESSAGE.TOTAL_BENEFIT_PRICE(totalBenefitPrice)); + Console.print(''); + }, + printBadge(badge) { + Console.print(MESSAGE.BADGE_TITLE); + Console.print(badge); + }, +}; + +export default OutputView;
JavaScript
으아 그러네요 ㅠㅠㅠ 생각지도 못했네요 ㅠㅠ
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
역할을 분리한다는 말씀이 어떤건지 잘 이해가 안되는데 혹시 어떤 말씀이신지 알려주실 수 있으실까요? getOrderDate는 Promotion에서 사용합니다
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
넵.... 제가 봐도 좀 가독성이 떨어지는 것 같네요
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
```js const validators = [ Order.validateDuplicationOrder.bind(this, orderMenus) // ... ] ``` 위와 같이 `bind` 사용도 고려해보면 좋을 것 같아요.
@@ -1,5 +1,42 @@ +import { InputView, OutputView } from './view/index.js'; +import { MENUS, PROMOTION_MONTH, PROMOTION_YEAR } from './constant/index.js'; +import { Order, Planner, PromotionCalendar, Promotions } from './model/index.js'; + class App { - async run() {} + async run() { + OutputView.printGreetings(); + const { order, planner } = await this.reserve(); + OutputView.printPreviewMessage(); + await this.preview(order, planner); + } + + async reserve() { + const orderDate = await InputView.readOrderDate((input) => Order.validateDate(input)); + const orderMenu = await InputView.readOrderMenus((input) => Order.validateOrder(input)); + const order = new Order(MENUS, orderMenu, orderDate); + const planner = new Planner(order, new PromotionCalendar(PROMOTION_YEAR, PROMOTION_MONTH, Promotions)); + + return { + order, + planner, + }; + } + + async preview(order, planner) { + const orderMenuList = order.getOrderMenuList(); + const totalPriceWithoutDiscount = order.getTotalPrice(); + const promotions = planner.getPromotionsByOrderDate(); + const totalBenefitPrice = planner.getTotalBenefitPrice(); + const totalPriceWithDiscount = planner.getTotalPriceWithDiscount(); + const badge = planner.getBadge(); + OutputView.printOrderMenus(orderMenuList); + OutputView.printTotalPriceWithoutDiscount(totalPriceWithoutDiscount); + OutputView.printGiveWayMenu(promotions); + OutputView.printBenefitDetails(promotions); + OutputView.printTotalBenefitPrice(totalBenefitPrice); + OutputView.printTotalPriceWithDiscount(totalPriceWithDiscount); + OutputView.printBadge(badge); + } } export default App;
JavaScript
아 맞네요 그게 더 좋을 것 같습니다 감사합니다
@@ -1,5 +1,42 @@ +import { InputView, OutputView } from './view/index.js'; +import { MENUS, PROMOTION_MONTH, PROMOTION_YEAR } from './constant/index.js'; +import { Order, Planner, PromotionCalendar, Promotions } from './model/index.js'; + class App { - async run() {} + async run() { + OutputView.printGreetings(); + const { order, planner } = await this.reserve(); + OutputView.printPreviewMessage(); + await this.preview(order, planner); + } + + async reserve() { + const orderDate = await InputView.readOrderDate((input) => Order.validateDate(input)); + const orderMenu = await InputView.readOrderMenus((input) => Order.validateOrder(input)); + const order = new Order(MENUS, orderMenu, orderDate); + const planner = new Planner(order, new PromotionCalendar(PROMOTION_YEAR, PROMOTION_MONTH, Promotions)); + + return { + order, + planner, + }; + } + + async preview(order, planner) { + const orderMenuList = order.getOrderMenuList(); + const totalPriceWithoutDiscount = order.getTotalPrice(); + const promotions = planner.getPromotionsByOrderDate(); + const totalBenefitPrice = planner.getTotalBenefitPrice(); + const totalPriceWithDiscount = planner.getTotalPriceWithDiscount(); + const badge = planner.getBadge(); + OutputView.printOrderMenus(orderMenuList); + OutputView.printTotalPriceWithoutDiscount(totalPriceWithoutDiscount); + OutputView.printGiveWayMenu(promotions); + OutputView.printBenefitDetails(promotions); + OutputView.printTotalBenefitPrice(totalBenefitPrice); + OutputView.printTotalPriceWithDiscount(totalPriceWithDiscount); + OutputView.printBadge(badge); + } } export default App;
JavaScript
진입점 코드에서 전체적인 흐름 파악이 어렵다는 생각이 듭니다. `printPreviewMessage()`, `this.preview` 함수들이 무슨 일을 하는지 잘 예상이 안 가요.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
아 추후 다른 메뉴를 넣을 때도 재사용성을 생각해서 따로 넣어놨습니다. Map을 사용한 이유는 저는 최대한 Object[Key] 로 사용을 자제 할려고 합니다 Map으로 만들면 get(),set()도 편하고 forEach나 다양한 함수도 한 번에 사용할 수 있어서 좀 더 좋은 것 같더라구요
@@ -0,0 +1,55 @@ +import { BADGE, PROMOTION_CATEGORIES, PROMOTION_MINIMUM_PRICE } from '../constant/index.js'; + +class Planner { + #order; + #calendar; + + constructor(order, calendar) { + this.#order = order; + this.#calendar = calendar; + } + + getPromotionsByOrderDate() { + const promotions = this.#calendar.getPromotionsByDate(this.#order.getOrderDate()); + const activePromotions = []; + promotions.forEach((promotion) => { + const { CONFIG } = promotion; + activePromotions.push({ + ...CONFIG, + promotionBenefitPrice: this.#applyPromotions(promotion), + }); + }); + + return activePromotions; + } + getTotalBenefitPrice() { + const promotions = this.getPromotionsByOrderDate(); + + return promotions.reduce((acc, cur) => acc + cur.promotionBenefitPrice, 0); + } + getTotalPriceWithDiscount() { + const promotions = this.getPromotionsByOrderDate(); + const totalPrice = this.#order.getTotalPrice(); + const getTotalBenefitPrice = this.getTotalBenefitPrice(); + const giftPromotion = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + + return totalPrice - (getTotalBenefitPrice - giftPromotion.promotionBenefitPrice); + } + getBadge() { + const { SANTA, TREE, STAR, NONE } = BADGE; + const totalBenefitPrice = this.getTotalBenefitPrice(); + if (totalBenefitPrice >= SANTA.PRICE) return SANTA.NAME; + if (totalBenefitPrice >= TREE.PRICE) return TREE.NAME; + if (totalBenefitPrice >= STAR.PRICE) return STAR.NAME; + + return NONE.NAME; + } + #applyPromotions(promotion) { + const totalPriceWithoutDiscount = this.#order.getTotalPrice(); + if (totalPriceWithoutDiscount < PROMOTION_MINIMUM_PRICE) return 0; + + return promotion.getPromotionPrice(this.#order); + } +} + +export default Planner;
JavaScript
Planner가 너무 많은 객체에 의존하는 것 같아요. 또, 어떤 객체인지 잘 파악이 안 돼요. Planner 라는 이름과, 메서드가 매칭이 잘 안되네요
@@ -0,0 +1,45 @@ +import { PROMOTIONS } from '../constant/index.js'; + +const ChristPromotion = { + CONFIG: PROMOTIONS.CHRISTMAS, + getPromotionPrice(order) { + const date = order.getOrderDate(); + + return this.CONFIG.BENEFIT_PRICE + this.CONFIG.BENEFIT_PRICE * 0.1 * (date - 1); + }, +}; +const WeekendsPromotion = { + CONFIG: PROMOTIONS.WEEKENDS, + getPromotionPrice(order) { + const productInOrder = order.getOrderMenuByCategory(this.CONFIG.PRODUCT); + const menuCount = productInOrder.reduce((acc, cur) => acc + Number(cur.count), 0); + + return this.CONFIG.BENEFIT_PRICE * menuCount; + }, +}; +const WeekdaysPromotion = { + CONFIG: PROMOTIONS.WEEKDAYS, + getPromotionPrice(order) { + const productInOrder = order.getOrderMenuByCategory(this.CONFIG.PRODUCT); + const menuCount = productInOrder.reduce((acc, cur) => acc + Number(cur.count), 0); + + return this.CONFIG.BENEFIT_PRICE * menuCount; + }, +}; +const SpecialPromotion = { + CONFIG: PROMOTIONS.SPECIAL, + getPromotionPrice() { + return this.CONFIG.BENEFIT_PRICE; + }, +}; +const GiftPromotion = { + CONFIG: PROMOTIONS.GIFT, + getPromotionPrice(order) { + const preDiscountAmount = order.getTotalPrice(); + if (preDiscountAmount < this.CONFIG.MINIMUM_PRICE) return 0; + + return this.CONFIG.BENEFIT_PRICE; + }, +}; +export const Promotions = [ChristPromotion, WeekendsPromotion, WeekdaysPromotion, SpecialPromotion, GiftPromotion]; +export default Promotions;
JavaScript
`CONFIG`가 뭘 뜻하는지 추측이 잘 안되네요. 마찬가지로 `PROMOTIONS.CHRISTMAS`에 뭐가 들어있는지 예상이 안가요. 상수들을 조금더 단순화하는게 필요하다고 생각합니다.
@@ -0,0 +1,13 @@ +const PREFIX_ERROR = '[ERROR]'; + +export const check = (errorMessage, validator) => { + if (validator()) throw new Error(`${PREFIX_ERROR} ${errorMessage}`); +}; +export const isMoreThanLimit = (errorMessage, target, limit) => check(errorMessage, () => target > limit); +export const isDuplicate = (errorMessage, targets) => + check(errorMessage, () => new Set(targets).size !== targets.length); +export const isNotMatchRegex = (errorMessage, target, regex) => check(errorMessage, () => !regex.test(target)); +export const isEveryInclude = (errorMessage, targets, references) => + check(errorMessage, () => targets.every((item) => references.includes(item))); +export const isSomeNotInclude = (errorMessage, targets, references) => + check(errorMessage, () => targets.some((item) => !references.includes(item)));
JavaScript
constant 폴더로 따로 분리하하지 않고 여기서 선언하신 이유가 있나요?
@@ -0,0 +1,84 @@ +import { Console } from '@woowacourse/mission-utils'; +import { PROMOTION_CATEGORIES } from '../constant/index.js'; + +const MESSAGE = { + GREETINGS: '안녕하세요! 우테코 식당 12월 이벤트 플래너입니다.', + INTRO_PREVIEW: '12월 26일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!\n', + ORDER_MENU_TITLE: '<주문 메뉴>', + TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE: '<할인 전 총주문 금액>', + BENEFIT_DETAILS_TITLE: '<혜택 내역>', + TOTAL_PRICE_WITH_DISCOUNT_TITLE: '<할인 후 예상 결제 금액>', + GIFT_TITLE: '<증정 메뉴>', + BENEFIT_TOTAL_PRICE_TITLE: '<총혜택 금액>', + BADGE_TITLE: '<12월 이벤트 배지>', + NONE: '없음', + MENU: (name, count) => `${name} ${count}개`, + PRICE: (price) => `${price.toLocaleString()}원`, + GIFT: (name, count) => `${name} ${count}개`, + DISCOUNT: (name, price) => `${name} 할인: -${price.toLocaleString()}원`, + TOTAL_BENEFIT_PRICE: (price) => (price > 0 ? `-${price.toLocaleString()}원` : '0원'), +}; + +const OutputView = { + printGreetings() { + Console.print(MESSAGE.GREETINGS); + }, + printPreviewMessage() { + Console.print(MESSAGE.INTRO_PREVIEW); + Console.print(''); + }, + printOrderMenus(orders) { + Console.print(MESSAGE.ORDER_MENU_TITLE); + + orders.forEach((order) => { + Console.print(MESSAGE.MENU(order.name, order.count)); + }); + + Console.print(''); + }, + printTotalPriceWithoutDiscount(totalPrice) { + Console.print(MESSAGE.TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPrice)); + Console.print(''); + }, + printBenefitDetails(promotions) { + Console.print(MESSAGE.BENEFIT_DETAILS_TITLE); + + const printData = []; + + promotions.forEach((promotion) => { + const { NAME, promotionBenefitPrice } = promotion; + const isApplied = promotionBenefitPrice > 0; + if (isApplied) printData.push(MESSAGE.DISCOUNT(NAME, promotionBenefitPrice)); + }); + if (printData.length === 0) printData.push(MESSAGE.NONE); + + Console.print(printData.join('\n')); + Console.print(''); + }, + printTotalPriceWithDiscount(totalPriceWithDiscount) { + Console.print(MESSAGE.TOTAL_PRICE_WITH_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPriceWithDiscount)); + Console.print(''); + }, + printGiveWayMenu(promotions) { + const giftMenu = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + const { PRODUCT, promotionBenefitPrice } = giftMenu; + const isApplied = promotionBenefitPrice > 0; + + Console.print(MESSAGE.GIFT_TITLE); + Console.print(isApplied ? MESSAGE.GIFT(PRODUCT.NAME, 1) : MESSAGE.NONE); + Console.print(''); + }, + printTotalBenefitPrice(totalBenefitPrice) { + Console.print(MESSAGE.BENEFIT_TOTAL_PRICE_TITLE); + Console.print(MESSAGE.TOTAL_BENEFIT_PRICE(totalBenefitPrice)); + Console.print(''); + }, + printBadge(badge) { + Console.print(MESSAGE.BADGE_TITLE); + Console.print(badge); + }, +}; + +export default OutputView;
JavaScript
airbnb 규칙에서 key값은 소문자로 하는것을 권장하고 있어요.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
ㅇㅏ~ static 메서드는 위로 빼놓아도 되는군요.. 처음 알았네요..!
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
저도 명확하게 설명드릴 수 있을지 모르겠는데, Order라는 도메인의 상태값으로 orderDate를 갖는데 Order 도메인 내부에서 사용되지 않고 Promotion에서만 사용된다면 Promotion 도메인에 필요한 값이지 않을까 생각이 들었어요.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
옛날에 bind를 사용했다가 최대한 "bind랑 apply는 사용하지 마라"라고 한 소리를 들어서.. 잘 사용안하게 되네요..이 부분은 bind로 사용하는게 깔끔할 것 같네요. 감사합니다
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
혹시 bind, apply 지양 이유가 뭔가요??
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
여기서는 객체 동결을 해주시는데 상수 객체는 동결을 안 하신 이유가 있으실까요? 저도 이 부분이 고민이라 여쭤봐요.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
구조분해할당을 잘 쓰시는 것 같아요! 배워갑니당
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
Object[Key] 사용을 자제하시려는 이유가 있으실까요?
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '유효하지 않은 날짜입니다. 다시 입력해 주세요.', + IS_INVALID_ORDER: '유효하지 않은 주문입니다. 다시 입력해 주세요.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
배열, Map, 객체의 여러가지 메서드들을 잘 활용하시는 것 같아요. 배워갑니다!
@@ -0,0 +1,55 @@ +import { BADGE, PROMOTION_CATEGORIES, PROMOTION_MINIMUM_PRICE } from '../constant/index.js'; + +class Planner { + #order; + #calendar; + + constructor(order, calendar) { + this.#order = order; + this.#calendar = calendar; + } + + getPromotionsByOrderDate() { + const promotions = this.#calendar.getPromotionsByDate(this.#order.getOrderDate()); + const activePromotions = []; + promotions.forEach((promotion) => { + const { CONFIG } = promotion; + activePromotions.push({ + ...CONFIG, + promotionBenefitPrice: this.#applyPromotions(promotion), + }); + }); + + return activePromotions; + } + getTotalBenefitPrice() { + const promotions = this.getPromotionsByOrderDate(); + + return promotions.reduce((acc, cur) => acc + cur.promotionBenefitPrice, 0); + } + getTotalPriceWithDiscount() { + const promotions = this.getPromotionsByOrderDate(); + const totalPrice = this.#order.getTotalPrice(); + const getTotalBenefitPrice = this.getTotalBenefitPrice(); + const giftPromotion = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + + return totalPrice - (getTotalBenefitPrice - giftPromotion.promotionBenefitPrice); + } + getBadge() { + const { SANTA, TREE, STAR, NONE } = BADGE; + const totalBenefitPrice = this.getTotalBenefitPrice(); + if (totalBenefitPrice >= SANTA.PRICE) return SANTA.NAME; + if (totalBenefitPrice >= TREE.PRICE) return TREE.NAME; + if (totalBenefitPrice >= STAR.PRICE) return STAR.NAME; + + return NONE.NAME; + } + #applyPromotions(promotion) { + const totalPriceWithoutDiscount = this.#order.getTotalPrice(); + if (totalPriceWithoutDiscount < PROMOTION_MINIMUM_PRICE) return 0; + + return promotion.getPromotionPrice(this.#order); + } +} + +export default Planner;
JavaScript
저는 왜 이렇게 생각하지 못했던 걸까요...ㅎㅎㅎ 상수화 해놓고 이상한 짓을 했네요.
@@ -0,0 +1,105 @@ +package controller; + +import model.user.ChristmasUser; +import model.calendar.December; +import model.event.ChristmasEvent; +import view.InputView; +import view.OutputView; + +import java.util.Map; + +public class ChristmasController { + private static ChristmasUser user; + + public ChristmasController() { + user = new ChristmasUser(); + } + + public void startEvent() { + December.init(); + requestGreeting(); + requestReadDate(); + requestReadMenu(); + requestPrintGuide(); + printEvent(); + } + + public void printEvent(){ + requestSection(); + requestPrintMenu(); + requestSection(); + requestPrintAmountBefore(); + requestSection(); + requestPrintGiftMenu(); + requestSection(); + requestPrintBenefitsDetails(); + requestSection(); + requestPrintTotalBenefit(); + requestSection(); + requestPrintEstimatedAmountAfter(); + requestSection(); + requestPrintBadge(); + } + + public static void requestSection() { + OutputView.printSection(); + } + + public static void requestGreeting() { + OutputView.printGreeting(); + } + + public void requestReadDate() { + user.setDate(InputView.readDate()); + } + + public void requestReadMenu() { + user.setOrder(InputView.readMenu()); + } + + public static void requestPrintGuide() { + OutputView.printBenefitsGuide(user.getMonth(), user.getDay()); + } + + public void requestPrintMenu() { + OutputView.printMenu(user.getOrder()); + } + + public void requestPrintAmountBefore() { + user.sumAmountBefore(); + OutputView.printTotalOrderAmountBefore(user.getTotalPrice()); + } + + public void requestPrintGiftMenu() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printGiftMenu("샴페인 1개"); + return; + } + OutputView.printGiftMenu("없음"); + } + + public void requestPrintBenefitsDetails() { + Map<String, Integer> benefit = ChristmasEvent.ResultChristmasDDayDiscount(user.getDay(), + user.getTotalPrice(), + user.getOrder()); + OutputView.printBenefitsDetails(benefit, user.getTotalPrice()); + if (user.getTotalPrice()>=10000) + user.setTotalDiscount(benefit.values().stream().mapToInt(Integer::intValue).sum()); + } + + public void requestPrintTotalBenefit() { + OutputView.printTotalBenefit(user.getTotalDiscount()); + } + public void requestPrintEstimatedAmountAfter() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount() + 25000); + return; + } + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount()); + } + + public void requestPrintBadge() { + OutputView.printEventBadge(user.getTotalDiscount()); + } + +}
Java
10_000을 상수로 포장하면 더욱 좋은 코드가 될 것 같아요!
@@ -0,0 +1,105 @@ +package controller; + +import model.user.ChristmasUser; +import model.calendar.December; +import model.event.ChristmasEvent; +import view.InputView; +import view.OutputView; + +import java.util.Map; + +public class ChristmasController { + private static ChristmasUser user; + + public ChristmasController() { + user = new ChristmasUser(); + } + + public void startEvent() { + December.init(); + requestGreeting(); + requestReadDate(); + requestReadMenu(); + requestPrintGuide(); + printEvent(); + } + + public void printEvent(){ + requestSection(); + requestPrintMenu(); + requestSection(); + requestPrintAmountBefore(); + requestSection(); + requestPrintGiftMenu(); + requestSection(); + requestPrintBenefitsDetails(); + requestSection(); + requestPrintTotalBenefit(); + requestSection(); + requestPrintEstimatedAmountAfter(); + requestSection(); + requestPrintBadge(); + } + + public static void requestSection() { + OutputView.printSection(); + } + + public static void requestGreeting() { + OutputView.printGreeting(); + } + + public void requestReadDate() { + user.setDate(InputView.readDate()); + } + + public void requestReadMenu() { + user.setOrder(InputView.readMenu()); + } + + public static void requestPrintGuide() { + OutputView.printBenefitsGuide(user.getMonth(), user.getDay()); + } + + public void requestPrintMenu() { + OutputView.printMenu(user.getOrder()); + } + + public void requestPrintAmountBefore() { + user.sumAmountBefore(); + OutputView.printTotalOrderAmountBefore(user.getTotalPrice()); + } + + public void requestPrintGiftMenu() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printGiftMenu("샴페인 1개"); + return; + } + OutputView.printGiftMenu("없음"); + } + + public void requestPrintBenefitsDetails() { + Map<String, Integer> benefit = ChristmasEvent.ResultChristmasDDayDiscount(user.getDay(), + user.getTotalPrice(), + user.getOrder()); + OutputView.printBenefitsDetails(benefit, user.getTotalPrice()); + if (user.getTotalPrice()>=10000) + user.setTotalDiscount(benefit.values().stream().mapToInt(Integer::intValue).sum()); + } + + public void requestPrintTotalBenefit() { + OutputView.printTotalBenefit(user.getTotalDiscount()); + } + public void requestPrintEstimatedAmountAfter() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount() + 25000); + return; + } + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount()); + } + + public void requestPrintBadge() { + OutputView.printEventBadge(user.getTotalDiscount()); + } + +}
Java
또 `getter()`로 가져와서 값을 비교하기 보단 `User`에 `isTotalPriceOver(int amount)`라는 메서드를 추가로 구현해 줘서 값에 대한 판단은 User 클래스 내부에서 하는게 더 객체지향적인 코드가 될 것 같아용
@@ -0,0 +1,16 @@ +package exception; + +public class InputValid { + private InputValid() { + + } + + public static int stringToInteger(String input, String errorType) { + for (int i = 0; i < input.length(); i++) { + if (!Character.isDigit(input.charAt(i))) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 " + errorType + "입니다. 다시 입력해 주세요."); + } + } + return Integer.parseInt(input); + } +}
Java
`Integer.parseInt()` 가 파싱 할 수 없는 경우엔 `NumberFormatException` 을 던지기 때문에 ~~~java try( return Integer.parseInt(input) ) catch (NumberFormatException e) { throw new IllegalArgumentException(); } ~~~ 처럼 더욱 간결하게 작성할 수 있어요!!
@@ -0,0 +1,16 @@ +package exception; + +public class InputValid { + private InputValid() { + + } + + public static int stringToInteger(String input, String errorType) { + for (int i = 0; i < input.length(); i++) { + if (!Character.isDigit(input.charAt(i))) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 " + errorType + "입니다. 다시 입력해 주세요."); + } + } + return Integer.parseInt(input); + } +}
Java
혹시 검증 로직을 분리하고 싶은 이유로 저렇게 작성 한거면 ~~~java for (int i = 0; i < input.length(); i++) { if (!Character.isDigit(input.charAt(i))) { throw new IllegalArgumentException("[ERROR] 유효하지 않은 " + errorType + "입니다. 다시 입력해 주세요."); } } ~~~ 를 `validateCanParseInt()` 같은 메소드로 분리해 주는게 더 보기 좋을 것 같아요!
@@ -0,0 +1,65 @@ +package exception; + +import model.menu.*; + +import java.util.Map; + +public class OrderMenu { + private OrderMenu() { + + } + + public static String[] menuFormat(String input) { + String[] itemInfo = input.split("-"); + + if (itemInfo.length != 2) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + + return itemInfo; + } + + public static int menuQuantityValid(String input) { + int num = InputValid.stringToInteger(input, "주문"); + if (num < 1) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + + return num; + } + + public static void menuValid(String menuName) { + if (!ChristmasMenu.isValidAppetizer(menuName) && + !ChristmasMenu.isValidDessert(menuName) && + !ChristmasMenu.isValidDrink(menuName) && + !ChristmasMenu.isValidMain(menuName)) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } + + public static void menuDuplication(Map<String, Integer> order, String menuName) { + if (order.containsKey(menuName)) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } + + public static void maxNumMenu(Map<String, Integer> order) { + if (order.values().stream().mapToInt(Integer::intValue).sum() > 20) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } + + public static void checkDrinkCount(Map<String, Integer> order) { + int drinkCount = 0; + + for (Drink menu : Drink.values()) { + if (order.containsKey(menu.getName())) { + drinkCount++; + } + } + + if (drinkCount == order.size()) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } +}
Java
validateDuplicate() 같은 이름이 더 어울릴 것 같아요!
@@ -0,0 +1,65 @@ +package exception; + +import model.menu.*; + +import java.util.Map; + +public class OrderMenu { + private OrderMenu() { + + } + + public static String[] menuFormat(String input) { + String[] itemInfo = input.split("-"); + + if (itemInfo.length != 2) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + + return itemInfo; + } + + public static int menuQuantityValid(String input) { + int num = InputValid.stringToInteger(input, "주문"); + if (num < 1) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + + return num; + } + + public static void menuValid(String menuName) { + if (!ChristmasMenu.isValidAppetizer(menuName) && + !ChristmasMenu.isValidDessert(menuName) && + !ChristmasMenu.isValidDrink(menuName) && + !ChristmasMenu.isValidMain(menuName)) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } + + public static void menuDuplication(Map<String, Integer> order, String menuName) { + if (order.containsKey(menuName)) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } + + public static void maxNumMenu(Map<String, Integer> order) { + if (order.values().stream().mapToInt(Integer::intValue).sum() > 20) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } + + public static void checkDrinkCount(Map<String, Integer> order) { + int drinkCount = 0; + + for (Drink menu : Drink.values()) { + if (order.containsKey(menu.getName())) { + drinkCount++; + } + } + + if (drinkCount == order.size()) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요."); + } + } +}
Java
~~~java boolean containsDrink = order.keySet().stream() .anyMatch(menu -> ChristmasMenu.isValidDrink(menu)) ~~~ 처럼 Stream을 활용할 수 있으면 더 좋을 것 같아요!
@@ -0,0 +1,19 @@ +package exception; + +public class VisitDate { + + private static Integer DateStart = 1; + private static Integer DateEnd = 31; + + private VisitDate() { + + } + /*날짜 범위를 확인 커밋메시지 실수*/ + public static int checkDate(String input) { + int date = InputValid.stringToInteger(input, "날짜"); + if (DateStart > date || DateEnd < date) { + throw new IllegalArgumentException("[ERROR] 유효하지 않은 날짜입니다. 다시 입력해 주세요."); + } + return date; + } +}
Java
이 방법 보다는 날짜 정보를 담고 있는 Date라는 클래스를 새로 만들어서 객채 생성과 동시에 검증을 하는건 어떨까요 ?? ~~~java class Date { final int value; public Date(int value) { validateDate(); this.value = value; } ~~~ 같이 활용하면 더욱 객체지향적인 코드가 될 것 같아요!
@@ -0,0 +1,84 @@ +package model.calendar; + +import model.event.ChristmasEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class December { + static private Map<Integer, Map<String, Object>> date = new HashMap<>(); + static private ArrayList<Integer> weekend = new ArrayList<Integer>() {{ + add(1); + add(2); + add(8); + add(9); + add(15); + add(16); + add(22); + add(23); + add(29); + add(30); + }}; + + static private ArrayList<Integer> starDay = new ArrayList<Integer>() {{ + add(3); + add(10); + add(17); + add(24); + add(25); + add(31); + }}; + + public static Map<String, Object> getDate(int day) { + return date.get(day); + } + + private December() { + } + + public static void init() { + initializeChristmasDiscountDates(); + initializeDefaultDiscountDates(); + } + + private static void initializeChristmasDiscountDates() { + int price = ChristmasEvent.getChristmasDDayDiscountInitPrice(); + int stepPrice = ChristmasEvent.getChristmasDDayDiscountStepPrice(); + + for (int i = 1; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(price, i); + date.put(i, tmpData); + price += stepPrice; + } + } + + private static void initializeDefaultDiscountDates() { + for (int i = 26; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(0, i); + date.put(i, tmpData); + } + } + + private static Map<String, Object> createDiscountDate(int price, int day) { + Map<String, Object> tmpData = new HashMap<>(); + tmpData.put("할인금액", price); + tmpData.put("영업일", getDayType(day)); + tmpData.put("별유무", isStar(day)); + return tmpData; + } + + public static String getDayType(Integer day) { + if (weekend.contains(day)) { + return "주말"; + } + return "평일"; + } + + public static boolean isStar(Integer day) { + if (starDay.contains(day)) { + return true; + } + return false; + } +}
Java
`List.of()`나 `Arrays.asList()` 를 활용하면 ~~~java List.of(1,2,8,9...); Arrays.asList(1,2,8,9...); ~~~ 처럼 간결하게 쓸 수 있어요!
@@ -0,0 +1,84 @@ +package model.calendar; + +import model.event.ChristmasEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class December { + static private Map<Integer, Map<String, Object>> date = new HashMap<>(); + static private ArrayList<Integer> weekend = new ArrayList<Integer>() {{ + add(1); + add(2); + add(8); + add(9); + add(15); + add(16); + add(22); + add(23); + add(29); + add(30); + }}; + + static private ArrayList<Integer> starDay = new ArrayList<Integer>() {{ + add(3); + add(10); + add(17); + add(24); + add(25); + add(31); + }}; + + public static Map<String, Object> getDate(int day) { + return date.get(day); + } + + private December() { + } + + public static void init() { + initializeChristmasDiscountDates(); + initializeDefaultDiscountDates(); + } + + private static void initializeChristmasDiscountDates() { + int price = ChristmasEvent.getChristmasDDayDiscountInitPrice(); + int stepPrice = ChristmasEvent.getChristmasDDayDiscountStepPrice(); + + for (int i = 1; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(price, i); + date.put(i, tmpData); + price += stepPrice; + } + } + + private static void initializeDefaultDiscountDates() { + for (int i = 26; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(0, i); + date.put(i, tmpData); + } + } + + private static Map<String, Object> createDiscountDate(int price, int day) { + Map<String, Object> tmpData = new HashMap<>(); + tmpData.put("할인금액", price); + tmpData.put("영업일", getDayType(day)); + tmpData.put("별유무", isStar(day)); + return tmpData; + } + + public static String getDayType(Integer day) { + if (weekend.contains(day)) { + return "주말"; + } + return "평일"; + } + + public static boolean isStar(Integer day) { + if (starDay.contains(day)) { + return true; + } + return false; + } +}
Java
Enum을 적극 활용해 보시는걸 추천드려요!
@@ -0,0 +1,84 @@ +package model.calendar; + +import model.event.ChristmasEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class December { + static private Map<Integer, Map<String, Object>> date = new HashMap<>(); + static private ArrayList<Integer> weekend = new ArrayList<Integer>() {{ + add(1); + add(2); + add(8); + add(9); + add(15); + add(16); + add(22); + add(23); + add(29); + add(30); + }}; + + static private ArrayList<Integer> starDay = new ArrayList<Integer>() {{ + add(3); + add(10); + add(17); + add(24); + add(25); + add(31); + }}; + + public static Map<String, Object> getDate(int day) { + return date.get(day); + } + + private December() { + } + + public static void init() { + initializeChristmasDiscountDates(); + initializeDefaultDiscountDates(); + } + + private static void initializeChristmasDiscountDates() { + int price = ChristmasEvent.getChristmasDDayDiscountInitPrice(); + int stepPrice = ChristmasEvent.getChristmasDDayDiscountStepPrice(); + + for (int i = 1; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(price, i); + date.put(i, tmpData); + price += stepPrice; + } + } + + private static void initializeDefaultDiscountDates() { + for (int i = 26; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(0, i); + date.put(i, tmpData); + } + } + + private static Map<String, Object> createDiscountDate(int price, int day) { + Map<String, Object> tmpData = new HashMap<>(); + tmpData.put("할인금액", price); + tmpData.put("영업일", getDayType(day)); + tmpData.put("별유무", isStar(day)); + return tmpData; + } + + public static String getDayType(Integer day) { + if (weekend.contains(day)) { + return "주말"; + } + return "평일"; + } + + public static boolean isStar(Integer day) { + if (starDay.contains(day)) { + return true; + } + return false; + } +}
Java
여기도 문자열을 그대로 반환하기보단 `WEEKDAY` `WEEKEND`를 가진 `Enum`을 만들어서 그 객체를 반환하는 게 더 좋아보여요!
@@ -0,0 +1,31 @@ +package model.event; + +public enum Badge { + STAR(5000), + TREE(10000), + SANTA(20000); + + private int price = 0; + + Badge(int price) { + this.price = price; + } + + public int getPrice() { + return price; + } + + public static String getBadgeType(int price) { + if (SANTA.getPrice() <= price) { + return "산타"; + } + if (TREE.getPrice() <= price) { + return "트리"; + } + if (STAR.getPrice() <= price) { + return "별"; + } + + return "없음"; + } +}
Java
이러면 Enum을 사용한 이유가 없어보여요 ,, String 대신 Enum을 반환하는 게 더 좋아보입니다 !
@@ -0,0 +1,24 @@ +package model.menu; + +public enum Main { + T_BONE_STEAK("티본스테이크", 55000), + BBQ_RIBS("바비큐립", 54000), + SEAFOOD_PASTA("해산물파스타", 35000), + CHRISTMAS_PASTA("크리스마스파스타", 25000); + + private String name = ""; + private int price = 0; + + Main(String name, int price) { + this.name = name; + this.price = price; + } + + public int getPrice() { + return price; + } + + public String getName() { + return name; + } +}
Java
Menu라는 Enum 하나를 만들고 그 안에 Category를 디저트, 애피타이저 등등으로 나눠두는 것은 어떨까요?
@@ -0,0 +1,16 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +public class DefaultMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + return request.getParameter(methodParameter.getParameterName()); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return true; + } +}
Java
해당 클래스에서 wrapper클래스도 지원해주면 좋겠네요. ClassUtils.isPrimitiveOrWrapper 등을 참고해보세요~
@@ -0,0 +1,16 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +public class DefaultMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + return request.getParameter(methodParameter.getParameterName()); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return true; + } +}
Java
true보다도 PrimitiveOrWrapper인지 확인할 수 있으면 좋겠네요.
@@ -0,0 +1,16 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +public class DefaultMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + return request.getParameter(methodParameter.getParameterName()); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return true; + } +}
Java
Primitive argument지원과 HttpServletRequest argument 지원은 나누어지는게 좋을 것 같습니다!
@@ -0,0 +1,24 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +import next.model.User; + +public class UserMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + String userId = request.getParameter("userId"); + String password = request.getParameter("password"); + String name = request.getParameter("name"); + String email = request.getParameter("email"); + + return new User(userId, password, name, email); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + Class<?> parameterType = methodParameter.getParameterType(); + return parameterType.equals(User.class); + } +}
Java
이와 같이 구현할 경우 User 객체만 사용할 수 있고 범용적으로 사용하는데는 한계가 있지 않을까? java bean 규약을 따르는 모든 객체에 대해 자동 매핑할 수 있도록 구현해 보면 어떨까? request로 전달되는 데이터에 해당하는 setter 메서드가 있으면 자동으로 값을 할당한다. 예를 들어 request.getParameter("userId") 값이 존재하면 setUserId()를 통해 값을 할당하는 방식으로 구현해야 java bean 규약을 따르는 객체에 범용적으로 사용할 수 있지 않을까?
@@ -0,0 +1,24 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +import next.model.User; + +public class UserMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + String userId = request.getParameter("userId"); + String password = request.getParameter("password"); + String name = request.getParameter("name"); + String email = request.getParameter("email"); + + return new User(userId, password, name, email); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + Class<?> parameterType = methodParameter.getParameterType(); + return parameterType.equals(User.class); + } +}
Java
포비님! 말씀하신 java bean 규약에 대해서는 PrimitiveMethodArgumentResolver, WrapperMethodArgumentResolver 에서 구현하고 있는데요. 혹시 이것만으로는 부족한 것일까요?
@@ -2,13 +2,30 @@ package com.petqua.application.product.review import com.amazonaws.services.s3.AmazonS3 import com.ninjasquad.springmockk.SpykBean +import com.petqua.application.product.dto.MemberProductReviewReadQuery import com.petqua.application.product.dto.ProductReviewCreateCommand import com.petqua.common.domain.findByIdOrThrow +import com.petqua.domain.delivery.DeliveryMethod +import com.petqua.domain.member.MemberRepository +import com.petqua.domain.order.OrderNumber +import com.petqua.domain.order.OrderPayment +import com.petqua.domain.order.OrderPaymentRepository +import com.petqua.domain.order.OrderRepository +import com.petqua.domain.order.OrderStatus.PURCHASE_CONFIRMED +import com.petqua.domain.product.ProductRepository +import com.petqua.domain.product.option.Sex import com.petqua.domain.product.review.ProductReviewImageRepository import com.petqua.domain.product.review.ProductReviewRepository +import com.petqua.domain.store.StoreRepository import com.petqua.exception.product.review.ProductReviewException import com.petqua.exception.product.review.ProductReviewExceptionType import com.petqua.test.DataCleaner +import com.petqua.test.fixture.member +import com.petqua.test.fixture.order +import com.petqua.test.fixture.product +import com.petqua.test.fixture.productReview +import com.petqua.test.fixture.productReviewImage +import com.petqua.test.fixture.store import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe @@ -18,12 +35,18 @@ import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE import org.springframework.http.MediaType import org.springframework.mock.web.MockMultipartFile +import java.math.BigDecimal @SpringBootTest(webEnvironment = NONE) class ProductReviewFacadeServiceTest( private val productReviewFacadeService: ProductReviewFacadeService, private val productReviewRepository: ProductReviewRepository, private val productReviewImageRepository: ProductReviewImageRepository, + private val orderRepository: OrderRepository, + private val memberRepository: MemberRepository, + private val storeRepository: StoreRepository, + private val productRepository: ProductRepository, + private val orderPaymentRepository: OrderPaymentRepository, private val dataCleaner: DataCleaner, @SpykBean @@ -225,6 +248,151 @@ class ProductReviewFacadeServiceTest( } } + Given("사용자가 리뷰를 작성한 후 자신의 리뷰 내역을 조회할 때") { + val member = memberRepository.save(member(nickname = "쿠아")) + val store = storeRepository.save(store(name = "펫쿠아")) + val productA = productRepository.save( + product( + name = "상품A", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val productB = productRepository.save( + product( + name = "상품B", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val orderA = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607020ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productA.id, + productName = productA.name, + thumbnailUrl = productA.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + val orderB = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607021ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productB.id, + productName = productB.name, + thumbnailUrl = productB.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + orderPaymentRepository.saveAll( + listOf( + OrderPayment( + orderId = orderA.id, + status = PURCHASE_CONFIRMED + ), + OrderPayment( + orderId = orderB.id, + status = PURCHASE_CONFIRMED + ) + ) + ) + + val productReviewA = productReviewRepository.save( + productReview( + productId = productA.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = true, + content = "상품A 정말 좋아요!" + ) + ) + val productReviewB = productReviewRepository.save( + productReview( + productId = productB.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = false, + content = "상품B 정말 좋아요!" + ) + ) + + productReviewImageRepository.saveAll( + listOf( + productReviewImage(imageUrl = "imageA1", productReviewId = productReviewA.id), + productReviewImage(imageUrl = "imageA2", productReviewId = productReviewA.id) + ) + ) + + When("회원의 Id를 입력해 조회하면") { + val memberProductReviewsResponse = productReviewFacadeService.readMemberProductReviews( + MemberProductReviewReadQuery( + memberId = member.id + ) + ) + + Then("리뷰 내역을 반환한다") { + val memberProductReviews = memberProductReviewsResponse.memberProductReviews + + memberProductReviews.size shouldBe 2 + + val memberProductReviewB = memberProductReviews[0] + memberProductReviewB.reviewId shouldBe productReviewB.id + memberProductReviewB.memberId shouldBe productReviewB.memberId + memberProductReviewB.createdAt shouldBe orderB.createdAt + memberProductReviewB.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeName shouldBe orderB.orderProduct.storeName + memberProductReviewB.productId shouldBe orderB.orderProduct.productId + memberProductReviewB.productName shouldBe orderB.orderProduct.productName + memberProductReviewB.productThumbnailUrl shouldBe orderB.orderProduct.thumbnailUrl + memberProductReviewB.quantity shouldBe orderB.orderProduct.quantity + memberProductReviewB.sex shouldBe orderB.orderProduct.sex.name + memberProductReviewB.deliveryMethod shouldBe orderB.orderProduct.deliveryMethod.name + memberProductReviewB.score shouldBe productReviewB.score.value + memberProductReviewB.content shouldBe productReviewB.content.value + memberProductReviewB.recommendCount shouldBe productReviewB.recommendCount + memberProductReviewB.reviewImages.size shouldBe 0 + + val memberProductReviewA = memberProductReviews[1] + memberProductReviewA.reviewId shouldBe productReviewA.id + memberProductReviewA.memberId shouldBe productReviewA.memberId + memberProductReviewA.createdAt shouldBe orderA.createdAt + memberProductReviewA.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeName shouldBe orderA.orderProduct.storeName + memberProductReviewA.productId shouldBe orderA.orderProduct.productId + memberProductReviewA.productName shouldBe orderA.orderProduct.productName + memberProductReviewA.productThumbnailUrl shouldBe orderA.orderProduct.thumbnailUrl + memberProductReviewA.quantity shouldBe orderA.orderProduct.quantity + memberProductReviewA.sex shouldBe orderA.orderProduct.sex.name + memberProductReviewA.deliveryMethod shouldBe orderA.orderProduct.deliveryMethod.name + memberProductReviewA.score shouldBe productReviewA.score.value + memberProductReviewA.content shouldBe productReviewA.content.value + memberProductReviewA.recommendCount shouldBe productReviewA.recommendCount + memberProductReviewA.reviewImages shouldBe listOf("imageA1", "imageA2") + } + } + } + afterContainer { dataCleaner.clean() }
Kotlin
여기 아래 memberProductReviews검증하는 코드가 조큼 긴데 음... 메서드로 분리하면 어떨까요?? valdiateMemberProductReview(memberProductReviewB, productReivewB, orderB);
@@ -6,6 +6,10 @@ import com.linecorp.kotlinjdsl.render.jpql.JpqlRenderer import com.petqua.common.domain.dto.CursorBasedPaging import com.petqua.common.util.createQuery import com.petqua.domain.member.Member +import com.petqua.domain.order.Order +import com.petqua.domain.order.OrderPayment +import com.petqua.domain.order.OrderProduct +import com.petqua.domain.product.dto.MemberProductReview import com.petqua.domain.product.dto.ProductReviewReadCondition import com.petqua.domain.product.dto.ProductReviewScoreWithCount import com.petqua.domain.product.dto.ProductReviewWithMemberResponse @@ -21,7 +25,7 @@ class ProductReviewCustomRepositoryImpl( override fun findAllByCondition( condition: ProductReviewReadCondition, - paging: CursorBasedPaging + paging: CursorBasedPaging, ): List<ProductReviewWithMemberResponse> { val query = jpql(ProductReviewDynamicJpqlGenerator) { @@ -69,4 +73,35 @@ class ProductReviewCustomRepositoryImpl( jpqlRenderer ) } + + override fun findMemberProductReviewBy( + memberId: Long, + paging: CursorBasedPaging, + ): List<MemberProductReview> { + val query = jpql(ProductReviewDynamicJpqlGenerator) { + selectNew<MemberProductReview>( + entity(ProductReview::class), + entity(Order::class), + entity(OrderPayment::class), + ).from( + entity(ProductReview::class), + join(Order::class).on( + path(ProductReview::memberId).eq(path(Order::memberId)) + .and(path(ProductReview::productId).eq(path(Order::orderProduct)(OrderProduct::productId))) + ), + join(OrderPayment::class).on(path(Order::id).eq(path(OrderPayment::orderId))) + ).whereAnd( + productReviewIdLt(paging.lastViewedId), + ).orderBy( + path(ProductReview::createdAt).desc(), + ) + } + + return entityManager.createQuery( + query, + jpqlRenderContext, + jpqlRenderer, + paging.limit + ) + } }
Kotlin
createdAt 대신 id로 정렬해도 무방한 거 맞을까요?? id가 인덱스라 더 효율적일 것 같아서요!
@@ -1,12 +1,14 @@ package com.petqua.application.product.review +import com.petqua.application.product.dto.MemberProductReviewReadQuery +import com.petqua.application.product.dto.MemberProductReviewResponse +import com.petqua.application.product.dto.MemberProductReviewsResponse import com.petqua.application.product.dto.ProductReviewReadQuery import com.petqua.application.product.dto.ProductReviewResponse import com.petqua.application.product.dto.ProductReviewStatisticsResponse import com.petqua.application.product.dto.ProductReviewsResponse import com.petqua.application.product.dto.UpdateReviewRecommendationCommand import com.petqua.common.domain.findByIdOrThrow -import com.petqua.domain.product.dto.ProductReviewWithMemberResponse import com.petqua.domain.product.review.ProductReview import com.petqua.domain.product.review.ProductReviewImage import com.petqua.domain.product.review.ProductReviewImageRepository @@ -42,7 +44,8 @@ class ProductReviewService( query.toCondition(), query.toPaging(), ) - val imagesByReview = getImagesByReview(reviewsByCondition) + val reviewIds = reviewsByCondition.map { it.id } + val imagesByReview = getImagesByReviewIds(reviewIds) val responses = reviewsByCondition.map { ProductReviewResponse(it, imagesByReview[it.id] ?: emptyList()) } @@ -59,12 +62,22 @@ class ProductReviewService( return ProductReviewsResponse.of(responses, query.limit) } - private fun getImagesByReview(reviewsByCondition: List<ProductReviewWithMemberResponse>): Map<Long, List<String>> { - val productReviewIds = reviewsByCondition.map { it.id } + private fun getImagesByReviewIds(productReviewIds: List<Long>): Map<Long, List<String>> { return productReviewImageRepository.findAllByProductReviewIdIn(productReviewIds).groupBy { it.productReviewId } .mapValues { it.value.map { image -> image.imageUrl } } } + fun readMemberProductReviews(query: MemberProductReviewReadQuery): MemberProductReviewsResponse { + val memberProductReviews = productReviewRepository.findMemberProductReviewBy(query.memberId, query.toPaging()) + val reviewIds = memberProductReviews.map { it.reviewId } + val imagesByReview = getImagesByReviewIds(reviewIds) + + val responses = memberProductReviews.map { + MemberProductReviewResponse(it, imagesByReview[it.reviewId] ?: emptyList()) + } + return MemberProductReviewsResponse.of(responses, query.limit) + } + @Transactional(readOnly = true) fun readReviewCountStatistics(productId: Long): ProductReviewStatisticsResponse { val reviewScoreWithCounts = productReviewRepository.findReviewScoresWithCount(productId)
Kotlin
ids를 받게 바꾸고 재활용 넘 좋네요!!
@@ -1,5 +1,6 @@ package com.petqua.presentation.product +import com.petqua.application.product.dto.MemberProductReviewsResponse import com.petqua.application.product.dto.ProductReviewStatisticsResponse import com.petqua.application.product.dto.ProductReviewsResponse import com.petqua.application.product.review.ProductReviewFacadeService @@ -9,6 +10,7 @@ import com.petqua.domain.auth.LoginMember import com.petqua.domain.auth.LoginMemberOrGuest import com.petqua.presentation.product.dto.CreateReviewRequest import com.petqua.presentation.product.dto.ReadAllProductReviewsRequest +import com.petqua.presentation.product.dto.ReadMemberProductReviewsRequest import com.petqua.presentation.product.dto.UpdateReviewRecommendationRequest import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.responses.ApiResponse @@ -63,14 +65,27 @@ class ProductReviewController( @PathVariable productId: Long, ): ResponseEntity<ProductReviewsResponse> { val responses = productReviewFacadeService.readAll( - request.toCommand( + request.toQuery( productId = productId, loginMemberOrGuest = loginMemberOrGuest, ) ) return ResponseEntity.ok(responses) } + @Operation(summary = "내 후기 조회 API", description = "내가 작성한 상품의 후기를 조회합니다") + @ApiResponse(responseCode = "200", description = "상품 후기 조건 조회 성공") + @SecurityRequirement(name = ACCESS_TOKEN_SECURITY_SCHEME_KEY) + @GetMapping("/product-reviews/me") + fun readMemberProductReviews( + @Auth loginMember: LoginMember, + request: ReadMemberProductReviewsRequest, + ): ResponseEntity<MemberProductReviewsResponse> { + val query = request.toQuery(loginMember) + val response = productReviewFacadeService.readMemberProductReviews(query) + return ResponseEntity.ok(response) + } + @Operation(summary = "상품 후기 통계 조회 API", description = "상품의 후기 통계를 조회합니다") @ApiResponse(responseCode = "200", description = "상품 후기 통계 조회 성공") @GetMapping("/products/{productId}/review-statistics")
Kotlin
URI 좋네용👍
@@ -2,13 +2,30 @@ package com.petqua.application.product.review import com.amazonaws.services.s3.AmazonS3 import com.ninjasquad.springmockk.SpykBean +import com.petqua.application.product.dto.MemberProductReviewReadQuery import com.petqua.application.product.dto.ProductReviewCreateCommand import com.petqua.common.domain.findByIdOrThrow +import com.petqua.domain.delivery.DeliveryMethod +import com.petqua.domain.member.MemberRepository +import com.petqua.domain.order.OrderNumber +import com.petqua.domain.order.OrderPayment +import com.petqua.domain.order.OrderPaymentRepository +import com.petqua.domain.order.OrderRepository +import com.petqua.domain.order.OrderStatus.PURCHASE_CONFIRMED +import com.petqua.domain.product.ProductRepository +import com.petqua.domain.product.option.Sex import com.petqua.domain.product.review.ProductReviewImageRepository import com.petqua.domain.product.review.ProductReviewRepository +import com.petqua.domain.store.StoreRepository import com.petqua.exception.product.review.ProductReviewException import com.petqua.exception.product.review.ProductReviewExceptionType import com.petqua.test.DataCleaner +import com.petqua.test.fixture.member +import com.petqua.test.fixture.order +import com.petqua.test.fixture.product +import com.petqua.test.fixture.productReview +import com.petqua.test.fixture.productReviewImage +import com.petqua.test.fixture.store import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe @@ -18,12 +35,18 @@ import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE import org.springframework.http.MediaType import org.springframework.mock.web.MockMultipartFile +import java.math.BigDecimal @SpringBootTest(webEnvironment = NONE) class ProductReviewFacadeServiceTest( private val productReviewFacadeService: ProductReviewFacadeService, private val productReviewRepository: ProductReviewRepository, private val productReviewImageRepository: ProductReviewImageRepository, + private val orderRepository: OrderRepository, + private val memberRepository: MemberRepository, + private val storeRepository: StoreRepository, + private val productRepository: ProductRepository, + private val orderPaymentRepository: OrderPaymentRepository, private val dataCleaner: DataCleaner, @SpykBean @@ -225,6 +248,151 @@ class ProductReviewFacadeServiceTest( } } + Given("사용자가 리뷰를 작성한 후 자신의 리뷰 내역을 조회할 때") { + val member = memberRepository.save(member(nickname = "쿠아")) + val store = storeRepository.save(store(name = "펫쿠아")) + val productA = productRepository.save( + product( + name = "상품A", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val productB = productRepository.save( + product( + name = "상품B", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val orderA = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607020ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productA.id, + productName = productA.name, + thumbnailUrl = productA.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + val orderB = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607021ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productB.id, + productName = productB.name, + thumbnailUrl = productB.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + orderPaymentRepository.saveAll( + listOf( + OrderPayment( + orderId = orderA.id, + status = PURCHASE_CONFIRMED + ), + OrderPayment( + orderId = orderB.id, + status = PURCHASE_CONFIRMED + ) + ) + ) + + val productReviewA = productReviewRepository.save( + productReview( + productId = productA.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = true, + content = "상품A 정말 좋아요!" + ) + ) + val productReviewB = productReviewRepository.save( + productReview( + productId = productB.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = false, + content = "상품B 정말 좋아요!" + ) + ) + + productReviewImageRepository.saveAll( + listOf( + productReviewImage(imageUrl = "imageA1", productReviewId = productReviewA.id), + productReviewImage(imageUrl = "imageA2", productReviewId = productReviewA.id) + ) + ) + + When("회원의 Id를 입력해 조회하면") { + val memberProductReviewsResponse = productReviewFacadeService.readMemberProductReviews( + MemberProductReviewReadQuery( + memberId = member.id + ) + ) + + Then("리뷰 내역을 반환한다") { + val memberProductReviews = memberProductReviewsResponse.memberProductReviews + + memberProductReviews.size shouldBe 2 + + val memberProductReviewB = memberProductReviews[0] + memberProductReviewB.reviewId shouldBe productReviewB.id + memberProductReviewB.memberId shouldBe productReviewB.memberId + memberProductReviewB.createdAt shouldBe orderB.createdAt + memberProductReviewB.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeName shouldBe orderB.orderProduct.storeName + memberProductReviewB.productId shouldBe orderB.orderProduct.productId + memberProductReviewB.productName shouldBe orderB.orderProduct.productName + memberProductReviewB.productThumbnailUrl shouldBe orderB.orderProduct.thumbnailUrl + memberProductReviewB.quantity shouldBe orderB.orderProduct.quantity + memberProductReviewB.sex shouldBe orderB.orderProduct.sex.name + memberProductReviewB.deliveryMethod shouldBe orderB.orderProduct.deliveryMethod.name + memberProductReviewB.score shouldBe productReviewB.score.value + memberProductReviewB.content shouldBe productReviewB.content.value + memberProductReviewB.recommendCount shouldBe productReviewB.recommendCount + memberProductReviewB.reviewImages.size shouldBe 0 + + val memberProductReviewA = memberProductReviews[1] + memberProductReviewA.reviewId shouldBe productReviewA.id + memberProductReviewA.memberId shouldBe productReviewA.memberId + memberProductReviewA.createdAt shouldBe orderA.createdAt + memberProductReviewA.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeName shouldBe orderA.orderProduct.storeName + memberProductReviewA.productId shouldBe orderA.orderProduct.productId + memberProductReviewA.productName shouldBe orderA.orderProduct.productName + memberProductReviewA.productThumbnailUrl shouldBe orderA.orderProduct.thumbnailUrl + memberProductReviewA.quantity shouldBe orderA.orderProduct.quantity + memberProductReviewA.sex shouldBe orderA.orderProduct.sex.name + memberProductReviewA.deliveryMethod shouldBe orderA.orderProduct.deliveryMethod.name + memberProductReviewA.score shouldBe productReviewA.score.value + memberProductReviewA.content shouldBe productReviewA.content.value + memberProductReviewA.recommendCount shouldBe productReviewA.recommendCount + memberProductReviewA.reviewImages shouldBe listOf("imageA1", "imageA2") + } + } + } + afterContainer { dataCleaner.clean() }
Kotlin
+ 조회 데이터에 대한 검증은 모든 필드를 할 필요는 없다고 생각합니다!
@@ -10,11 +10,14 @@ "preview": "vite preview" }, "dependencies": { + "add": "^2.0.6", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-hook-form": "^7.45.4", "react-router-dom": "^6.14.2", "recoil": "^0.7.7", "styled-components": "^6.0.7", + "yarn": "^1.22.19", "zustand": "^4.4.1" }, "devDependencies": {
Unknown
yarn 패키지 설치는 실수인가용~?
@@ -0,0 +1,19 @@ +import * as S from "./styled"; + +const Button = (props: { + text: string; + type: "button" | "submit" | "reset"; + bgColor: "black" | "grey" | "hidden"; + onClick?: React.MouseEventHandler<HTMLButtonElement>; +}) => { + const { type, text, bgColor, onClick } = props; + return ( + <> + <S.DefaultButton type={type} onClick={onClick} colortype={bgColor}> + {text} + </S.DefaultButton> + </> + ); +}; + +export default Button;
Unknown
jsx를 왜 빈태그로 래핑하셨나여?
@@ -0,0 +1,19 @@ +import * as S from "./styled"; + +const Button = (props: { + text: string; + type: "button" | "submit" | "reset"; + bgColor: "black" | "grey" | "hidden"; + onClick?: React.MouseEventHandler<HTMLButtonElement>; +}) => { + const { type, text, bgColor, onClick } = props; + return ( + <> + <S.DefaultButton type={type} onClick={onClick} colortype={bgColor}> + {text} + </S.DefaultButton> + </> + ); +}; + +export default Button;
Unknown
Button Props을 지정해주실Eo Native element attributes를 넣지않은 이유가 있을까여?
@@ -0,0 +1,76 @@ +import { styled } from "styled-components"; + +// input +export const RegisterInput = styled.input` + padding: 1rem; + border-radius: 8px; +`; + +// label text +export const InputLabelText = styled.div` + padding: 1rem 0; + font-weight: 600; + font-size: 16px; + color: #222; +`; + +// button +export const DefaultButton = styled.button<{ + colortype: "black" | "grey" | "hidden"; +}>` + width: 100%; + background-color: ${(props) => + props.colortype === "black" + ? "#222" + : props.colortype === "grey" + ? "#ddd" + : "#f0f0f0"}; + color: ${(props) => + props.colortype === "black" + ? "#fff" + : props.colortype === "grey" + ? "#222" + : "#cdcdcd"}; + font-weight: 700; + padding: 1rem; + border: 0; + cursor: ${(props) => (props.colortype === "hidden" ? "default" : "pointer")}; + border-radius: 8px; +`; + +// titleText +export const TitleBoldText = styled.div` + width: 100%; + padding-top: 1rem; + text-align: center; + font-size: 2rem; + font-weight: 600; + color: #222; +`; + +// text contents +export const TextContentsGreatingContainer = styled.div` + height: calc(100vh - 200px); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: 24px; + color: #222; + text-align: center; +`; + +export const TextContentsGreatingName = styled.div` + font-size: 24px; + font-weight: 600; + color: blueviolet; +`; + +export const TextContentsGreatingDescription = styled.div` + font-size: 24px; +`; + +export const GreetingNameContainer = styled.div` + display: flex; + flex-direction: row; +`;
TypeScript
Button Props 타입을 지정해주지 않은 이유가 무엇일까요?
@@ -0,0 +1,76 @@ +import { styled } from "styled-components"; + +// input +export const RegisterInput = styled.input` + padding: 1rem; + border-radius: 8px; +`; + +// label text +export const InputLabelText = styled.div` + padding: 1rem 0; + font-weight: 600; + font-size: 16px; + color: #222; +`; + +// button +export const DefaultButton = styled.button<{ + colortype: "black" | "grey" | "hidden"; +}>` + width: 100%; + background-color: ${(props) => + props.colortype === "black" + ? "#222" + : props.colortype === "grey" + ? "#ddd" + : "#f0f0f0"}; + color: ${(props) => + props.colortype === "black" + ? "#fff" + : props.colortype === "grey" + ? "#222" + : "#cdcdcd"}; + font-weight: 700; + padding: 1rem; + border: 0; + cursor: ${(props) => (props.colortype === "hidden" ? "default" : "pointer")}; + border-radius: 8px; +`; + +// titleText +export const TitleBoldText = styled.div` + width: 100%; + padding-top: 1rem; + text-align: center; + font-size: 2rem; + font-weight: 600; + color: #222; +`; + +// text contents +export const TextContentsGreatingContainer = styled.div` + height: calc(100vh - 200px); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: 24px; + color: #222; + text-align: center; +`; + +export const TextContentsGreatingName = styled.div` + font-size: 24px; + font-weight: 600; + color: blueviolet; +`; + +export const TextContentsGreatingDescription = styled.div` + font-size: 24px; +`; + +export const GreetingNameContainer = styled.div` + display: flex; + flex-direction: row; +`;
TypeScript
이렇게 hex 코드가 그대로 노출되는것은 매직넘버가 아닐까 싶슴다 상수처리해주면 어떨까요?
@@ -4,19 +4,20 @@ import { Routes, Route } from "react-router-dom"; // Components import Home from "./Home"; +import SignUp from "./SignUp"; const Router = () => { - const [isInLogged, setisInLogged] = useState(true); + const [isInLogged, setIsInLogged] = useState(false); return ( <> {isInLogged ? ( <Routes> - <Route path="/" element={<Home />} /> + <Route path="/" element={<Home setIsInLogged={setIsInLogged} />} /> </Routes> ) : ( <Routes> - <Route /> + <Route path="/" element={<SignUp setIsInLogged={setIsInLogged} />} /> </Routes> )} </>
Unknown
컴포넌트는 Login 인데 InLogged는 네이밍 불일치 아닐까요?
@@ -0,0 +1,60 @@ +import { + UseFormRegister, + FieldValues, + UseFormWatch, + UseFormGetValues, + UseFormSetValue, +} from "react-hook-form"; +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import * as S from "./styled"; + +type InputAndButtonPropsType = { + type: "button" | "submit" | "reset"; + name: string; + onClick: () => void; + register: UseFormRegister<FieldValues>; + watch: UseFormWatch<FieldValues>; + getValues?: UseFormGetValues<FieldValues>; + setValue?: UseFormSetValue<FieldValues>; + isEmailPass?: boolean; +}; + +// 버튼과 함께 쓰는 인풋 컴포넌트 +const InputAndButton = (props: InputAndButtonPropsType) => { + const { + onClick: checkValiable, + type, + name, + register, + getValues, + setValue, + watch, + isEmailPass, + } = props; + return ( + <> + <S.InputAndButtonContainer> + <Input + name={name} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + {isEmailPass ? ( + <Button text={"중복 확인 완료"} type={"button"} bgColor={"hidden"} /> + ) : ( + <Button + type={type} + text={"중복 확인하기"} + bgColor={"grey"} + onClick={checkValiable} + /> + )} + </S.InputAndButtonContainer> + </> + ); +}; + +export default InputAndButton;
Unknown
인풋과 버튼을 함께 사용하는 이유가 어떤 이유에서 있었을까요? 부모 컴포넌트에서 input과 button을 적절히 사용해주면 되는데 이렇게 분리하신 이유가 궁금함다
@@ -0,0 +1,190 @@ +/** + * + * 이름 + * 이메일 (중복 확인 버튼) + * 비밀번호 + * 비밀번호 재확인 + * 회원가입 버튼 + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // 등록 후 + if (!isEmailPass) { + return alert("이메일을 확인해주세요."); + } + + alert("회원가입을 축하합니다."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("비밀번호 확인이 일치하지 않습니다. 다시 입력해주세요."); + } + + return true; + }; + + const checkEmailVariable = () => { + // 이메일 check + if (!getValues("userEmail")) { + return alert("이메일을 입력해주세요."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("올바른 이메일을 입력해주세요."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("중복된 이메일입니다. 다시 입력해주세요."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("이름을 3자이상 입력해주세요."); + } + + if (!getValues("userPhoneNumber")) { + return alert("휴대폰 번호를 입력해주세요."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"회원가입"}</TitleTex> + <LabelText>{"이름"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"휴대폰 번호"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"이메일"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"비밀번호"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"비밀번호 확인"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"회원가입"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
여기서는 input button을 둘다 쓰면서 InputAndButton을 쓰기도해서 컴포넌트 설계에 대한 일관성이 안보인다? 제가 아토믹 디자인패턴을 완벽하게 이해하지는 못하고있다는점 알아주세요 폼 컴포넌트라고 하는데 폼컴포넌트에서 어떤 이벤트가 발생하지 솔직하게 잘 보이질않습니다! 컴포넌트를 보고있으면 이 컴포넌트에서는 어떤 일을 할지가 보여야하는데 잘 보이지가 않는다?
@@ -0,0 +1,36 @@ +import { + FieldValues, + UseFormGetValues, + UseFormRegister, + UseFormSetValue, + UseFormWatch, + useForm, +} from "react-hook-form"; +import * as S from "./styled"; +import { useEffect } from "react"; + +type InputPropsType = { + type?: string; + placeholder?: string; + name: string; + register: UseFormRegister<FieldValues>; + watch: UseFormWatch<FieldValues>; + getValues?: UseFormGetValues<FieldValues>; + setValue?: UseFormSetValue<FieldValues>; +}; + +const Input = (props: InputPropsType) => { + const { type, placeholder, name, register } = props; + + return ( + <> + <S.RegisterInput + type={type} + placeholder={placeholder} + {...register(name)} + ></S.RegisterInput> + </> + ); +}; + +export default Input;
Unknown
Native input 어트리뷰트를 고려해봐도 좋을것같습니다 그리고 watch와 같은 메서드를 해당 컴포넌트에서 알아야할까요? 사용처에서 알고있어야하는 메서드일텐데 과도한 정보가 아닐까싶네요!
@@ -0,0 +1,8 @@ +import * as S from "./styled"; + +const LabelText = (props: { children: string }) => { + const { children } = props; + return <S.InputLabelText>{children}</S.InputLabelText>; +}; + +export default LabelText;
Unknown
Props Type 컨벤션 지켜주세요
@@ -0,0 +1,21 @@ +import * as S from "./styled"; + +const TextContents = () => { + const userName = JSON.parse(localStorage.getItem("loginData") || "").name; + + return ( + <S.TextContentsGreatingContainer> + <S.GreetingNameContainer> + <S.TextContentsGreatingName>{userName}</S.TextContentsGreatingName> + <S.TextContentsGreatingDescription> + {"님,"} + </S.TextContentsGreatingDescription> + </S.GreetingNameContainer> + <S.TextContentsGreatingDescription> + {"환영합니다."} + </S.TextContentsGreatingDescription> + </S.TextContentsGreatingContainer> + ); +}; + +export default TextContents;
Unknown
이 경우엔 TextContents가 순수한 형태라고 할수있을까여? 사용처에서 userName을 프랍스로 전달해줬다면 순수했을것같은데요!
@@ -0,0 +1,27 @@ +import Button from "../atoms/Button"; +import TextContents from "../atoms/TextContents"; +import TitleTex from "../atoms/TitleText"; +import * as S from "./styled"; + +type MainPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; + +const Main = (props: MainPropsType) => { + return ( + <S.Container> + <TitleTex>{"홈"}</TitleTex> + <TextContents /> + <S.SignUpButtonContainer> + <Button + text={"로그아웃"} + bgColor={"black"} + type={"button"} + onClick={() => props.setIsInLogged(false)} + /> + </S.SignUpButtonContainer> + </S.Container> + ); +}; + +export default Main;
Unknown
setState를 프랍스로 전달하지않고 setState를 래핑하는 함수를 전달했으면 아래와 같이 편하게 전달이 가능하지않았을까여? ```ts setIsInLogged: (state : boolean) => void ```
@@ -0,0 +1,190 @@ +/** + * + * 이름 + * 이메일 (중복 확인 버튼) + * 비밀번호 + * 비밀번호 재확인 + * 회원가입 버튼 + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // 등록 후 + if (!isEmailPass) { + return alert("이메일을 확인해주세요."); + } + + alert("회원가입을 축하합니다."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("비밀번호 확인이 일치하지 않습니다. 다시 입력해주세요."); + } + + return true; + }; + + const checkEmailVariable = () => { + // 이메일 check + if (!getValues("userEmail")) { + return alert("이메일을 입력해주세요."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("올바른 이메일을 입력해주세요."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("중복된 이메일입니다. 다시 입력해주세요."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("이름을 3자이상 입력해주세요."); + } + + if (!getValues("userPhoneNumber")) { + return alert("휴대폰 번호를 입력해주세요."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"회원가입"}</TitleTex> + <LabelText>{"이름"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"휴대폰 번호"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"이메일"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"비밀번호"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"비밀번호 확인"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"회원가입"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
Submit 함수내부에서 유효성검사의 결과로 유저에게 노출시키는것이 아니라 Submit 이벤트를 막아버렸으면 어떨까여? 예를들어 유효성검사를 실패했다면 버튼의 disabled처리도 고려해볼수있을것같습니다 근데 이건 기획과 맞물리는거니까!
@@ -0,0 +1,190 @@ +/** + * + * 이름 + * 이메일 (중복 확인 버튼) + * 비밀번호 + * 비밀번호 재확인 + * 회원가입 버튼 + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // 등록 후 + if (!isEmailPass) { + return alert("이메일을 확인해주세요."); + } + + alert("회원가입을 축하합니다."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("비밀번호 확인이 일치하지 않습니다. 다시 입력해주세요."); + } + + return true; + }; + + const checkEmailVariable = () => { + // 이메일 check + if (!getValues("userEmail")) { + return alert("이메일을 입력해주세요."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("올바른 이메일을 입력해주세요."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("중복된 이메일입니다. 다시 입력해주세요."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("이름을 3자이상 입력해주세요."); + } + + if (!getValues("userPhoneNumber")) { + return alert("휴대폰 번호를 입력해주세요."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"회원가입"}</TitleTex> + <LabelText>{"이름"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"휴대폰 번호"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"이메일"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"비밀번호"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"비밀번호 확인"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"회원가입"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
setLocalData 함수네임을 보고 이게 뭔역할을하는거지 싶네요 setLocalStorageData라고 작명하는건 어땠을까여
@@ -0,0 +1,190 @@ +/** + * + * 이름 + * 이메일 (중복 확인 버튼) + * 비밀번호 + * 비밀번호 재확인 + * 회원가입 버튼 + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // 등록 후 + if (!isEmailPass) { + return alert("이메일을 확인해주세요."); + } + + alert("회원가입을 축하합니다."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "비밀번호는 특수문자 1개 포함하여 작성해주세요(최소 2자~최대20자)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("비밀번호 확인이 일치하지 않습니다. 다시 입력해주세요."); + } + + return true; + }; + + const checkEmailVariable = () => { + // 이메일 check + if (!getValues("userEmail")) { + return alert("이메일을 입력해주세요."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("올바른 이메일을 입력해주세요."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("중복된 이메일입니다. 다시 입력해주세요."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("이름을 3자이상 입력해주세요."); + } + + if (!getValues("userPhoneNumber")) { + return alert("휴대폰 번호를 입력해주세요."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"회원가입"}</TitleTex> + <LabelText>{"이름"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"휴대폰 번호"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"이메일"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"비밀번호"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"비밀번호 확인"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"회원가입"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
이런 유효성검사로직은 외부에 모듈화하여 사용하는건 어떘을까요? 그리고 리액트 훅폼 사용하신다면 https://www.react-hook-form.com/advanced-usage/#CustomHookwithResolver 이런것도 있슴다
@@ -4,19 +4,20 @@ import { Routes, Route } from "react-router-dom"; // Components import Home from "./Home"; +import SignUp from "./SignUp"; const Router = () => { - const [isInLogged, setisInLogged] = useState(true); + const [isInLogged, setIsInLogged] = useState(false); return ( <> {isInLogged ? ( <Routes> - <Route path="/" element={<Home />} /> + <Route path="/" element={<Home setIsInLogged={setIsInLogged} />} /> </Routes> ) : ( <Routes> - <Route /> + <Route path="/" element={<SignUp setIsInLogged={setIsInLogged} />} /> </Routes> )} </>
Unknown
이렇게 로그인 상태여부를 Router에서 하는것이 아니라 전역으로 관리하는게 어땠을까여? 라우터 컴포넌트는 url에 매핑되는 컴포넌트를 렌더해주는 역할이라고 생각되어서여! 해당 컴포넌트가 로그인 상태여부까지 알아야했을까요?
@@ -0,0 +1,11 @@ +import SignUpForm from "../components/organisms/SignUpForm"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; + +const SignUp = (props: SignUpFormPropsType) => { + return <SignUpForm setIsInLogged={props.setIsInLogged} />; +}; + +export default SignUp;
Unknown
이부분도 잘 이해가 되지않는데 Form 컴포넌트가 로그인여부를 알아야하는 이유가 없다고 생각됩니다..! 컴포넌트에게 전달되는 prop은 컴포넌트가 알아야하는 정보의 범위를 나타낸다고 봐요
@@ -0,0 +1,59 @@ +import accumulator.Accumulator; +import accumulator.PostFixAccumulator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class CalculatorTest { + + + @ParameterizedTest + @DisplayName("덧셈") + @CsvSource(value = {"1 2 + 3 + : 6", "10 20 + 30 + : 60", + "100 200 + 300 + : 600"}, delimiter = ':') + public void postFixAddCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("뺼셈") + @CsvSource(value = {"1 2 - 3 -: -4", "10 30 - 20 -: -40", "300 200 - 1 - : 99"}, delimiter = ':') + public void postFixMinusCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("곱셈") + @CsvSource(value = {"1 2 * 3 *: 6", "10 20 * 30 *: 6000", + "100 200 * 300 * : 6000000"}, delimiter = ':') + public void postFixMultiplyCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("나눗셈") + @CsvSource(value = {"100 10 / 1 / : 10", "10 2 / : 5", "10000 20 / 10 / : 50"}, delimiter = ':') + public void postFixDivideCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("사칙연산") + @CsvSource(value = {"5 3 2 * + 8 4 / - : 9", "7 4 * 2 / 3 + 1 - : 16", + "9 5 - 2 * 6 3 / +: 10"}, delimiter = ':') + public void PostFixCalculate(String expression, int expectResult) { + PostFixAccumulator calculator = new PostFixAccumulator(); + int result = calculator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + +}
Java
여기도 컨벤션이 쫌... 각 메서드 사이는 띄워 주시는게 원칙이고 IDE문제인건지 제가 보는 환면이 문제인건지 class 단위와 메서드 단위에 대한 블럭이 구분되지 않습니다. 이 또한 지켜주셨으면 좋겠습니다. 또한 지금 하나의 예시에 대한 테스트 코드만 작성하신 것을 볼 수 있습니다. @ParameterizedTest 를 공부해보시는게 좋을 것 같습니다.
@@ -0,0 +1,117 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +# End of https://www.toptal.com/developers/gitignore/api/intellij \ No newline at end of file
Unknown
이쪽 부분 옵션으로 어떠한 내역 추가했는지 알려주실 수 있을까요?
@@ -0,0 +1,9 @@ +package input; + +public interface Input { + + public String selectInput(); + + public String expressionInput(); + +}
Java
제너릭을 사용한 이유가 있을까요? Input은 바이트 혹은 문자열로 들어올텐데 어떠한 생각으로 제너릭을 사용했는지가 궁금합니당
@@ -0,0 +1,9 @@ + +import calculator.Calculator; + +public class main { + + public static void main(String[] args) { + new Calculator().run(); + } +}
Java
IOException이 애플리케이션이 실행되는 부분까지 전파되었습니다. 이러면 입출력 예외 발생 시 프로그램이 비정상적으로 종료될 가능성이 있겠네요.
@@ -0,0 +1,20 @@ +package repository; + +import java.util.ArrayList; +import java.util.List; + +public class Repository { + + private List<String> list = new ArrayList<>(); + + public void store(String expression, String result) { + StringBuilder formattedExpression = new StringBuilder(expression).append(" = ").append(result); + list.add(formattedExpression.toString()); + + } + + public List<String> getResult() { + return new ArrayList<>(list); + } + +}
Java
저장소를 List로 표현하신 이유를 알 수 있을까요? 동일한 연산식이여도 리스트에 추가하는게 맞을까요? 메모리를 최대한 아낄 수 있는 방법을 생각해보는게 좋을 것 같습니다
@@ -0,0 +1,19 @@ +import convertor.InfixToPostfixConverter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class ChangToPostfixTest { + + @ParameterizedTest + @DisplayName("중위 표기식 후위 표기식 변환") + @CsvSource(value = {"7 * 4 / 2 + 3 - 1 :'7 4 * 2 / 3 + 1 - '", + "9 - 5 * 2 + 6 / 3: '9 5 2 * - 6 3 / + '"}, delimiter = ':') + public void InfixToPostfixTest(String infixExpression, String postFinExpression) { + InfixToPostfixConverter calculator = new InfixToPostfixConverter(); + String result = calculator.changeToPostFix(infixExpression); + Assertions.assertEquals(postFinExpression, result); + } + +}
Java
테스트 코드 내용이 많이 부실합니다. 단위 테스트에 대해서 생각해보셨으면 좋겠습니다. 적어도 작성하신 코드에서 View 영역을 제외한 나머지 영역은 테스트가 가능합니다.
@@ -0,0 +1,22 @@ +package christmas.config; + +public enum ErrorMessage { + WRONG_DATE("유효하지 않은 날짜입니다."), + WRONG_ORDER("유효하지 않은 주문입니다."), + OVER_MAX_ORDER("메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다."), + ONLY_DRINK_ORDER("음료만 주문할 수 없습니다."); + + private static final String PREFIX = "[ERROR]"; + private static final String SUFFIX = "다시 입력해 주세요."; + private static final String DELIMITER = " "; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.join(DELIMITER, PREFIX, message, SUFFIX); + } +}
Java
해당 에러메시지는 왜 enum을 사용하셨나요? 상수를 만드는 데 일반 클래스와 enum 클래스를 사용하신 기준이 궁금합니다!
@@ -0,0 +1,57 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.dto.OrderDTO; +import christmas.util.IntParser; +import christmas.util.OrderParser; +import christmas.util.RetryExecutor; +import christmas.view.InputView; +import christmas.view.OutputView; + +import java.util.List; + +public class EventController { + private Bill bill; + private EventHandler eventHandler; + private final InputView inputView; + private final OutputView outputView; + + public EventController(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + outputView.printHelloMessage(); + RetryExecutor.execute(this::setBill, outputView::printErrorMessage); + RetryExecutor.execute(this::setOrder, error -> { + outputView.printErrorMessage(error); + bill.clearOrder(); + }); + printResult(); + } + + private void setBill() { + String input = inputView.inputDate().trim(); + bill = Bill.from(IntParser.parseIntOrThrow(input)); + eventHandler = EventHandler.from(bill); + } + + private void setOrder() { + String input = inputView.inputOrder(); + List<OrderDTO> orders = OrderParser.parseOrderOrThrow(input); + orders.forEach(it -> bill.add(Order.create(it.menuName(), it.count()))); + bill.validateOnlyDrink(); + } + + private void printResult() { + outputView.printEventPreviewTitle(bill.getDateValue()); + outputView.printOrder(bill.getAllOrders()); + outputView.printTotalPrice(bill.getTotalPrice()); + outputView.printGift(eventHandler.hasChampagneGift()); + outputView.printAllBenefit(eventHandler.getAllBenefit()); + outputView.printBenefitPrice(eventHandler.getTotalBenefitPrice()); + outputView.printAfterDiscountPrice(bill.getTotalPrice() - eventHandler.getTotalDiscountPrice()); + outputView.printBadge(Badge.getBadgeNameWithBenefitPrice(eventHandler.getTotalBenefitPrice())); + } +}
Java
오.. 이런 방법으로 사용하는 함수형 인터페이스는 처음 보는 것 같아요 배울 부분이 많네요 ㅠ 👍👍
@@ -0,0 +1,26 @@ +package christmas.domain; + +import java.util.Arrays; + +public enum Badge { + SANTA("산타", 20000), + TREE("트리", 10000), + STAR("별", 5000), + NOTHING("없음", 0); + + private final String badgeName; + private final int threshold; + + Badge(String badgeName, int threshold) { + this.badgeName = badgeName; + this.threshold = threshold; + } + + public static String getBadgeNameWithBenefitPrice(int benefitPrice) { + return Arrays.stream(Badge.values()) + .filter(it -> it.threshold <= benefitPrice) + .map(it -> it.badgeName) + .findFirst() + .orElse(NOTHING.badgeName); + } +}
Java
stream 사용을 잘하시는 것 같아요! 혹시 어떻게 공부하면 좋을지... 팁이 있으실까요?
@@ -0,0 +1,94 @@ +package christmas.domain; + +import christmas.config.Constant; +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; +import christmas.config.MenuType; + +import java.util.ArrayList; +import java.util.List; + +public class Bill implements CheckEventDate { + private final List<Order> orders = new ArrayList<>(); + private final Date date; + + private Bill(Date date) { + this.date = date; + } + + public static Bill from(int date) { + return new Bill(Date.from(date)); + } + + public Bill add(Order order) { + validateDuplicates(order); + orders.add(order); + validateMaxOrder(); + return this; + } + + private void validateDuplicates(Order newOrder) { + long duplicated = orders.stream() + .filter(it -> it.isSameMenu(newOrder)) + .count(); + if (duplicated != Constant.FILTER_CONDITION) { + throw new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage()); + } + } + + private void validateMaxOrder() { + if (Order.accumulateCount(orders) > Constant.MAX_ORDER) { + throw new IllegalArgumentException(ErrorMessage.OVER_MAX_ORDER.getMessage()); + } + } + + public void validateOnlyDrink() { + if (Order.accumulateCount(orders) == getTypeCount(MenuType.DRINK)) { + throw new IllegalArgumentException(ErrorMessage.ONLY_DRINK_ORDER.getMessage()); + } + } + + public void clearOrder() { + orders.clear(); + } + + public int getTotalPrice() { + return orders.stream() + .map(Order::getPrice) + .reduce(Constant.INIT_VALUE, Integer::sum); + } + + public int getTypeCount(MenuType type) { + return Order.accumulateCount(orders, type); + } + + public List<OrderDTO> getAllOrders() { + return orders.stream().map(Order::getOrder).toList(); + } + + // 아래는 Date 관련 method + + @Override + public boolean isWeekend() { + return date.isWeekend(); + } + + @Override + public boolean isSpecialDay() { + return date.isSpecialDay(); + } + + @Override + public boolean isNotPassedChristmas() { + return date.isNotPassedChristmas(); + } + + @Override + public int timePassedSinceFirstDay() { + return date.timePassedSinceFirstDay(); + } + + public int getDateValue() { + return date.getDateValue(); + } +}
Java
해당 리스트를 클래스로 만들어 선언 하는 것은 어떨까요?
@@ -0,0 +1,75 @@ +package christmas.domain; + +import christmas.config.Menu; +import christmas.config.MenuType; + +import java.util.function.Function; +import java.util.function.Predicate; + +public enum Event { + CHRISTMAS( + "크리스마스 디데이 할인", + true, + Bill::isNotPassedChristmas, + bill -> bill.timePassedSinceFirstDay() * 100 + 1000 + ), + WEEKDAY( + "평일 할인", + true, + bill -> !bill.isWeekend(), + bill -> bill.getTypeCount(MenuType.DESSERT) * 2023 + ), + WEEKEND( + "주말 할인", + true, + Bill::isWeekend, + bill -> bill.getTypeCount(MenuType.MAIN) * 2023 + ), + SPECIAL( + "특별 할인", + true, + Bill::isSpecialDay, + bill -> 1000 + ), + CHAMPAGNE( + "증정 이벤트", + false, + bill -> bill.getTotalPrice() >= 120000, + bill -> Menu.CHAMPAGNE.getPrice() + ); + + private static final int ALL_EVENT_THRESHOLD = 10000; + + private final String eventName; + private final boolean isDiscount; + private final Predicate<Bill> condition; + private final Function<Bill, Integer> benefit; + + Event( + String eventName, + boolean isDiscount, + Predicate<Bill> condition, + Function<Bill, Integer> benefit + ) { + this.eventName = eventName; + this.isDiscount = isDiscount; + this.condition = condition; + this.benefit = benefit; + } + + public String getEventName() { + return eventName; + } + + public boolean isDiscount() { + return isDiscount; + } + + public boolean checkCondition(Bill bill) { + return condition.test(bill) && bill.getTotalPrice() >= ALL_EVENT_THRESHOLD; + } + + public int getBenefit(Bill bill) { + return benefit.apply(bill); + } +}
Java
오.. 할인 리스트를 enum 클래스를 만들어 선언한 것 되게 좋은 아이디어네요 👍👍
@@ -0,0 +1,38 @@ +package christmas.util; + +import christmas.config.ErrorMessage; + +public class IntParser { + private static final int MAX_STRING_LENGTH = 11; + + private IntParser() { + // 인스턴스 생성 방지 + } + + public static int parseIntOrThrow(String numeric) { + validateNumericStringLength(numeric); + long parsed = parseLongOrThrow(numeric); + validateIntRange(parsed); + return Integer.parseInt(numeric); + } + + private static long parseLongOrThrow(String numeric) { + try { + return Long.parseLong(numeric); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private static void validateNumericStringLength(String numeric) { + if (numeric.length() > MAX_STRING_LENGTH) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private static void validateIntRange(long number) { + if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } +}
Java
인스턴스 생성 방지라는 것이 무엇인지 잘 모르겠는데 빈 생성자를 만들어 두면 무엇이 좋나요..??
@@ -0,0 +1,91 @@ +package christmas.view; + +import christmas.dto.BenefitDTO; +import christmas.dto.OrderDTO; + +import java.util.List; + +public class OutputView { + private void printMessage(ViewMessage message) { + System.out.println(message.getMessage()); + } + + private void printFormat(ViewMessage message, Object... args) { + System.out.printf(message.getMessage(), args); + newLine(); + } + + private void printTitle(ViewTitle title) { + System.out.println(title.getTitle()); + } + + public void printHelloMessage() { + printMessage(ViewMessage.HELLO); + } + + public void printEventPreviewTitle(int date) { + printFormat(ViewMessage.EVENT_PREVIEW_TITLE, date); + newLine(); + } + + public void printOrder(List<OrderDTO> orders) { + printTitle(ViewTitle.ORDER_MENU); + orders.forEach(it -> printFormat(ViewMessage.ORDER_FORMAT, it.menuName(), it.count())); + newLine(); + } + + public void printTotalPrice(int price) { + printTitle(ViewTitle.TOTAL_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printGift(boolean hasGift) { + printTitle(ViewTitle.GIFT_MENU); + if (hasGift) { + printMessage(ViewMessage.CHAMPAGNE); + newLine(); + return; + } + printMessage(ViewMessage.NOTHING); + newLine(); + } + + public void printAllBenefit(List<BenefitDTO> benefits) { + printTitle(ViewTitle.BENEFIT_LIST); + if (benefits.isEmpty()) { + printMessage(ViewMessage.NOTHING); + newLine(); + return; + } + benefits.forEach(it -> printFormat(ViewMessage.BENEFIT_FORMAT, it.EventName(), it.price())); + newLine(); + } + + public void printBenefitPrice(int price) { + printTitle(ViewTitle.BENEFIT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, -price); + newLine(); + } + + public void printAfterDiscountPrice(int price) { + printTitle(ViewTitle.AFTER_DISCOUNT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printBadge(String badge) { + printTitle(ViewTitle.BADGE); + System.out.println(badge); + } + + public void printErrorMessage(IllegalArgumentException error) { + newLine(); + System.out.println(error.getMessage()); + newLine(); + } + + public void newLine() { + System.out.println(); + } +}
Java
새로운 라인을 만들때는 System.lineSeperator()를 추천 해주시더라구요. 참고하시면 좋을 것 같습니다!
@@ -0,0 +1,145 @@ +package christmas.domain; + +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; +import christmas.config.MenuType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class BillTest { + @DisplayName("잘못된 date 값 사용 시 예외 발생") + @ParameterizedTest + @ValueSource(ints = {-5, 0, 32, 75}) + void checkCreateFromWrongDate(int date) { + assertThatThrownBy(() -> Bill.from(date)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.WRONG_DATE.getMessage()); + } + + @DisplayName("add 동작 확인") + @Test + void checkAddMethod() { + Bill bill = Bill.from(1) + .add(Order.create("시저샐러드", 3)) + .add(Order.create("해산물파스타", 1)) + .add(Order.create("제로콜라", 2)); + + List<OrderDTO> answer = List.of( + new OrderDTO("시저샐러드", 3), + new OrderDTO("해산물파스타", 1), + new OrderDTO("제로콜라", 2) + ); + + assertThat(bill.getAllOrders()).isEqualTo(answer); + } + + @DisplayName("중복된 메뉴를 입력시 예외 발생") + @Test + void checkDuplicatedMenu() { + assertThatThrownBy(() -> Bill.from(1) + .add(Order.create("크리스마스파스타", 2)) + .add(Order.create("바비큐립", 1)) + .add(Order.create("크리스마스파스타", 3)) + ).isInstanceOf(IllegalArgumentException.class).hasMessage(ErrorMessage.WRONG_ORDER.getMessage()); + } + + @DisplayName("메뉴가 20개를 초과하는 경우 예외 발생") + @ParameterizedTest + @MethodSource("overedOrder") + void checkOverOrder(List<Order> orders) { + Bill bill = Bill.from(1); + + assertThatThrownBy(() -> orders.forEach(bill::add)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.OVER_MAX_ORDER.getMessage()); + } + + static Stream<Arguments> overedOrder() { + return Stream.of( + Arguments.of(List.of( + Order.create("해산물파스타", 7), + Order.create("제로콜라", 15) + )), + Arguments.of(List.of( + Order.create("아이스크림", 25) + )) + ); + } + + @DisplayName("clearOrder 동작 확인") + @Test + void checkClearOrder() { + Bill bill = Bill.from(1) + .add(Order.create("시저샐러드", 3)) + .add(Order.create("해산물파스타", 1)) + .add(Order.create("제로콜라", 2)); + bill.clearOrder(); + assertThat(bill.getAllOrders()).isEqualTo(List.of()); + } + + @DisplayName("getTotalPrice 동작 확인") + @Test + void checkTotalPrice() { + Bill bill = Bill.from(1) + .add(Order.create("타파스", 2)) + .add(Order.create("티본스테이크", 1)) + .add(Order.create("제로콜라", 2)); + assertThat(bill.getTotalPrice()).isEqualTo(72000); + } + + @DisplayName("getTypeCount 동작 확인") + @ParameterizedTest + @MethodSource("typedBill") + void checkTypeCount(Bill bill, MenuType type, int answer) { + assertThat(bill.getTypeCount(type)).isEqualTo(answer); + } + + static Stream<Arguments> typedBill() { + return Stream.of( + Arguments.of( + Bill.from(1) + .add(Order.create("양송이수프", 3)) + .add(Order.create("티본스테이크", 1)) + .add(Order.create("바비큐립", 2)), + MenuType.MAIN, + 3 + ), + Arguments.of( + Bill.from(1) + .add(Order.create("티본스테이크", 2)) + .add(Order.create("초코케이크", 2)) + .add(Order.create("아이스크림", 3)) + .add(Order.create("제로콜라", 7)), + MenuType.DESSERT, + 5 + ) + ); + } + + @DisplayName("getDateValue 동작 확인") + @ParameterizedTest + @ValueSource(ints = {1, 17, 25, 31}) + void checkDateValue(int date) { + assertThat(Bill.from(date).getDateValue()).isEqualTo(date); + } + + @DisplayName("음료만 주문한 경우 예외 발생") + @Test + void checkOnlyDrinkOrder() { + assertThatThrownBy(() -> Bill.from(1) + .add(Order.create("제로콜라", 3)) + .add(Order.create("레드와인", 1)) + .validateOnlyDrink() + ).isInstanceOf(IllegalArgumentException.class).hasMessage(ErrorMessage.ONLY_DRINK_ORDER.getMessage()); + } +}
Java
isInstanceOf와 hasMessage를 사용하면 좀 더 꼼꼼한 테스트를 할 수 있군요! 배워 갑니당 👍👍
@@ -0,0 +1,22 @@ +package christmas.config; + +public enum ErrorMessage { + WRONG_DATE("유효하지 않은 날짜입니다."), + WRONG_ORDER("유효하지 않은 주문입니다."), + OVER_MAX_ORDER("메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다."), + ONLY_DRINK_ORDER("음료만 주문할 수 없습니다."); + + private static final String PREFIX = "[ERROR]"; + private static final String SUFFIX = "다시 입력해 주세요."; + private static final String DELIMITER = " "; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.join(DELIMITER, PREFIX, message, SUFFIX); + } +}
Java
사실 저도 상수를 처리할 때 `enum`을 사용할지 `class`를 사용할지 고민이 많았습니다. 어떤 기준을 세워야 할지도 스스로 확립하지 못했구요. 그래서 우선은 아무런 기능 없이 상수값만 저장하는 경우는 `class`를 사용하고, 약간의 기능이라도 함께 사용한다면 `enum`을 사용하려고 해봤습니다. 여기 `ErrorMessage`에서는 공통적으로 사용되는 prefix와 suffix를 `getMessage()`메서드에서 함께 합쳐서 반환하도록 구상했기 때문에 `enum`을 사용해봤습니다. 사실 `class`로 사용해도 무방할거 같네요. 😂
@@ -0,0 +1,57 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.dto.OrderDTO; +import christmas.util.IntParser; +import christmas.util.OrderParser; +import christmas.util.RetryExecutor; +import christmas.view.InputView; +import christmas.view.OutputView; + +import java.util.List; + +public class EventController { + private Bill bill; + private EventHandler eventHandler; + private final InputView inputView; + private final OutputView outputView; + + public EventController(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + outputView.printHelloMessage(); + RetryExecutor.execute(this::setBill, outputView::printErrorMessage); + RetryExecutor.execute(this::setOrder, error -> { + outputView.printErrorMessage(error); + bill.clearOrder(); + }); + printResult(); + } + + private void setBill() { + String input = inputView.inputDate().trim(); + bill = Bill.from(IntParser.parseIntOrThrow(input)); + eventHandler = EventHandler.from(bill); + } + + private void setOrder() { + String input = inputView.inputOrder(); + List<OrderDTO> orders = OrderParser.parseOrderOrThrow(input); + orders.forEach(it -> bill.add(Order.create(it.menuName(), it.count()))); + bill.validateOnlyDrink(); + } + + private void printResult() { + outputView.printEventPreviewTitle(bill.getDateValue()); + outputView.printOrder(bill.getAllOrders()); + outputView.printTotalPrice(bill.getTotalPrice()); + outputView.printGift(eventHandler.hasChampagneGift()); + outputView.printAllBenefit(eventHandler.getAllBenefit()); + outputView.printBenefitPrice(eventHandler.getTotalBenefitPrice()); + outputView.printAfterDiscountPrice(bill.getTotalPrice() - eventHandler.getTotalDiscountPrice()); + outputView.printBadge(Badge.getBadgeNameWithBenefitPrice(eventHandler.getTotalBenefitPrice())); + } +}
Java
저도 함수형 인터페이스라는 걸 처음 써봤답니다! 3주차 코드리뷰를 하면서 어깨너머로 배운거라, @HongYeseul 님도 이번 코드리뷰를 기회로 한번 공부해보시는건 어떨까요? 😁
@@ -0,0 +1,26 @@ +package christmas.domain; + +import java.util.Arrays; + +public enum Badge { + SANTA("산타", 20000), + TREE("트리", 10000), + STAR("별", 5000), + NOTHING("없음", 0); + + private final String badgeName; + private final int threshold; + + Badge(String badgeName, int threshold) { + this.badgeName = badgeName; + this.threshold = threshold; + } + + public static String getBadgeNameWithBenefitPrice(int benefitPrice) { + return Arrays.stream(Badge.values()) + .filter(it -> it.threshold <= benefitPrice) + .map(it -> it.badgeName) + .findFirst() + .orElse(NOTHING.badgeName); + } +}
Java
정말 놀랍게도 저도 1주차와 2주차 코드 리뷰를 하면서 대부분의 리뷰에 `stream`사용을 잘 하시는게 부럽다! 라는식으로 많이 리뷰를 남기고 다녔어요. 그렇게 많은 분들의 코드를 보면서 `stream`과 점점 친숙해지다 보니 저도 `stream`을 한번 써볼까? 라는 생각이 들었고, 그렇게 점점 익숙해진 것 같아요! 😊 4주차가 끝난 지금은 학교 도서관에서 '이것이 자바다'라는 책을 빌려서 읽고 있어요. 자바에 익숙해지긴 했지만, 그래도 컬렉션이나 스트림과 같은 부분을 제대로 공부하고 싶어서요. 이런 자바 서적을 하나 정하셔서 기본 문법을 정리하시는 시간을 가지는 것도 좋아보입니다! 😄
@@ -0,0 +1,38 @@ +package christmas.util; + +import christmas.config.ErrorMessage; + +public class IntParser { + private static final int MAX_STRING_LENGTH = 11; + + private IntParser() { + // 인스턴스 생성 방지 + } + + public static int parseIntOrThrow(String numeric) { + validateNumericStringLength(numeric); + long parsed = parseLongOrThrow(numeric); + validateIntRange(parsed); + return Integer.parseInt(numeric); + } + + private static long parseLongOrThrow(String numeric) { + try { + return Long.parseLong(numeric); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private static void validateNumericStringLength(String numeric) { + if (numeric.length() > MAX_STRING_LENGTH) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private static void validateIntRange(long number) { + if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } +}
Java
모든 메서드가 `static`인 유틸리티성 클래스의 경우 `new` 키워드를 사용해 객체를 생성할 필요가 전혀 없다고 생각했습니다. 그래서 혹시라도 의도치 않게 객체가 생성될 경우를 방지하기 위해 생성자를 `private`으로 선언했고, 빈 생성자로 그냥 두긴 좀 밋밋해서 주석을 살짝 달아봤습니다! 😁
@@ -0,0 +1,91 @@ +package christmas.view; + +import christmas.dto.BenefitDTO; +import christmas.dto.OrderDTO; + +import java.util.List; + +public class OutputView { + private void printMessage(ViewMessage message) { + System.out.println(message.getMessage()); + } + + private void printFormat(ViewMessage message, Object... args) { + System.out.printf(message.getMessage(), args); + newLine(); + } + + private void printTitle(ViewTitle title) { + System.out.println(title.getTitle()); + } + + public void printHelloMessage() { + printMessage(ViewMessage.HELLO); + } + + public void printEventPreviewTitle(int date) { + printFormat(ViewMessage.EVENT_PREVIEW_TITLE, date); + newLine(); + } + + public void printOrder(List<OrderDTO> orders) { + printTitle(ViewTitle.ORDER_MENU); + orders.forEach(it -> printFormat(ViewMessage.ORDER_FORMAT, it.menuName(), it.count())); + newLine(); + } + + public void printTotalPrice(int price) { + printTitle(ViewTitle.TOTAL_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printGift(boolean hasGift) { + printTitle(ViewTitle.GIFT_MENU); + if (hasGift) { + printMessage(ViewMessage.CHAMPAGNE); + newLine(); + return; + } + printMessage(ViewMessage.NOTHING); + newLine(); + } + + public void printAllBenefit(List<BenefitDTO> benefits) { + printTitle(ViewTitle.BENEFIT_LIST); + if (benefits.isEmpty()) { + printMessage(ViewMessage.NOTHING); + newLine(); + return; + } + benefits.forEach(it -> printFormat(ViewMessage.BENEFIT_FORMAT, it.EventName(), it.price())); + newLine(); + } + + public void printBenefitPrice(int price) { + printTitle(ViewTitle.BENEFIT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, -price); + newLine(); + } + + public void printAfterDiscountPrice(int price) { + printTitle(ViewTitle.AFTER_DISCOUNT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printBadge(String badge) { + printTitle(ViewTitle.BADGE); + System.out.println(badge); + } + + public void printErrorMessage(IllegalArgumentException error) { + newLine(); + System.out.println(error.getMessage()); + newLine(); + } + + public void newLine() { + System.out.println(); + } +}
Java
좋은 지적 감사합니다! `lineSeperator()`에 대해서 공부해봐야겠네요! 😊
@@ -0,0 +1,94 @@ +package christmas.domain; + +import christmas.config.Constant; +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; +import christmas.config.MenuType; + +import java.util.ArrayList; +import java.util.List; + +public class Bill implements CheckEventDate { + private final List<Order> orders = new ArrayList<>(); + private final Date date; + + private Bill(Date date) { + this.date = date; + } + + public static Bill from(int date) { + return new Bill(Date.from(date)); + } + + public Bill add(Order order) { + validateDuplicates(order); + orders.add(order); + validateMaxOrder(); + return this; + } + + private void validateDuplicates(Order newOrder) { + long duplicated = orders.stream() + .filter(it -> it.isSameMenu(newOrder)) + .count(); + if (duplicated != Constant.FILTER_CONDITION) { + throw new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage()); + } + } + + private void validateMaxOrder() { + if (Order.accumulateCount(orders) > Constant.MAX_ORDER) { + throw new IllegalArgumentException(ErrorMessage.OVER_MAX_ORDER.getMessage()); + } + } + + public void validateOnlyDrink() { + if (Order.accumulateCount(orders) == getTypeCount(MenuType.DRINK)) { + throw new IllegalArgumentException(ErrorMessage.ONLY_DRINK_ORDER.getMessage()); + } + } + + public void clearOrder() { + orders.clear(); + } + + public int getTotalPrice() { + return orders.stream() + .map(Order::getPrice) + .reduce(Constant.INIT_VALUE, Integer::sum); + } + + public int getTypeCount(MenuType type) { + return Order.accumulateCount(orders, type); + } + + public List<OrderDTO> getAllOrders() { + return orders.stream().map(Order::getOrder).toList(); + } + + // 아래는 Date 관련 method + + @Override + public boolean isWeekend() { + return date.isWeekend(); + } + + @Override + public boolean isSpecialDay() { + return date.isSpecialDay(); + } + + @Override + public boolean isNotPassedChristmas() { + return date.isNotPassedChristmas(); + } + + @Override + public int timePassedSinceFirstDay() { + return date.timePassedSinceFirstDay(); + } + + public int getDateValue() { + return date.getDateValue(); + } +}
Java
그렇게도 할 수 있겠네요! 아예 `Orders`라는 클래스를 만들어 리스트를 관리하는 방법도 좋아보입니다! 리팩토링 할만한 부분들을 짚어주셔서 좋습니다!! 😁
@@ -0,0 +1,456 @@ +# 이메일 답장 + +> 제목: 12월 이벤트 개발 보고 + +> 보낸 사람: 개발팀 <`dev@woowacourse.io`> +> +> 받는 사람: 비즈니스팀 <`biz@woowacourse.io`> + +안녕하세요. 개발팀입니다! + +12월 이벤트 플래너 개발 요청 사항은 잘 받아 보았습니다. +요청하신 내용들을 모두 적용해보았는데요. 혹시 누락된 부분이 있다면 바로 말씀해주시면 감사하겠습니다. + +#### 방문 날짜 입력 + +- 방문 날짜는 1 이상 31 이하의 숫자로만 입력받게 했습니다. +- 단, 사용자의 부주의로 입력 앞뒤로 공백이 생기는 경우가 종종 있는데, 이는 프로그램 내부에서 자동 처리하게 했습니다. + - " 12 " (O) + - " 1 2" (X) +- 이외의 모든 잘못된 입력은 요청하신 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 날짜입니다. 다시 입력해 주세요.` (요청 사항) +- 에러 메시지가 나온 다음에는 다시 재입력 받을 수 있게 했습니다. + +#### 주문 입력 + +- 모든 주문은 "해산물파스타-2,레드와인-1,초코케이크-1" 와 같은 형식으로만 입력받게 했습니다. +- 단, 사용자의 부주의로 입력 사이에 공백이 생기는 경우가 종종 있는데, 이는 프로그램 내부에서 자동 처리하게 했습니다. + - 띄워쓰기가 포함된 메뉴가 없어서 입력의 모든 공백을 허용하게 했습니다. + - "해산물파스타 - 2, 레드와인 - 3" (O) + - "해 산 물 파 스 타 - 1 2 , 레드와인-3" (O) +- 메뉴 형식이 예시와 다른 경우 에러 메시지를 보이게 했습니다. + - "해산물파스타 2, 레드와인 3" (X) + - "해산물파스타: 2, 레드와인: 3" (X) + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 메뉴의 개수를 0 이하의 숫자로 입력하면 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 중복 메뉴를 입력한 경우 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 메뉴판에 없는 메뉴를 입력한 경우 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 메뉴의 개수가 합쳐서 20개를 초과하면 에러 메시지를 보이게 했습니다. + - `[ERROR] 메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다. 다시 입력해 주세요.` (추가) +- 음료만 주문 시, 에러 메시지를 보이게 했습니다. + - `[ERROR] 음료만 주문할 수 없습니다. 다시 입력해 주세요.` (추가) +- 에러 메시지가 나온 다음에는 다시 주문을 재입력 받을 수 있게 했습니다. + +#### 이벤트 + +- 모든 이벤트는 10,000원 이상부터 적용되도록 했습니다. +- 모든 이벤트는 적용 가능하다면 중복으로 적용되도록 했습니다. +- 크리스마스 디데이 할인 + - 기간: 2023.12.01 ~ 2023.12.25 + - 할인 금액: 2023.12.01 1,000원으로 시작하여, 매일 할인 금액이 100원씩 증가 + - 할인 방법: 총 주문 금액에서 할인 금액만큼 할인 +- 평일 할인 + - 기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일 ~ 목요일 + - 할인 금액: 2,023원 + - 할인 방법: 디저트 메뉴를 개당 할인 금액만큼 할인 +- 주말 할인 + - 기간: 2023.12.01 ~ 2023.12.31 중 매주 금요일, 토요일 + - 할인 금액: 2,023원 + - 할인 방법: 메인 메뉴를 개당 할인 금액만큼 할인 +- 특별 할인 + - 기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일, 12월 25일 + - 할인 금액: 1,000원 + - 할인 방법: 총주문 금액에서 할인 금액만큼 할인 +- 증정 이벤트 + - 기간: 2023.12.01 ~ 2023.12.31 + - 이벤트: 할인 전 총주문 금액이 12만원 이상일 때, 샴페인 1개 증정 (25,000원) +- 증정 이벤트는 총혜택 금액에는 포함되지만, 실제 할인 후 예상 결제 금액에는 적용되지 않게 했습니다. +- 나머지 이벤트는 총혜택 금액에도 포함되고 실제 할인에도 적용됩니다. + +#### 이벤트 배지 + +- 5천원 미만: 없음 +- 5천원 이상: 별 +- 1만원 이상: 트리 +- 2만원 이상: 산타 + +#### 결과 출력 + +- 입력한 주문 메뉴를 출력합니다. +- 할인 전 총주문 금액을 출력합니다. +- 증정 메뉴를 출력합니다. 증정 메뉴가 없으면 "없음"을 출력합니다. +- 혜택 내역을 출력합니다. 혜택이 없으면 "없음"을 출력합니다. +- 총혜택 금액을 출력합니다. 혜택이 없으면 0을 출력합니다. +- 할인 후 예상 결제 금액을 출력합니다. +- 12월 이벤트 배지를 출력합니다. 받을 배지가 없으면 "없음"을 출력합니다. + +개발팀 내부에서 여러 상황을 고려해서 많은 테스트를 진행했습니다. +하지만 그럼에도 버그가 있거나 새롭게 추가하고 싶은 기능이 있으시다면 바로 말씀해주세요. + +특히 새로운 이벤트를 추가하거나, 새로운 메뉴를 추가하는 건 언제든 환영입니다! +확장성있게 설계를 해두었기 때문에 편하게 요청하셔도 괜찮습니다! + +감사합니다 :) + +--- + +# 이벤트 내용 + +## 이벤트 종류 + +### 크리스마스 디데이 할인 + +기간: 2023.12.01 ~ 2023.12.25 + +할인 금액: 2023.12.01 1,000원으로 시작하여, 매일 할인 금액이 100원씩 증가 + +할인 방법: 총 주문 금액에서 할인 금액만큼 할인 + +### 평일 할인 + +기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일 ~ 목요일 + +할인 금액: 2,023원 + +할인 방법: 디저트 메뉴를 개당 할인 금액만큼 할인 + +### 주말 할인 + +기간: 2023.12.01 ~ 2023.12.31 중 매주 금요일, 토요일 + +할인 금액: 2,023원 + +할인 방법: 메인 메뉴를 개당 할인 금액만큼 할인 + +### 특별 할인 + +기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일, 12월 25일 + +할인 금액: 1,000원 + +할인 방법: 총주문 금액에서 할인 금액만큼 할인 + +### 증정 이벤트 + +기간: 2023.12.01 ~ 2023.12.31 + +이벤트: 할인 전 총주문 금액이 12만원 이상일 때, 샴페인 1개 증정 (25,000원) + +## 이벤트 배지 + +이벤트로 받은 총혜택 금액에 따라 각기 다른 이벤트 배지를 부여 +(이때 `총혜택 금액 = 할인 금액의 합계 + 증정 메뉴의 가격`으로 계산) + +- 5천원 이상: 별 +- 1만원 이상: 트리 +- 2만원 이상: 산타 + +## 이벤트 주의 사항 + +- 총주문 금액 10,000원 이상부터 이벤트가 적용 +- 음료만 주문 시, 주문할 수 없음 +- 메뉴는 한 번에 최대 20개까지만 주문할 수 있음 (종류가 아닌 개수) + +# 개발 요청 사항 + +- [x] 방문할 날짜 입력 + - [x] 1 이상 31 이하의 숫자만 입력받음 +- [x] 주문할 메뉴와 개수 입력 + - [x] 메뉴판에 있는 메뉴만 입력받음 + - [x] 정해진 형식의 메뉴만 입력받음 + - [x] 메뉴의 개수는 1 이상의 숫자만 입력받음 + - [x] 중복되지 않은 메뉴만 입력받음 +- [x] 주문 메뉴 출력 + - [x] 출력 순서는 자유롭게 출력 +- [x] 할인 전 총주문 금액 출력 +- [x] 증정 메뉴 출력 + - [x] 증정 이벤트에 해당하지 않는 경우 `없음` 출력 +- [x] 혜택 내역 출력 + - [x] 고객에게 적용된 이벤트 내역만 출력 + - [x] 적용된 이벤트가 없는 경우 `없음` 출력 + - [x] 이벤트 출력 순서는 자유롭게 출력 +- [x] 총혜택 금액 출력 + - [x] `총혜택 금액 = 할인 금액의 합계 + 증정 메뉴의 가격` +- [x] 할인 후 예상 결제 금액 출력 + - [x] `할인 후 예상 결제 금액 = 할인 전 총주문 금액 - 할인금액` +- [x] 12월 이벤트 배지 출력 + - [x] 이벤트 배지가 부여되지 않는 경우 `없음` 출력 + +# 입력 예외 사항 + +- [x] 방문할 날짜 입력 예외 + - [x] 1 이상 31 이하의 숫자가 아닌 경우 + - `[ERROR] 유효하지 않은 날짜입니다. 다시 입력해 주세요.` (요청 사항) +- [x] 주문할 메뉴와 개수 입력 + - [x] 메뉴판에 없는 메뉴를 입력 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 메뉴의 개수가 1 이상의 정수가 아닌 경우 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 메뉴의 형식이 정해진 형식을 벗어난 경우 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 중복 메뉴를 입력한 경우 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 메뉴 개수가 20개를 초과한 경우 + - `[ERROR] 메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다. 다시 입력해 주세요.` (추가) + - [x] 음료만 주문한 경우 + - `[ERROR] 음료만 주문할 수 없습니다. 다시 입력해 주세요.` (추가) +- 이외 모든 예외 사항에 `[ERROR]` Prefix 사용 + +# 기능 명세 + +## Config + +- [x] Menu + - [x] 메뉴 이름으로 Menu 찾아 반환 +- [x] MenuType +- [x] ErrorMessage + +## Controller + +- [x] EventController + - [x] 날짜를 입력받아 `Bill`을 생성 + - [x] 주문을 입력받아 `Bill`에 추가 + - [x] 위 두 과정 중 예외가 발생할 경우 반복하여 입력받음 + - [x] 필요한 모든 결과를 출력 + +## Domain + +- [x] Order + - [x] 주문 메뉴와 주문 수량을 저장 + - [x] 1이상의 주문 수량만 사용하도록 검증 + - [x] 가격(`메뉴 가격 x 주문 수량`)을 반환 + - [x] 특정 `Order`와 같은 메뉴인지 확인 + - [x] `OrderDTO` 반환 + - [x] `List<Order>`의 모든 주문 수량을 누적하여 합산 + - [x] `MenuType`을 조건으로 사용할 수 있도록 오버로딩 +- [x] Bill + - [x] 주문 리스트와 날짜를 저장 + - [x] 주문을 추가 + - [x] 중복되는 메뉴가 있는 주문인지 검증 + - [x] 최대 주문수를 넘지 않는지 검증 + - [x] 음료만 주문했는지 검증 + - [x] 주문을 초기화 + - [x] 전체 주문 금액을 계산 + - [x] 특정 타입의 메뉴 주문량을 반환 + - [x] `CheckEventDate`의 메서드 오버로딩 + - [x] 주문 날짜를 반환 +- [x] Date + - [x] 생성을 위한 날짜가 1 ~ 31 범위의 값인지 검증 + - [x] 요일을 확인 + - [x] 주말인지 확인 -> 평일 할인, 주말 할인 + - [x] 달력에 별이 있는 특별한 날인지 확인 -> 특별 할인 + - [x] 크리스마스 이전인지 확인 -> 크리스마스 디데이 할인 + - [x] 첫째날로부터 얼마나 지났는지 확인 -> 크리스마스 디데이 할인 + - [x] 날짜를 반환 +- [x] EventHandler + - [x] 증정 메뉴(샴페인) 존재 여부 + - [x] 혜택 내역 + - [x] 할인 금액 + - [x] 총혜택 금액 +- [x] Event + - [x] 이벤트 조건에 맞는지 확인 + - [x] 이벤트 혜택을 반환 +- [x] Badge + - [x] 가격에 맞는 이벤트 배지를 반환 + +## DTO + +- [x] BenefitDTO -> 혜택 이름, 혜택 금액을 전달하는 객체 +- [x] OrderDTO -> 메뉴 이름, 주문 개수를 전달하는 객체 + +## View + +- [x] InputView + - [x] 날짜 입력 + - [x] 주문 입력 +- [x] OutputView + - [x] 각 제목 출력 + - [x] 주문 메뉴 출력 + - [x] 할인 전 총주문 금액 출력 + - [x] 증정 메뉴 출력 + - [x] 혜택 내역 출력 + - [x] 총혜택 금액 출력 + - [x] 할인 후 예상 결제 금액 출력 + - [x] 이벤트 배지 출력 +- [x] ViewMessage +- [x] ViewTitle + +## Util + +- [x] IntParser +- [x] OrderParser +- [x] RetryExecutor + +# 테스트 코드 + +- [x] Badge + - [x] `getBadgeNameWithBenefitPrice` 동작 확인 + - [x] 0 -> 없음 + - [x] 2500 -> 없음 + - [x] 5000 -> 별 + - [x] 9000 -> 별 + - [x] 10000 -> 트리 + - [x] 17000 -> 트리 + - [x] 20000 -> 산타 + - [x] 50000 -> 산타 +- [x] Bill + - [x] `from` 동작 확인 + - [x] 잘못된 date 값 사용시 예외 발생 -> Date 클래스에서 테스트 + - [x] `add` 동작 확인 + - [x] `add` 중복된 메뉴 입력시 예외 발생 + - [x] `add` 20개 이상 메뉴 입력시 예외 발생 + - [x] 여러 메뉴의 총 수량이 20개 이상인 경우 + - [x] 한 메뉴의 수량이 20개 이상인 경우 + - [x] `clearOrder` 동작 확인 + - [x] `getTotalPrice` 동작 확인 + - [x] `getTypeCount` 동작 확인 + - [x] DESSERT 타입 확인 + - [x] MAIN 타입 확인 + - [x] `getDateValue` 동작 확인 + - [x] 음료만 주문한 경우 예외 발생 + - [x] 이외의 Date 관련 메서드는 Date 클래스에서 테스트 +- [x] Date + - [x] 생성 시 `validate` 동작 확인 + - [x] 1 -> 동작 + - [x] 25 -> 동작 + - [x] 31 -> 동작 + - [x] 생성 시 `validate` 예외 발생 + - [x] -5 -> 예외 발생 + - [x] 0 -> 예외 발생 + - [x] 32 -> 예외 발생 + - [x] 75 -> 예외 발생 + - [x] `isWeekend` 동작 확인 + - [x] 1 -> true + - [x] 8 -> true + - [x] 16 -> true + - [x] 17 -> false + - [x] 25 -> false + - [x] 28 -> false + - [x] `isSpecialDay` 동작 확인 + - [x] 3 -> true + - [x] 25 -> true + - [x] 31 -> true + - [x] 13 -> false + - [x] 22 -> false + - [x] `isNotPassedChristmas` 동작 확인 + - [x] 1 -> true + - [x] 14 -> true + - [x] 25 -> true + - [x] 26 -> false + - [x] 31 -> false + - [x] `timePassedSinceFirstDay` 동작 확인 + - [x] 1 -> 0 + - [x] 18 -> 17 + - [x] 25 -> 24 +- [x] Event + - [x] `getEventName` 동작 확인 + - [x] `isDiscount` 동작 확인 + - [x] `checkCondition` 동작 확인 + - [x] 크리스마스 디데이 할인 -> `isNotPassedChristmas`에서 테스트 + - [x] 평일 할인 -> `isWeekend`에서 테스트 + - [x] 주말 할인 -> `isWeekend`에서 테스트 + - [x] 특별 할인 -> `isSpecialDay`에서 테스트 + - [x] 증정 이벤트 + - [x] 티본스테이크(2) + 아이스크림(2) = 120,000 -> true + - [x] 티본스테이크(2) + 시저샐러드(5) = 150,000 -> true + - [x] 바비큐립(1) + 양송이수프(1) = 60,000 -> false + - [x] `getBenefit` 동작 확인 + - [x] 크리스마스 디데이 할인 + - [x] 1 -> 1000 + - [x] 11 -> 2000 + - [x] 25 -> 3400 + - [x] 평일 할인 + - [x] 양송이수프(1) + 바비큐립(1) -> 0 + - [x] 타파스(1) + 해산물파스타(1) + 초코케이크(2) -> 4046 + - [x] 바비큐립(2) + 초코케이크(2) + 아이스크림(3) -> 10115 + - [x] 주말 할인 + - [x] 양송이수프(2) + 제로콜라(2) -> 0 + - [x] 타파스(1) + 티본스테이크(1) -> 2023 + - [x] 티본스테이크(1) + 바비큐립(2) + 해산물파스타(3) + 제로콜라(6) -> 12138 + - [x] 특별 할인 -> 항상 1000 + - [x] 증정 이벤트 -> 항상 25000 + - [x] 모든 이벤트에서 총주문금액 10000원 이상부터 이벤트 적용 +- [x] EventHandler + - [x] `hasChampagneGift` 동작 확인 -> Event `checkCondition`에서 테스트 + - [x] `getTotalDiscountPrice` 동작 확인 + - [x] 1일, 티본스테이크(2) + 아이스크림(2) -> 5046 + - [x] 3일, 티본스테이크(2) + 아이스크림(2) -> 10292 + - [x] 13일, 해산물파스타(10) + 초코케이크(1) + 아이스크림(2) -> 8269 + - [x] 25일, 크리스마스파스타(2) + 샴페인(2) -> 4400 + - [x] 30일, 시저샐러드(5) + 바비큐립(2) + 티본스테이크(1) + 레드와인(2) -> 6069 + - [x] `getTotalBenefitPrice` 동작 확인 + - [x] 1일, 티본스테이크(2) + 아이스크림(2) -> 30046 + - [x] 3일, 티본스테이크(2) + 아이스크림(2) -> 10292 + - [x] 13일, 해산물파스타(10) + 초코케이크(1) + 아이스크림(2) -> 33269 + - [x] 25일, 크리스마스파스타(2) + 샴페인(2) -> 4400 + - [x] 30일, 시저샐러드(5) + 바비큐립(2) + 티본스테이크(1) + 레드와인(2) -> 31069 + - [x] `getAllBenefit` 동작 확인 + - [x] 1일, 티본스테이크(2) + 아이스크림(1) -> 크리스마스(1000), 주말(4046) + - [x] 3일, 티본스테이크(1) + 아이스크림(4) -> 크리스마스(1200), 평일(8092), 특별(1000) + - [x] 13일, 해산물파스타(10) + 초코케이크(1) + 아이스크림(2) -> 크리스마스(2200), 평일(6069), 증정(25000) + - [x] 25일, 크리스마스파스타(2) + 샴페인(2) -> 크리스마스(3400), 특별(1000) + - [x] 30일, 시저샐러드(5) + 바비큐립(2) + 티본스테이크(1) + 레드와인(2) -> 주말(6069), 증정(25000) +- [x] Order + - [x] `create` 동작 확인 + - [x] 잘못된 메뉴 이름 사용시 예외 발생 -> Menu 클래스에서 테스트 + - [x] 잘못된 count 사용시 예외 발생 + - [x] `getPrice` 동작 확인 + - [x] 타파스(2) -> 11000 + - [x] 바비큐립(3) -> 162000 + - [x] 아이스크림(5) -> 25000 + - [x] `isSameMenu` 동작 확인 + - [x] 타파스, 타파스 -> true + - [x] 레드와인, 레드와인 -> true + - [x] 티본스테이크, 아이스크림 -> false + - [x] 초코케이크, 바비큐립 -> false + - [x] `accumulateCount` 동작 확인 + - [x] 티본스테이크(5) -> 5 + - [x] 양송이수프(3) + 바비큐립(1) + 아이스크림(3) -> 7 + - [x] `accumulateCount` type 사용하여 동작 확인 + - [x] DESSERT, 티본스테이크(2) + 제로콜라(4) -> 0 + - [x] MAIN, 양송이스프(3) + 바비큐립(1) + 해산물파스타(2) + 아이스크림(5) -> 3 +- [x] Menu + - [x] `from` 동작 확인 + - [x] 양송이수프 -> Menu.SOUP + - [x] 해산물파스타 -> Menu.SEAFOOD_PASTA + - [x] 메뉴판에 없는 메뉴 입력시 예외 확인 +- [x] IntParser + - [x] `parseIntOrThrow` 동작 확인 + - [x] "123" -> 123 + - [x] "-123" -> -123 + - [x] "2147483647" -> 2147483647 (최댓값) + - [x] "-2147483648" -> -2147483648 (최솟값) + - [x] 정수형태가 아닌 문자열 입력시 예외 발생 + - [x] ABC + - [x] 12L + - [x] 13.5 + - [x] Integer 범위를 벗어난 문자열 입력시 예외 발생 + - [x] 2147483648 + - [x] -2147483649 + - [x] 999999999999999 +- [x] OrderParser + - [x] `parseOrderOrThrow` 동작 확인 + - [x] "타파스-1,제로콜라-2,티본스테이크-5" -> 타파스(1) + 제로콜라(2) + 티본스테이크(5) + - [x] "타파스 - 1, 제로콜라- 2, 티본 스테이크 -5" -> 타파스(1) + 제로콜라(2) + 티본스테이크(5) + - [x] "티본스테이크-1" -> 티본스테이크(1) + - [x] "해산물파스타-3 , " -> 해산물파스타(3) + - [x] 잘못된 형식의 주문을 입력시 예외 발생 + - [x] "타파스: 1, 제로콜라: 2" + - [x] "타파스-1 제로콜라-2 파스타-3" + - [x] "타파스 1 제로콜라 2 파스타 3" + - [x] "타파스, 제로콜라, 파스타" + - [x] "타파스 -" + - [x] "- 3" +- [x] OutputView + - [x] `printHelloMessage` 동작 확인 + - [x] `printEventPreviewTitle` 동작 확인 + - [x] `printOrder` 동작 확인 + - [x] `printTotalPrice` 동작 확인 + - [x] `printGift` 동작 확인 + - [x] `printAllBenefit` 동작 확인 + - [x] `printBenefitPrice` 동작 확인 + - [x] `printAfterDiscountPrice` 동작 확인 + - [x] `printBadge` 동작 확인
Unknown
Readme.md 를 꼼꼼히 잘 작성하신 것 같아요😄
@@ -0,0 +1,47 @@ +package christmas.config; + +import java.util.Arrays; + +public enum Menu { + SOUP("양송이수프", 6000, MenuType.APPETIZER), + TAPAS("타파스", 5500, MenuType.APPETIZER), + SALAD("시저샐러드", 8000, MenuType.APPETIZER), + STEAK("티본스테이크", 55000, MenuType.MAIN), + BARBECUE("바비큐립", 54000, MenuType.MAIN), + SEAFOOD_PASTA("해산물파스타", 35000, MenuType.MAIN), + CHRISTMAS_PASTA("크리스마스파스타", 25000, MenuType.MAIN), + CAKE("초코케이크", 15000, MenuType.DESSERT), + ICE_CREAM("아이스크림", 5000, MenuType.DESSERT), + COLA("제로콜라", 3000, MenuType.DRINK), + WINE("레드와인", 60000, MenuType.DRINK), + CHAMPAGNE("샴페인", 25000, MenuType.DRINK); + + private final String menuName; + private final int price; + private final MenuType type; + + Menu(String menuName, int price, MenuType type) { + this.menuName = menuName; + this.price = price; + this.type = type; + } + + public static Menu from(String menuName) { + return Arrays.stream(Menu.values()) + .filter(it -> menuName.equals(it.menuName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage())); + } + + public String getMenuName() { + return menuName; + } + + public int getPrice() { + return price; + } + + public MenuType getType() { + return type; + } +}
Java
저도 같은 방식으로 구현했는데 Menu의 확장성을 생각해서 여러가지 카테고리에 포함될 수도 있는 점을 생각하여 카테고리는 따로 빼는게 좋다는 의견을 봤습니다! 쿠키님은 어떻게 생각하시나요?
@@ -0,0 +1,18 @@ +package christmas.util; + +import java.util.function.Consumer; + +public class RetryExecutor { + private RetryExecutor() { + // 인스턴스 생성 방지 + } + + public static void execute(Runnable action, Consumer<IllegalArgumentException> onError) { + try { + action.run(); + } catch (IllegalArgumentException error) { + onError.accept(error); + execute(action, onError); + } + } +}
Java
Retry를 저는 Controller에서 while문으로 하여 지저분한 것이 고민이었는데 이런 방법이 있었네요! 배워 갑니다!!
@@ -0,0 +1,91 @@ +package christmas.view; + +import christmas.dto.BenefitDTO; +import christmas.dto.OrderDTO; + +import java.util.List; + +public class OutputView { + private void printMessage(ViewMessage message) { + System.out.println(message.getMessage()); + } + + private void printFormat(ViewMessage message, Object... args) { + System.out.printf(message.getMessage(), args); + newLine(); + } + + private void printTitle(ViewTitle title) { + System.out.println(title.getTitle()); + } + + public void printHelloMessage() { + printMessage(ViewMessage.HELLO); + } + + public void printEventPreviewTitle(int date) { + printFormat(ViewMessage.EVENT_PREVIEW_TITLE, date); + newLine(); + } + + public void printOrder(List<OrderDTO> orders) { + printTitle(ViewTitle.ORDER_MENU); + orders.forEach(it -> printFormat(ViewMessage.ORDER_FORMAT, it.menuName(), it.count())); + newLine(); + } + + public void printTotalPrice(int price) { + printTitle(ViewTitle.TOTAL_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printGift(boolean hasGift) { + printTitle(ViewTitle.GIFT_MENU); + if (hasGift) { + printMessage(ViewMessage.CHAMPAGNE); + newLine(); + return; + } + printMessage(ViewMessage.NOTHING); + newLine(); + } + + public void printAllBenefit(List<BenefitDTO> benefits) { + printTitle(ViewTitle.BENEFIT_LIST); + if (benefits.isEmpty()) { + printMessage(ViewMessage.NOTHING); + newLine(); + return; + } + benefits.forEach(it -> printFormat(ViewMessage.BENEFIT_FORMAT, it.EventName(), it.price())); + newLine(); + } + + public void printBenefitPrice(int price) { + printTitle(ViewTitle.BENEFIT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, -price); + newLine(); + } + + public void printAfterDiscountPrice(int price) { + printTitle(ViewTitle.AFTER_DISCOUNT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printBadge(String badge) { + printTitle(ViewTitle.BADGE); + System.out.println(badge); + } + + public void printErrorMessage(IllegalArgumentException error) { + newLine(); + System.out.println(error.getMessage()); + newLine(); + } + + public void newLine() { + System.out.println(); + } +}
Java
저는 자주 사용되는 newLine()을 static으로 선언하면 좋을 것 같다고 말씀드리려 했는데 lineSeperator() 라는게 있었군요! 저도 배워가겠습니다😊
@@ -0,0 +1,12 @@ +package christmas.config; + +public class Constant { + public static final int INIT_VALUE = 0; + public static final int FILTER_CONDITION = 0; + public static final int MIN_ORDER = 1; + public static final int MAX_ORDER = 20; + + private Constant() { + // 인스턴스 생성 방지 + } +}
Java
개인적으로 Constant 클래스에 상수들을 모아넣는 것 보다는 각 클래스에 필요한 Constant 클래스를 각각 만들어서 만드는 것이 의미를 더 명확히하고 알아보기 쉬운 것 같아요!
@@ -0,0 +1,145 @@ +package christmas.domain; + +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; +import christmas.config.MenuType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class BillTest { + @DisplayName("잘못된 date 값 사용 시 예외 발생") + @ParameterizedTest + @ValueSource(ints = {-5, 0, 32, 75}) + void checkCreateFromWrongDate(int date) { + assertThatThrownBy(() -> Bill.from(date)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.WRONG_DATE.getMessage()); + } + + @DisplayName("add 동작 확인") + @Test + void checkAddMethod() { + Bill bill = Bill.from(1) + .add(Order.create("시저샐러드", 3)) + .add(Order.create("해산물파스타", 1)) + .add(Order.create("제로콜라", 2)); + + List<OrderDTO> answer = List.of( + new OrderDTO("시저샐러드", 3), + new OrderDTO("해산물파스타", 1), + new OrderDTO("제로콜라", 2) + ); + + assertThat(bill.getAllOrders()).isEqualTo(answer); + } + + @DisplayName("중복된 메뉴를 입력시 예외 발생") + @Test + void checkDuplicatedMenu() { + assertThatThrownBy(() -> Bill.from(1) + .add(Order.create("크리스마스파스타", 2)) + .add(Order.create("바비큐립", 1)) + .add(Order.create("크리스마스파스타", 3)) + ).isInstanceOf(IllegalArgumentException.class).hasMessage(ErrorMessage.WRONG_ORDER.getMessage()); + } + + @DisplayName("메뉴가 20개를 초과하는 경우 예외 발생") + @ParameterizedTest + @MethodSource("overedOrder") + void checkOverOrder(List<Order> orders) { + Bill bill = Bill.from(1); + + assertThatThrownBy(() -> orders.forEach(bill::add)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.OVER_MAX_ORDER.getMessage()); + } + + static Stream<Arguments> overedOrder() { + return Stream.of( + Arguments.of(List.of( + Order.create("해산물파스타", 7), + Order.create("제로콜라", 15) + )), + Arguments.of(List.of( + Order.create("아이스크림", 25) + )) + ); + } + + @DisplayName("clearOrder 동작 확인") + @Test + void checkClearOrder() { + Bill bill = Bill.from(1) + .add(Order.create("시저샐러드", 3)) + .add(Order.create("해산물파스타", 1)) + .add(Order.create("제로콜라", 2)); + bill.clearOrder(); + assertThat(bill.getAllOrders()).isEqualTo(List.of()); + } + + @DisplayName("getTotalPrice 동작 확인") + @Test + void checkTotalPrice() { + Bill bill = Bill.from(1) + .add(Order.create("타파스", 2)) + .add(Order.create("티본스테이크", 1)) + .add(Order.create("제로콜라", 2)); + assertThat(bill.getTotalPrice()).isEqualTo(72000); + } + + @DisplayName("getTypeCount 동작 확인") + @ParameterizedTest + @MethodSource("typedBill") + void checkTypeCount(Bill bill, MenuType type, int answer) { + assertThat(bill.getTypeCount(type)).isEqualTo(answer); + } + + static Stream<Arguments> typedBill() { + return Stream.of( + Arguments.of( + Bill.from(1) + .add(Order.create("양송이수프", 3)) + .add(Order.create("티본스테이크", 1)) + .add(Order.create("바비큐립", 2)), + MenuType.MAIN, + 3 + ), + Arguments.of( + Bill.from(1) + .add(Order.create("티본스테이크", 2)) + .add(Order.create("초코케이크", 2)) + .add(Order.create("아이스크림", 3)) + .add(Order.create("제로콜라", 7)), + MenuType.DESSERT, + 5 + ) + ); + } + + @DisplayName("getDateValue 동작 확인") + @ParameterizedTest + @ValueSource(ints = {1, 17, 25, 31}) + void checkDateValue(int date) { + assertThat(Bill.from(date).getDateValue()).isEqualTo(date); + } + + @DisplayName("음료만 주문한 경우 예외 발생") + @Test + void checkOnlyDrinkOrder() { + assertThatThrownBy(() -> Bill.from(1) + .add(Order.create("제로콜라", 3)) + .add(Order.create("레드와인", 1)) + .validateOnlyDrink() + ).isInstanceOf(IllegalArgumentException.class).hasMessage(ErrorMessage.ONLY_DRINK_ORDER.getMessage()); + } +}
Java
동작 확인 보다는 시나리오를 적어주면 좋을 것 같아요 타파스 2개, 티본스테이크 1개, 제로콜라 2개의 토탈 주문 금액 72000원을 반환한다 . 약간 이런식으로?
@@ -0,0 +1,456 @@ +# 이메일 답장 + +> 제목: 12월 이벤트 개발 보고 + +> 보낸 사람: 개발팀 <`dev@woowacourse.io`> +> +> 받는 사람: 비즈니스팀 <`biz@woowacourse.io`> + +안녕하세요. 개발팀입니다! + +12월 이벤트 플래너 개발 요청 사항은 잘 받아 보았습니다. +요청하신 내용들을 모두 적용해보았는데요. 혹시 누락된 부분이 있다면 바로 말씀해주시면 감사하겠습니다. + +#### 방문 날짜 입력 + +- 방문 날짜는 1 이상 31 이하의 숫자로만 입력받게 했습니다. +- 단, 사용자의 부주의로 입력 앞뒤로 공백이 생기는 경우가 종종 있는데, 이는 프로그램 내부에서 자동 처리하게 했습니다. + - " 12 " (O) + - " 1 2" (X) +- 이외의 모든 잘못된 입력은 요청하신 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 날짜입니다. 다시 입력해 주세요.` (요청 사항) +- 에러 메시지가 나온 다음에는 다시 재입력 받을 수 있게 했습니다. + +#### 주문 입력 + +- 모든 주문은 "해산물파스타-2,레드와인-1,초코케이크-1" 와 같은 형식으로만 입력받게 했습니다. +- 단, 사용자의 부주의로 입력 사이에 공백이 생기는 경우가 종종 있는데, 이는 프로그램 내부에서 자동 처리하게 했습니다. + - 띄워쓰기가 포함된 메뉴가 없어서 입력의 모든 공백을 허용하게 했습니다. + - "해산물파스타 - 2, 레드와인 - 3" (O) + - "해 산 물 파 스 타 - 1 2 , 레드와인-3" (O) +- 메뉴 형식이 예시와 다른 경우 에러 메시지를 보이게 했습니다. + - "해산물파스타 2, 레드와인 3" (X) + - "해산물파스타: 2, 레드와인: 3" (X) + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 메뉴의 개수를 0 이하의 숫자로 입력하면 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 중복 메뉴를 입력한 경우 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 메뉴판에 없는 메뉴를 입력한 경우 에러 메시지를 보이게 했습니다. + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) +- 메뉴의 개수가 합쳐서 20개를 초과하면 에러 메시지를 보이게 했습니다. + - `[ERROR] 메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다. 다시 입력해 주세요.` (추가) +- 음료만 주문 시, 에러 메시지를 보이게 했습니다. + - `[ERROR] 음료만 주문할 수 없습니다. 다시 입력해 주세요.` (추가) +- 에러 메시지가 나온 다음에는 다시 주문을 재입력 받을 수 있게 했습니다. + +#### 이벤트 + +- 모든 이벤트는 10,000원 이상부터 적용되도록 했습니다. +- 모든 이벤트는 적용 가능하다면 중복으로 적용되도록 했습니다. +- 크리스마스 디데이 할인 + - 기간: 2023.12.01 ~ 2023.12.25 + - 할인 금액: 2023.12.01 1,000원으로 시작하여, 매일 할인 금액이 100원씩 증가 + - 할인 방법: 총 주문 금액에서 할인 금액만큼 할인 +- 평일 할인 + - 기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일 ~ 목요일 + - 할인 금액: 2,023원 + - 할인 방법: 디저트 메뉴를 개당 할인 금액만큼 할인 +- 주말 할인 + - 기간: 2023.12.01 ~ 2023.12.31 중 매주 금요일, 토요일 + - 할인 금액: 2,023원 + - 할인 방법: 메인 메뉴를 개당 할인 금액만큼 할인 +- 특별 할인 + - 기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일, 12월 25일 + - 할인 금액: 1,000원 + - 할인 방법: 총주문 금액에서 할인 금액만큼 할인 +- 증정 이벤트 + - 기간: 2023.12.01 ~ 2023.12.31 + - 이벤트: 할인 전 총주문 금액이 12만원 이상일 때, 샴페인 1개 증정 (25,000원) +- 증정 이벤트는 총혜택 금액에는 포함되지만, 실제 할인 후 예상 결제 금액에는 적용되지 않게 했습니다. +- 나머지 이벤트는 총혜택 금액에도 포함되고 실제 할인에도 적용됩니다. + +#### 이벤트 배지 + +- 5천원 미만: 없음 +- 5천원 이상: 별 +- 1만원 이상: 트리 +- 2만원 이상: 산타 + +#### 결과 출력 + +- 입력한 주문 메뉴를 출력합니다. +- 할인 전 총주문 금액을 출력합니다. +- 증정 메뉴를 출력합니다. 증정 메뉴가 없으면 "없음"을 출력합니다. +- 혜택 내역을 출력합니다. 혜택이 없으면 "없음"을 출력합니다. +- 총혜택 금액을 출력합니다. 혜택이 없으면 0을 출력합니다. +- 할인 후 예상 결제 금액을 출력합니다. +- 12월 이벤트 배지를 출력합니다. 받을 배지가 없으면 "없음"을 출력합니다. + +개발팀 내부에서 여러 상황을 고려해서 많은 테스트를 진행했습니다. +하지만 그럼에도 버그가 있거나 새롭게 추가하고 싶은 기능이 있으시다면 바로 말씀해주세요. + +특히 새로운 이벤트를 추가하거나, 새로운 메뉴를 추가하는 건 언제든 환영입니다! +확장성있게 설계를 해두었기 때문에 편하게 요청하셔도 괜찮습니다! + +감사합니다 :) + +--- + +# 이벤트 내용 + +## 이벤트 종류 + +### 크리스마스 디데이 할인 + +기간: 2023.12.01 ~ 2023.12.25 + +할인 금액: 2023.12.01 1,000원으로 시작하여, 매일 할인 금액이 100원씩 증가 + +할인 방법: 총 주문 금액에서 할인 금액만큼 할인 + +### 평일 할인 + +기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일 ~ 목요일 + +할인 금액: 2,023원 + +할인 방법: 디저트 메뉴를 개당 할인 금액만큼 할인 + +### 주말 할인 + +기간: 2023.12.01 ~ 2023.12.31 중 매주 금요일, 토요일 + +할인 금액: 2,023원 + +할인 방법: 메인 메뉴를 개당 할인 금액만큼 할인 + +### 특별 할인 + +기간: 2023.12.01 ~ 2023.12.31 중 매주 일요일, 12월 25일 + +할인 금액: 1,000원 + +할인 방법: 총주문 금액에서 할인 금액만큼 할인 + +### 증정 이벤트 + +기간: 2023.12.01 ~ 2023.12.31 + +이벤트: 할인 전 총주문 금액이 12만원 이상일 때, 샴페인 1개 증정 (25,000원) + +## 이벤트 배지 + +이벤트로 받은 총혜택 금액에 따라 각기 다른 이벤트 배지를 부여 +(이때 `총혜택 금액 = 할인 금액의 합계 + 증정 메뉴의 가격`으로 계산) + +- 5천원 이상: 별 +- 1만원 이상: 트리 +- 2만원 이상: 산타 + +## 이벤트 주의 사항 + +- 총주문 금액 10,000원 이상부터 이벤트가 적용 +- 음료만 주문 시, 주문할 수 없음 +- 메뉴는 한 번에 최대 20개까지만 주문할 수 있음 (종류가 아닌 개수) + +# 개발 요청 사항 + +- [x] 방문할 날짜 입력 + - [x] 1 이상 31 이하의 숫자만 입력받음 +- [x] 주문할 메뉴와 개수 입력 + - [x] 메뉴판에 있는 메뉴만 입력받음 + - [x] 정해진 형식의 메뉴만 입력받음 + - [x] 메뉴의 개수는 1 이상의 숫자만 입력받음 + - [x] 중복되지 않은 메뉴만 입력받음 +- [x] 주문 메뉴 출력 + - [x] 출력 순서는 자유롭게 출력 +- [x] 할인 전 총주문 금액 출력 +- [x] 증정 메뉴 출력 + - [x] 증정 이벤트에 해당하지 않는 경우 `없음` 출력 +- [x] 혜택 내역 출력 + - [x] 고객에게 적용된 이벤트 내역만 출력 + - [x] 적용된 이벤트가 없는 경우 `없음` 출력 + - [x] 이벤트 출력 순서는 자유롭게 출력 +- [x] 총혜택 금액 출력 + - [x] `총혜택 금액 = 할인 금액의 합계 + 증정 메뉴의 가격` +- [x] 할인 후 예상 결제 금액 출력 + - [x] `할인 후 예상 결제 금액 = 할인 전 총주문 금액 - 할인금액` +- [x] 12월 이벤트 배지 출력 + - [x] 이벤트 배지가 부여되지 않는 경우 `없음` 출력 + +# 입력 예외 사항 + +- [x] 방문할 날짜 입력 예외 + - [x] 1 이상 31 이하의 숫자가 아닌 경우 + - `[ERROR] 유효하지 않은 날짜입니다. 다시 입력해 주세요.` (요청 사항) +- [x] 주문할 메뉴와 개수 입력 + - [x] 메뉴판에 없는 메뉴를 입력 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 메뉴의 개수가 1 이상의 정수가 아닌 경우 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 메뉴의 형식이 정해진 형식을 벗어난 경우 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 중복 메뉴를 입력한 경우 + - `[ERROR] 유효하지 않은 주문입니다. 다시 입력해 주세요.` (요청 사항) + - [x] 메뉴 개수가 20개를 초과한 경우 + - `[ERROR] 메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다. 다시 입력해 주세요.` (추가) + - [x] 음료만 주문한 경우 + - `[ERROR] 음료만 주문할 수 없습니다. 다시 입력해 주세요.` (추가) +- 이외 모든 예외 사항에 `[ERROR]` Prefix 사용 + +# 기능 명세 + +## Config + +- [x] Menu + - [x] 메뉴 이름으로 Menu 찾아 반환 +- [x] MenuType +- [x] ErrorMessage + +## Controller + +- [x] EventController + - [x] 날짜를 입력받아 `Bill`을 생성 + - [x] 주문을 입력받아 `Bill`에 추가 + - [x] 위 두 과정 중 예외가 발생할 경우 반복하여 입력받음 + - [x] 필요한 모든 결과를 출력 + +## Domain + +- [x] Order + - [x] 주문 메뉴와 주문 수량을 저장 + - [x] 1이상의 주문 수량만 사용하도록 검증 + - [x] 가격(`메뉴 가격 x 주문 수량`)을 반환 + - [x] 특정 `Order`와 같은 메뉴인지 확인 + - [x] `OrderDTO` 반환 + - [x] `List<Order>`의 모든 주문 수량을 누적하여 합산 + - [x] `MenuType`을 조건으로 사용할 수 있도록 오버로딩 +- [x] Bill + - [x] 주문 리스트와 날짜를 저장 + - [x] 주문을 추가 + - [x] 중복되는 메뉴가 있는 주문인지 검증 + - [x] 최대 주문수를 넘지 않는지 검증 + - [x] 음료만 주문했는지 검증 + - [x] 주문을 초기화 + - [x] 전체 주문 금액을 계산 + - [x] 특정 타입의 메뉴 주문량을 반환 + - [x] `CheckEventDate`의 메서드 오버로딩 + - [x] 주문 날짜를 반환 +- [x] Date + - [x] 생성을 위한 날짜가 1 ~ 31 범위의 값인지 검증 + - [x] 요일을 확인 + - [x] 주말인지 확인 -> 평일 할인, 주말 할인 + - [x] 달력에 별이 있는 특별한 날인지 확인 -> 특별 할인 + - [x] 크리스마스 이전인지 확인 -> 크리스마스 디데이 할인 + - [x] 첫째날로부터 얼마나 지났는지 확인 -> 크리스마스 디데이 할인 + - [x] 날짜를 반환 +- [x] EventHandler + - [x] 증정 메뉴(샴페인) 존재 여부 + - [x] 혜택 내역 + - [x] 할인 금액 + - [x] 총혜택 금액 +- [x] Event + - [x] 이벤트 조건에 맞는지 확인 + - [x] 이벤트 혜택을 반환 +- [x] Badge + - [x] 가격에 맞는 이벤트 배지를 반환 + +## DTO + +- [x] BenefitDTO -> 혜택 이름, 혜택 금액을 전달하는 객체 +- [x] OrderDTO -> 메뉴 이름, 주문 개수를 전달하는 객체 + +## View + +- [x] InputView + - [x] 날짜 입력 + - [x] 주문 입력 +- [x] OutputView + - [x] 각 제목 출력 + - [x] 주문 메뉴 출력 + - [x] 할인 전 총주문 금액 출력 + - [x] 증정 메뉴 출력 + - [x] 혜택 내역 출력 + - [x] 총혜택 금액 출력 + - [x] 할인 후 예상 결제 금액 출력 + - [x] 이벤트 배지 출력 +- [x] ViewMessage +- [x] ViewTitle + +## Util + +- [x] IntParser +- [x] OrderParser +- [x] RetryExecutor + +# 테스트 코드 + +- [x] Badge + - [x] `getBadgeNameWithBenefitPrice` 동작 확인 + - [x] 0 -> 없음 + - [x] 2500 -> 없음 + - [x] 5000 -> 별 + - [x] 9000 -> 별 + - [x] 10000 -> 트리 + - [x] 17000 -> 트리 + - [x] 20000 -> 산타 + - [x] 50000 -> 산타 +- [x] Bill + - [x] `from` 동작 확인 + - [x] 잘못된 date 값 사용시 예외 발생 -> Date 클래스에서 테스트 + - [x] `add` 동작 확인 + - [x] `add` 중복된 메뉴 입력시 예외 발생 + - [x] `add` 20개 이상 메뉴 입력시 예외 발생 + - [x] 여러 메뉴의 총 수량이 20개 이상인 경우 + - [x] 한 메뉴의 수량이 20개 이상인 경우 + - [x] `clearOrder` 동작 확인 + - [x] `getTotalPrice` 동작 확인 + - [x] `getTypeCount` 동작 확인 + - [x] DESSERT 타입 확인 + - [x] MAIN 타입 확인 + - [x] `getDateValue` 동작 확인 + - [x] 음료만 주문한 경우 예외 발생 + - [x] 이외의 Date 관련 메서드는 Date 클래스에서 테스트 +- [x] Date + - [x] 생성 시 `validate` 동작 확인 + - [x] 1 -> 동작 + - [x] 25 -> 동작 + - [x] 31 -> 동작 + - [x] 생성 시 `validate` 예외 발생 + - [x] -5 -> 예외 발생 + - [x] 0 -> 예외 발생 + - [x] 32 -> 예외 발생 + - [x] 75 -> 예외 발생 + - [x] `isWeekend` 동작 확인 + - [x] 1 -> true + - [x] 8 -> true + - [x] 16 -> true + - [x] 17 -> false + - [x] 25 -> false + - [x] 28 -> false + - [x] `isSpecialDay` 동작 확인 + - [x] 3 -> true + - [x] 25 -> true + - [x] 31 -> true + - [x] 13 -> false + - [x] 22 -> false + - [x] `isNotPassedChristmas` 동작 확인 + - [x] 1 -> true + - [x] 14 -> true + - [x] 25 -> true + - [x] 26 -> false + - [x] 31 -> false + - [x] `timePassedSinceFirstDay` 동작 확인 + - [x] 1 -> 0 + - [x] 18 -> 17 + - [x] 25 -> 24 +- [x] Event + - [x] `getEventName` 동작 확인 + - [x] `isDiscount` 동작 확인 + - [x] `checkCondition` 동작 확인 + - [x] 크리스마스 디데이 할인 -> `isNotPassedChristmas`에서 테스트 + - [x] 평일 할인 -> `isWeekend`에서 테스트 + - [x] 주말 할인 -> `isWeekend`에서 테스트 + - [x] 특별 할인 -> `isSpecialDay`에서 테스트 + - [x] 증정 이벤트 + - [x] 티본스테이크(2) + 아이스크림(2) = 120,000 -> true + - [x] 티본스테이크(2) + 시저샐러드(5) = 150,000 -> true + - [x] 바비큐립(1) + 양송이수프(1) = 60,000 -> false + - [x] `getBenefit` 동작 확인 + - [x] 크리스마스 디데이 할인 + - [x] 1 -> 1000 + - [x] 11 -> 2000 + - [x] 25 -> 3400 + - [x] 평일 할인 + - [x] 양송이수프(1) + 바비큐립(1) -> 0 + - [x] 타파스(1) + 해산물파스타(1) + 초코케이크(2) -> 4046 + - [x] 바비큐립(2) + 초코케이크(2) + 아이스크림(3) -> 10115 + - [x] 주말 할인 + - [x] 양송이수프(2) + 제로콜라(2) -> 0 + - [x] 타파스(1) + 티본스테이크(1) -> 2023 + - [x] 티본스테이크(1) + 바비큐립(2) + 해산물파스타(3) + 제로콜라(6) -> 12138 + - [x] 특별 할인 -> 항상 1000 + - [x] 증정 이벤트 -> 항상 25000 + - [x] 모든 이벤트에서 총주문금액 10000원 이상부터 이벤트 적용 +- [x] EventHandler + - [x] `hasChampagneGift` 동작 확인 -> Event `checkCondition`에서 테스트 + - [x] `getTotalDiscountPrice` 동작 확인 + - [x] 1일, 티본스테이크(2) + 아이스크림(2) -> 5046 + - [x] 3일, 티본스테이크(2) + 아이스크림(2) -> 10292 + - [x] 13일, 해산물파스타(10) + 초코케이크(1) + 아이스크림(2) -> 8269 + - [x] 25일, 크리스마스파스타(2) + 샴페인(2) -> 4400 + - [x] 30일, 시저샐러드(5) + 바비큐립(2) + 티본스테이크(1) + 레드와인(2) -> 6069 + - [x] `getTotalBenefitPrice` 동작 확인 + - [x] 1일, 티본스테이크(2) + 아이스크림(2) -> 30046 + - [x] 3일, 티본스테이크(2) + 아이스크림(2) -> 10292 + - [x] 13일, 해산물파스타(10) + 초코케이크(1) + 아이스크림(2) -> 33269 + - [x] 25일, 크리스마스파스타(2) + 샴페인(2) -> 4400 + - [x] 30일, 시저샐러드(5) + 바비큐립(2) + 티본스테이크(1) + 레드와인(2) -> 31069 + - [x] `getAllBenefit` 동작 확인 + - [x] 1일, 티본스테이크(2) + 아이스크림(1) -> 크리스마스(1000), 주말(4046) + - [x] 3일, 티본스테이크(1) + 아이스크림(4) -> 크리스마스(1200), 평일(8092), 특별(1000) + - [x] 13일, 해산물파스타(10) + 초코케이크(1) + 아이스크림(2) -> 크리스마스(2200), 평일(6069), 증정(25000) + - [x] 25일, 크리스마스파스타(2) + 샴페인(2) -> 크리스마스(3400), 특별(1000) + - [x] 30일, 시저샐러드(5) + 바비큐립(2) + 티본스테이크(1) + 레드와인(2) -> 주말(6069), 증정(25000) +- [x] Order + - [x] `create` 동작 확인 + - [x] 잘못된 메뉴 이름 사용시 예외 발생 -> Menu 클래스에서 테스트 + - [x] 잘못된 count 사용시 예외 발생 + - [x] `getPrice` 동작 확인 + - [x] 타파스(2) -> 11000 + - [x] 바비큐립(3) -> 162000 + - [x] 아이스크림(5) -> 25000 + - [x] `isSameMenu` 동작 확인 + - [x] 타파스, 타파스 -> true + - [x] 레드와인, 레드와인 -> true + - [x] 티본스테이크, 아이스크림 -> false + - [x] 초코케이크, 바비큐립 -> false + - [x] `accumulateCount` 동작 확인 + - [x] 티본스테이크(5) -> 5 + - [x] 양송이수프(3) + 바비큐립(1) + 아이스크림(3) -> 7 + - [x] `accumulateCount` type 사용하여 동작 확인 + - [x] DESSERT, 티본스테이크(2) + 제로콜라(4) -> 0 + - [x] MAIN, 양송이스프(3) + 바비큐립(1) + 해산물파스타(2) + 아이스크림(5) -> 3 +- [x] Menu + - [x] `from` 동작 확인 + - [x] 양송이수프 -> Menu.SOUP + - [x] 해산물파스타 -> Menu.SEAFOOD_PASTA + - [x] 메뉴판에 없는 메뉴 입력시 예외 확인 +- [x] IntParser + - [x] `parseIntOrThrow` 동작 확인 + - [x] "123" -> 123 + - [x] "-123" -> -123 + - [x] "2147483647" -> 2147483647 (최댓값) + - [x] "-2147483648" -> -2147483648 (최솟값) + - [x] 정수형태가 아닌 문자열 입력시 예외 발생 + - [x] ABC + - [x] 12L + - [x] 13.5 + - [x] Integer 범위를 벗어난 문자열 입력시 예외 발생 + - [x] 2147483648 + - [x] -2147483649 + - [x] 999999999999999 +- [x] OrderParser + - [x] `parseOrderOrThrow` 동작 확인 + - [x] "타파스-1,제로콜라-2,티본스테이크-5" -> 타파스(1) + 제로콜라(2) + 티본스테이크(5) + - [x] "타파스 - 1, 제로콜라- 2, 티본 스테이크 -5" -> 타파스(1) + 제로콜라(2) + 티본스테이크(5) + - [x] "티본스테이크-1" -> 티본스테이크(1) + - [x] "해산물파스타-3 , " -> 해산물파스타(3) + - [x] 잘못된 형식의 주문을 입력시 예외 발생 + - [x] "타파스: 1, 제로콜라: 2" + - [x] "타파스-1 제로콜라-2 파스타-3" + - [x] "타파스 1 제로콜라 2 파스타 3" + - [x] "타파스, 제로콜라, 파스타" + - [x] "타파스 -" + - [x] "- 3" +- [x] OutputView + - [x] `printHelloMessage` 동작 확인 + - [x] `printEventPreviewTitle` 동작 확인 + - [x] `printOrder` 동작 확인 + - [x] `printTotalPrice` 동작 확인 + - [x] `printGift` 동작 확인 + - [x] `printAllBenefit` 동작 확인 + - [x] `printBenefitPrice` 동작 확인 + - [x] `printAfterDiscountPrice` 동작 확인 + - [x] `printBadge` 동작 확인
Unknown
클래스별로 예외사항 예시나 기능을 꼼꼼히 작성해서 좋았습니다! 프로그램을 조금 요약해서 정리한 정보도 있으면 좋을 것 같습니다!
@@ -0,0 +1,12 @@ +package christmas.config; + +public class Constant { + public static final int INIT_VALUE = 0; + public static final int FILTER_CONDITION = 0; + public static final int MIN_ORDER = 1; + public static final int MAX_ORDER = 20; + + private Constant() { + // 인스턴스 생성 방지 + } +}
Java
주문 수량에 대한 상수들을 저장하셨는데, 클래스명이 Constant여서 init value 나 filter condition 상수명은 의미가 좀 명확하지 않은 것 같습니다. 타인이 읽기에 용도가 명확하지 않은것 같습니다! 클래스명을 OrderConstatns 와 같이 하면 좋을것 같네요. 최대 주문 갯수를 언제든 정책변경에 따라 바꾸시려고 빼둔 것이라면 패키지 위치를 고려해보는 것도 좋을 것 같습니다.
@@ -0,0 +1,22 @@ +package christmas.config; + +public enum ErrorMessage { + WRONG_DATE("유효하지 않은 날짜입니다."), + WRONG_ORDER("유효하지 않은 주문입니다."), + OVER_MAX_ORDER("메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다."), + ONLY_DRINK_ORDER("음료만 주문할 수 없습니다."); + + private static final String PREFIX = "[ERROR]"; + private static final String SUFFIX = "다시 입력해 주세요."; + private static final String DELIMITER = " "; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.join(DELIMITER, PREFIX, message, SUFFIX); + } +}
Java
저는 `class`로 구현했는데 다른 분들 보고 `enum`으로 구현해보려구요! 열거형으로 구현했을 때만의 장점이 있는 것 같습니다! "에러 모음집에서 이런 에러를 가져오는 구나~" 라고 읽기 더 좋은 것 같아요
@@ -0,0 +1,47 @@ +package christmas.config; + +import java.util.Arrays; + +public enum Menu { + SOUP("양송이수프", 6000, MenuType.APPETIZER), + TAPAS("타파스", 5500, MenuType.APPETIZER), + SALAD("시저샐러드", 8000, MenuType.APPETIZER), + STEAK("티본스테이크", 55000, MenuType.MAIN), + BARBECUE("바비큐립", 54000, MenuType.MAIN), + SEAFOOD_PASTA("해산물파스타", 35000, MenuType.MAIN), + CHRISTMAS_PASTA("크리스마스파스타", 25000, MenuType.MAIN), + CAKE("초코케이크", 15000, MenuType.DESSERT), + ICE_CREAM("아이스크림", 5000, MenuType.DESSERT), + COLA("제로콜라", 3000, MenuType.DRINK), + WINE("레드와인", 60000, MenuType.DRINK), + CHAMPAGNE("샴페인", 25000, MenuType.DRINK); + + private final String menuName; + private final int price; + private final MenuType type; + + Menu(String menuName, int price, MenuType type) { + this.menuName = menuName; + this.price = price; + this.type = type; + } + + public static Menu from(String menuName) { + return Arrays.stream(Menu.values()) + .filter(it -> menuName.equals(it.menuName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage())); + } + + public String getMenuName() { + return menuName; + } + + public int getPrice() { + return price; + } + + public MenuType getType() { + return type; + } +}
Java
```suggestion SOUP("양송이수프", 6_000, MenuType.APPETIZER), ``` 별거 아니지만 가격은 3자리 숫자 마다 '-' 언더바 넣어주시면 가독성에 좋은것같습니다. 실수도 줄여주고요
@@ -0,0 +1,47 @@ +package christmas.config; + +import java.util.Arrays; + +public enum Menu { + SOUP("양송이수프", 6000, MenuType.APPETIZER), + TAPAS("타파스", 5500, MenuType.APPETIZER), + SALAD("시저샐러드", 8000, MenuType.APPETIZER), + STEAK("티본스테이크", 55000, MenuType.MAIN), + BARBECUE("바비큐립", 54000, MenuType.MAIN), + SEAFOOD_PASTA("해산물파스타", 35000, MenuType.MAIN), + CHRISTMAS_PASTA("크리스마스파스타", 25000, MenuType.MAIN), + CAKE("초코케이크", 15000, MenuType.DESSERT), + ICE_CREAM("아이스크림", 5000, MenuType.DESSERT), + COLA("제로콜라", 3000, MenuType.DRINK), + WINE("레드와인", 60000, MenuType.DRINK), + CHAMPAGNE("샴페인", 25000, MenuType.DRINK); + + private final String menuName; + private final int price; + private final MenuType type; + + Menu(String menuName, int price, MenuType type) { + this.menuName = menuName; + this.price = price; + this.type = type; + } + + public static Menu from(String menuName) { + return Arrays.stream(Menu.values()) + .filter(it -> menuName.equals(it.menuName)) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage())); + } + + public String getMenuName() { + return menuName; + } + + public int getPrice() { + return price; + } + + public MenuType getType() { + return type; + } +}
Java
```suggestion public static Menu getMenuBy(String menuName) { ``` 정말 각자 스타일이 달라서 제가 꼭 정답은 아니지만 메서드명 추천드립니다!
@@ -0,0 +1,5 @@ +package christmas.config; + +public enum MenuType { + APPETIZER, MAIN, DESSERT, DRINK +}
Java
카테고리 따로 열거해서 구분하신게 나중에 문자로 비교하는 것보다 안정성 있게 구현하신것 같아요
@@ -0,0 +1,26 @@ +package christmas.domain; + +import java.util.Arrays; + +public enum Badge { + SANTA("산타", 20000), + TREE("트리", 10000), + STAR("별", 5000), + NOTHING("없음", 0); + + private final String badgeName; + private final int threshold; + + Badge(String badgeName, int threshold) { + this.badgeName = badgeName; + this.threshold = threshold; + } + + public static String getBadgeNameWithBenefitPrice(int benefitPrice) { + return Arrays.stream(Badge.values()) + .filter(it -> it.threshold <= benefitPrice) + .map(it -> it.badgeName) + .findFirst() + .orElse(NOTHING.badgeName); + } +}
Java
저도 이렇게 구현했는데 고민하다보니 뱃지가 가진 개념이 `가격` 인지 `범위`인지 취향 차이라고 생각하는데 저는 `범위`가 조금더 뱃지가 가진 개념이라고 생각이 들더라구요 그래서 안에 기준 가격대신 범위를 넣어보는 고민도 해보시면 좋을 것 같습니다.
@@ -0,0 +1,81 @@ +package christmas.domain; + +import christmas.config.ErrorMessage; + +import java.util.Arrays; + +public class Date implements CheckEventDate { + private static final int WEEK_NUM = 7; + private static final int WEEK_DIFF = 4; + private static final int FIRST_DAY = 1; + private static final int LAST_DAY = 31; + private static final int CHRISTMAS = 25; + + private final int date; + + private Date(int date) { + validate(date); + this.date = date; + } + + public static Date from(int date) { + return new Date(date); + } + + private void validate(int date) { + if (date < FIRST_DAY || date > LAST_DAY) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private enum DayOfWeek { + SUN(0), MON(1), TUE(2), WED(3), THU(4), FRI(5), SAT(6); + + private final int value; + + DayOfWeek(int value) { + this.value = value; + } + + public static DayOfWeek from(int value) { + return Arrays.stream(DayOfWeek.values()) + .filter(it -> value == it.value) + .findAny() + .orElse(null); + } + } + + /** + * 2023년 12월을 기준으로 현재 날짜에 맞는 요일을 반환합니다. + * @return DayOfWeek (0: 일요일 ~ 6: 토요일) + */ + private DayOfWeek getDayOfWeek() { + int dayValue = (date + WEEK_DIFF) % WEEK_NUM; + return DayOfWeek.from(dayValue); + } + + @Override + public boolean isWeekend() { + DayOfWeek dayOfWeek = getDayOfWeek(); + return dayOfWeek == DayOfWeek.FRI || dayOfWeek == DayOfWeek.SAT; + } + + @Override + public boolean isSpecialDay() { + return getDayOfWeek() == DayOfWeek.SUN || date == CHRISTMAS; + } + + @Override + public boolean isNotPassedChristmas() { + return date <= CHRISTMAS; + } + + @Override + public int timePassedSinceFirstDay() { + return date - FIRST_DAY; + } + + public int getDateValue() { + return date; + } +}
Java
이 클래스 굉장히 좋은 것 같아요 Date라는 개념도 잘 담겨있고 크리스마스나 시작 요일을 다른 곳에서 받아오는 방식으로 바꾼다면 해당 정보만 갈아끼우면 계속 동작되는 클래스 같아요. java.time 이라는 자바 패키지를 하나 추천해드릴게요 ``` import java.time.LocalDate; import java.time.DayOfWeek; import java.time.format.TextStyle; import java.util.Locale; public class Main { public static void main(String[] args) { // 특정 날짜 설정 LocalDate date = LocalDate.of(2023, 11, 24); // 예: 2023년 11월 24일 // 해당 날짜의 요일을 가져옴 DayOfWeek dayOfWeek = date.getDayOfWeek(); // 요일을 문자열로 출력 (예: 한국어로 짧은 형식) String dayOfWeekInKorean = dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.KOREAN); System.out.println("요일 (한국어): " + dayOfWeekInKorean); } } ```
@@ -0,0 +1,75 @@ +package christmas.domain; + +import christmas.config.Menu; +import christmas.config.MenuType; + +import java.util.function.Function; +import java.util.function.Predicate; + +public enum Event { + CHRISTMAS( + "크리스마스 디데이 할인", + true, + Bill::isNotPassedChristmas, + bill -> bill.timePassedSinceFirstDay() * 100 + 1000 + ), + WEEKDAY( + "평일 할인", + true, + bill -> !bill.isWeekend(), + bill -> bill.getTypeCount(MenuType.DESSERT) * 2023 + ), + WEEKEND( + "주말 할인", + true, + Bill::isWeekend, + bill -> bill.getTypeCount(MenuType.MAIN) * 2023 + ), + SPECIAL( + "특별 할인", + true, + Bill::isSpecialDay, + bill -> 1000 + ), + CHAMPAGNE( + "증정 이벤트", + false, + bill -> bill.getTotalPrice() >= 120000, + bill -> Menu.CHAMPAGNE.getPrice() + ); + + private static final int ALL_EVENT_THRESHOLD = 10000; + + private final String eventName; + private final boolean isDiscount; + private final Predicate<Bill> condition; + private final Function<Bill, Integer> benefit; + + Event( + String eventName, + boolean isDiscount, + Predicate<Bill> condition, + Function<Bill, Integer> benefit + ) { + this.eventName = eventName; + this.isDiscount = isDiscount; + this.condition = condition; + this.benefit = benefit; + } + + public String getEventName() { + return eventName; + } + + public boolean isDiscount() { + return isDiscount; + } + + public boolean checkCondition(Bill bill) { + return condition.test(bill) && bill.getTotalPrice() >= ALL_EVENT_THRESHOLD; + } + + public int getBenefit(Bill bill) { + return benefit.apply(bill); + } +}
Java
오 할인이 적용 되었는지 불린값을 넣어두신 것이 매우 좋아보입니다! 배워갑니다. 해당 내용을 뱃지에도 적용하시면 좋을 것 같습니다.
@@ -0,0 +1,52 @@ +package christmas.util; + +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +public class OrderParser { + private static final String SEQUENCE_DELIMITER = ","; + private static final String ORDER_DELIMITER = "-"; + private static final String ORDER_PATTERN = "[^-]+-[0-9]+"; + private static final String REPLACE_TARGET = " "; + private static final String REPLACEMENT = ""; + + private OrderParser() { + // 인스턴스 생성 방지 + } + + public static List<OrderDTO> parseOrderOrThrow(String orderSequence) { + List<OrderDTO> result = new ArrayList<>(); + for (String order : splitOrder(trimAll(orderSequence))) { + result.add(parseOrderDTO(order)); + } + return result; + } + + private static List<String> splitOrder(String orderSequence) { + return List.of(orderSequence.split(SEQUENCE_DELIMITER)); + } + + private static OrderDTO parseOrderDTO(String order) { + validateOrderPattern(order); + String[] split = order.split(ORDER_DELIMITER); + try { + return new OrderDTO(split[0], IntParser.parseIntOrThrow(split[1])); + } catch (IndexOutOfBoundsException e) { + throw new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage()); + } + } + + private static String trimAll(String target) { + return target.replaceAll(REPLACE_TARGET, REPLACEMENT); + } + + private static void validateOrderPattern(String order) { + if (!Pattern.matches(ORDER_PATTERN, order)) { + throw new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage()); + } + } +}
Java
```suggestion private static final Pattern ORDER_PATTERN = Pattern.compile("[^-]+-[0-9]+"); // 컴파일된 패턴 ```
@@ -0,0 +1,110 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.utils.EventSettings; +import christmas.parser.EventDetailsParser; +import christmas.view.EventView; + +import java.math.BigDecimal; +import java.util.Map; + +public class ChristmasEventController implements EventController { + private static final String WEEKDAY_DISCOUNT_TYPE = "dessert"; + private static final String WEEKEND_DISCOUNT_TYPE = "main"; + private static final DecemberCalendar decemberCalendar = new DecemberCalendar(); + + private boolean canPresent = false; + private BigDecimal totalBenefitAmount = new BigDecimal(0); + private Map<Menu, Integer> orderDetails; + private Badge badge; + private String eventResultDetails = ""; + private BigDecimal beforeEventApplied; + + public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) { + beforeEventApplied = bill.getTotalPrice(); + if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) { + this.orderDetails = order.getOrderDetails(); + presentEvent(bill); + dDayDiscountEvent(reservationDay, bill); + weekdayDiscountEvent(reservationDay, bill); + weekendDiscountEvent(reservationDay, bill); + specialDayDiscountEvent(reservationDay, bill); + badgeEvent(totalBenefitAmount); + } + } + + public void presentEvent(Bill bill) { + if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) { + canPresent = true; + BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount(); + + totalBenefitAmount = totalBenefitAmount.add(benefitValue); + eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue); + } + } + + public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) { + if (reservationDay.dDayDiscountEventPeriod()) { + BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1); + BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount(). + add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay))); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue); + } + } + + public void weekdayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekday(day.getDay())) { + long dessertCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(dessertCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue); + } + } + + public void weekendDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekend(day.getDay())) { + long mainDishCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(mainDishCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue); + } + } + + public void specialDayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isSpecialDay(day.getDay())) { + BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount(); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue); + } + } + + public void badgeEvent(BigDecimal totalBenefitAmount) { + badge = Badge.getBadge(totalBenefitAmount); + } + + public void showEventDiscountDetails(Bill bill) { + EventView.printPriceBeforeDiscount(beforeEventApplied); + EventView.printPresentDetails(canPresent); + EventView.printEventResultDetails(eventResultDetails); + EventView.printTotalBenefitAmount(totalBenefitAmount); + EventView.printPriceAfterDiscount(bill); + EventView.printBadge(badge); + } +}
Java
3주 차 웹 백엔드 공통 피드백으로 필드(인스턴스 변수)의 수를 줄이기 위해 노력한다라는 항목이 있었는데요 중복되는 항목들은 하나의 result로 묶어서 한번 관리를 해보는 건 어떨까요?
@@ -0,0 +1,110 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.utils.EventSettings; +import christmas.parser.EventDetailsParser; +import christmas.view.EventView; + +import java.math.BigDecimal; +import java.util.Map; + +public class ChristmasEventController implements EventController { + private static final String WEEKDAY_DISCOUNT_TYPE = "dessert"; + private static final String WEEKEND_DISCOUNT_TYPE = "main"; + private static final DecemberCalendar decemberCalendar = new DecemberCalendar(); + + private boolean canPresent = false; + private BigDecimal totalBenefitAmount = new BigDecimal(0); + private Map<Menu, Integer> orderDetails; + private Badge badge; + private String eventResultDetails = ""; + private BigDecimal beforeEventApplied; + + public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) { + beforeEventApplied = bill.getTotalPrice(); + if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) { + this.orderDetails = order.getOrderDetails(); + presentEvent(bill); + dDayDiscountEvent(reservationDay, bill); + weekdayDiscountEvent(reservationDay, bill); + weekendDiscountEvent(reservationDay, bill); + specialDayDiscountEvent(reservationDay, bill); + badgeEvent(totalBenefitAmount); + } + } + + public void presentEvent(Bill bill) { + if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) { + canPresent = true; + BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount(); + + totalBenefitAmount = totalBenefitAmount.add(benefitValue); + eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue); + } + } + + public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) { + if (reservationDay.dDayDiscountEventPeriod()) { + BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1); + BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount(). + add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay))); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue); + } + } + + public void weekdayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekday(day.getDay())) { + long dessertCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(dessertCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue); + } + } + + public void weekendDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekend(day.getDay())) { + long mainDishCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(mainDishCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue); + } + } + + public void specialDayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isSpecialDay(day.getDay())) { + BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount(); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue); + } + } + + public void badgeEvent(BigDecimal totalBenefitAmount) { + badge = Badge.getBadge(totalBenefitAmount); + } + + public void showEventDiscountDetails(Bill bill) { + EventView.printPriceBeforeDiscount(beforeEventApplied); + EventView.printPresentDetails(canPresent); + EventView.printEventResultDetails(eventResultDetails); + EventView.printTotalBenefitAmount(totalBenefitAmount); + EventView.printPriceAfterDiscount(bill); + EventView.printBadge(badge); + } +}
Java
개인적인 생각으로는 컨트롤러에서 도메인에서 해야 할 역할들을 많이 가지고 있는 것 같아요 이런 계산이나 할인에 대한 내용들은 따로 이 역할을 담당하는 객체를 만들어서 그곳에서 스스로 일을 할 수 있도록 객체지향적으로 설계해 보는 건 어떨까요?
@@ -0,0 +1,110 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.utils.EventSettings; +import christmas.parser.EventDetailsParser; +import christmas.view.EventView; + +import java.math.BigDecimal; +import java.util.Map; + +public class ChristmasEventController implements EventController { + private static final String WEEKDAY_DISCOUNT_TYPE = "dessert"; + private static final String WEEKEND_DISCOUNT_TYPE = "main"; + private static final DecemberCalendar decemberCalendar = new DecemberCalendar(); + + private boolean canPresent = false; + private BigDecimal totalBenefitAmount = new BigDecimal(0); + private Map<Menu, Integer> orderDetails; + private Badge badge; + private String eventResultDetails = ""; + private BigDecimal beforeEventApplied; + + public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) { + beforeEventApplied = bill.getTotalPrice(); + if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) { + this.orderDetails = order.getOrderDetails(); + presentEvent(bill); + dDayDiscountEvent(reservationDay, bill); + weekdayDiscountEvent(reservationDay, bill); + weekendDiscountEvent(reservationDay, bill); + specialDayDiscountEvent(reservationDay, bill); + badgeEvent(totalBenefitAmount); + } + } + + public void presentEvent(Bill bill) { + if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) { + canPresent = true; + BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount(); + + totalBenefitAmount = totalBenefitAmount.add(benefitValue); + eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue); + } + } + + public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) { + if (reservationDay.dDayDiscountEventPeriod()) { + BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1); + BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount(). + add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay))); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue); + } + } + + public void weekdayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekday(day.getDay())) { + long dessertCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(dessertCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue); + } + } + + public void weekendDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekend(day.getDay())) { + long mainDishCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(mainDishCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue); + } + } + + public void specialDayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isSpecialDay(day.getDay())) { + BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount(); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue); + } + } + + public void badgeEvent(BigDecimal totalBenefitAmount) { + badge = Badge.getBadge(totalBenefitAmount); + } + + public void showEventDiscountDetails(Bill bill) { + EventView.printPriceBeforeDiscount(beforeEventApplied); + EventView.printPresentDetails(canPresent); + EventView.printEventResultDetails(eventResultDetails); + EventView.printTotalBenefitAmount(totalBenefitAmount); + EventView.printPriceAfterDiscount(bill); + EventView.printBadge(badge); + } +}
Java
하나의 함수에서 다양한 일을 하고 있는 것 같은데 기능을 분리해 보는 건 어떨까요?
@@ -0,0 +1,26 @@ +package christmas.controller; + +import christmas.domain.Bill; +import christmas.domain.Order; +import christmas.domain.ReservationDay; + +import java.math.BigDecimal; + +public interface EventController { + + void applyEvent(ReservationDay day, Order order, Bill bill); + + void showEventDiscountDetails(Bill bill); + + void presentEvent(Bill bill); + + void dDayDiscountEvent(ReservationDay reservationDay, Bill bill); + + void weekdayDiscountEvent(ReservationDay day, Bill bill); + + void weekendDiscountEvent(ReservationDay day, Bill bill); + + void specialDayDiscountEvent(ReservationDay day, Bill bill); + + void badgeEvent(BigDecimal totalBenefitAmount); +}
Java
EventController를 interface로 만들어서 이벤트에 대한 로직을 관리하는 것보다 이벤트 관련 도메인을 interface로 만들어서 사용해 보는 건 어떨까요? 객체지향을 다룬 오브젝트 서적에서 비슷한 내용이 있어서 링크 남깁니다. https://github.com/eternity-oop/object/tree/master/chapter13/src/main/java/org/eternity/movie/step02
@@ -0,0 +1,32 @@ +package christmas.domain; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.*; + +class BadgeTest { + + @Test + @DisplayName("산타_뱃지_경계값_테스트") + void getBadge_SantaBadgeAmount_ShouldReturnSantaBadge() { + BigDecimal santaBadgeAmount = new BigDecimal(20000); + assertEquals(Badge.SANTA_BADGE, Badge.getBadge(santaBadgeAmount)); + } + + @Test + @DisplayName("트리_뱃지_경계값_테스트") + void getBadge_BetweenTreeAndSantaAmount_ShouldReturnTreeBadge() { + BigDecimal betweenTreeAndSantaAmount = new BigDecimal(15000); + assertEquals(Badge.TREE_BADGE, Badge.getBadge(betweenTreeAndSantaAmount)); + } + + @Test + @DisplayName("별_뱃지_경계값_테스트") + void getBadge_StarBadgeAmount_ShouldReturnStarBadge() { + BigDecimal starBadgeAmount = new BigDecimal(5000); + assertEquals(Badge.STAR_BADGE, Badge.getBadge(starBadgeAmount)); + } +}
Java
import static org.junit.jupiter.api.Assertions.*; 를 사용하기보다 더 간편하게 테스트를 할 수 있는 import static org.junit.jupiter.api.Assertions.*;를 사용해 보는 건 어떨까요? https://jwkim96.tistory.com/168