code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | countryList 컴포넌트를 보니, 단순 UI만 제공하는 것이 아닌 핵심 로직들을 전부 다 가지고 있는 것으로 보입니다.
파일명으로만 보았을땐, UI 역할만 하고 있을 것으로 추측되었는데 재활용 가능한 컴포넌트는 아닌 것 같아서요~
개인적인 의견으로는 List에는 단순 내려준 데이터를 노출하게만 하고, 비즈니스 로직은 위에서 전달해주는 것이 어떤지 코멘트 드립니다! |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ retu... | TypeScript | 별로 중요한 것은 아니지만 ㅎㅎ
throw new Error() 요기에 뭔가를 넣어주시면 좋아요
```javascript
throw new Error(error.response?.data.message);
```
이런식으로요 ㅎㅎ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 필터를 하기 위한 의도로 setCountries 를 만들어 값을 변경하고 있는 것으로 보입니다!
favoriteCountries 라는 상태를 따로 지니고 있기에 countries를 변경하는 것보다 아래에서 filter만 해주는 로직으로 변경하는 것이 어떨지 제안 드립니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 이것도 아주 사소한 거지만 ㅎㅎ
isDone 보다 isFavorite 이 알기 쉬울것 같아용ㅎㅎ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 동일합니다! |
@@ -0,0 +1,18 @@
+import CountryList from "../components/CountryList";
+
+const Home = () => {
+ return (
+ <>
+ <h1 className="flex justify-center items-center mt-8 mb-8 text-2xl font-bold">
+ Favorite Countries
+ </h1>
+ <CountryList isDone={true} />
+ <h1 className="flex justify-center... | Unknown | h1이 너무 많습니다! 페이지에 하나만 존재해야합니다.
하지만 코드에서도 혼란을 야기할 수 있는 헤딩태그를 지양하는 것을 제안드립니다 :) |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ retu... | TypeScript | 제가 이번에 스스로 써본건 처음이라 잘 몰랐는데 은님 코드 보면서 깨달았습니다 감삼댜 |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 아마 공부를 위해서 하신 듯 합니다만..!
zustand 스토어에 countries 와 favoriteCountries 가 있고 실제로
```javascript
const isDoneCountries = isDone ? favoriteCountries : countries;
```
이런 부분에서도 useQuery 의 data 를 따로 쓰지는 않으니, 이런 경우라면 tanstack을 안쓰는 방향도 있을 것 같습니다~
물론 공부용이기 때문에 무시하셔도 됩니다 ^^;; |
@@ -0,0 +1,28 @@
+import { Country } from "../types/country";
+
+const CountryCard = ({
+ country,
+ handleToggleCountry,
+}: {
+ country: Country;
+ handleToggleCountry: (country: Country) => void;
+}) => {
+ return (
+ <div
+ className="flex flex-col border rounded gap-2 px-4"
+ onClick={() => handl... | Unknown | 아 그냥..h1밑에 하위로 있다 생각해서 아무 생각없이 h2를 쓴겁니다.. 그렇군여.. html css에 대해서 따로 공부를 안하고 필요할 때마다 그냥 그 때 그때 쓰다보니 이런 부분이 아직 많이 미흡한듯하네여 후... |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 오오 같은 생각입니다~~ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 맞는 말씀입니다 훨씬 좋겟군여 |
@@ -0,0 +1,18 @@
+import CountryList from "../components/CountryList";
+
+const Home = () => {
+ return (
+ <>
+ <h1 className="flex justify-center items-center mt-8 mb-8 text-2xl font-bold">
+ Favorite Countries
+ </h1>
+ <CountryList isDone={true} />
+ <h1 className="flex justify-center... | Unknown | h1태그는 페이지당 1개만 써야하는지 몰랐네여... 명심하겠습니당 |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ retu... | TypeScript | 주의 :: 타입스크립트 잘 몰라서 이상한 소리일 수 있습니다 ㅠ
getCountires 함수의 반환값이 Promise<Country[]>임을 명시해주고 계시는 것 같습니다.
저는 이번 API 구조가 복잡해서인지 무슨 에러였는지 자세히 기억은 안 나지만 에러를 계속 겪었습니다~!
try문 안에서 get 요청 부분을 보면 응답값의 타입 지정이 안 되어 있는데, 저는 이 부분에서 문제를 해결할 수 있었던 것으로 기억합니다!
`const response = await countryApi.get<Country[]>("/all");`
예를 들어서 dat... |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 홈페이지 관련해서 적어주신 것처럼 태그 이름을 바꾸는게 좋다는 말씀이신가요? |
@@ -0,0 +1,28 @@
+import { Country } from "../types/country";
+
+const CountryCard = ({
+ country,
+ handleToggleCountry,
+}: {
+ country: Country;
+ handleToggleCountry: (country: Country) => void;
+}) => {
+ return (
+ <div
+ className="flex flex-col border rounded gap-2 px-4"
+ onClick={() => handl... | Unknown | 참고:
- https://techblog.woowahan.com/15541/
- https://webactually.com/2020/03/03/%3Csection%3E%EC%9D%84-%EB%B2%84%EB%A6%AC%EA%B3%A0-HTML5-%3Carticle%3E%EC%9D%84-%EC%8D%A8%EC%95%BC-%ED%95%98%EB%8A%94-%EC%9D%B4%EC%9C%A0/ |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 그 생각은 못해봤는데 동일한 결과가...나오는지 해보겠습니다 ㅎㅎ... 한번의 동작으로 아 조건문을 개선하면 되겠군여! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 이건 제가 뭐 말씀하시는지 잘 몰라서...학습하겠습니다 ㅠ.. |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 이 부분은 home.tsx에서는 전체적인 UI 및 페이지 관련만 나타내고 List에서 Card를 핸들링 할 수 있도록 생각을 해서 로직을 구현했는데 이런 핸들링 로직은 home.tsx가 더 적절하단 말씀이실까여?? |
@@ -0,0 +1,15 @@
+import axios from "axios";
+import { Country } from "../types/country";
+
+export const countryApi = axios.create({
+ baseURL: "https://restcountries.com/v3.1",
+});
+
+export const getCountries = async (): Promise<Country[]> => {
+ try {
+ const response = await countryApi.get("/all");
+ retu... | TypeScript | 아 그렇군여! 저는 일단 js하듯이 작성 한 후에 strict모드가 설정 되어있으니 ts에서 새로 발생한 오류에 맞춰 수정했어가지고 반환값만 명시하고 오류가 사라졌길래 그 부분은 미처 생각을 못했습니다.
아무래도 모든 값에 정확한 타입을 명시하는건 저도 해야겠다 생각했는데 감사합니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | prop 타입을 인라인으로 정의한 이유가 있는지 궁금합니다! |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 아...원래 data로 mpa을 돌렸었는데...;; 이게 isDone값을 꼭 써보려고 노력하다보니 어쩌다 그렇게 되었습니다 ㅠㅠ... 말씀대로 지금 쿼리가 초기값 넣어주는거말고 딱히 안쓰이긴합니다.. |
@@ -0,0 +1,66 @@
+import { useQuery } from "@tanstack/react-query";
+import { getCountries } from "../api/countryAPI";
+import CountryCard from "./CountryCard";
+import { useEffect } from "react";
+import { Country } from "../types/country";
+import useCountryStore from "../zustand/countryStore";
+
+const CountryList =... | Unknown | 저도 궁금합니다..!!! |
@@ -0,0 +1,84 @@
+export interface Country {
+ name: {
+ common: string;
+ official: string;
+ nativeName: {
+ [key: string]: {
+ official: string;
+ common: string;
+ };
+ };
+ };
+ tld: string[];
+ cca2: string;
+ ccn3: string;
+ cca3: string;
+ cioc: string;
+ independent:... | TypeScript | 저도 사실 모든 데이터를 다 보지 않았지만, 몇몇 데이터는 선택적으로 들어오는 것 같더라구요..!! 그래서 모든 데이터에 다 들어오는 것이 아니라면 옵셔널을 붙여주면 좋을 것 같습니다..!! |
@@ -0,0 +1,185 @@
+package pairmatching.controller;
+
+import java.util.function.Function;
+import org.mockito.internal.util.Supplier;
+import pairmatching.enums.Course;
+import pairmatching.enums.Crew;
+import pairmatching.enums.Functions;
+import pairmatching.enums.Level;
+import pairmatching.enums.Missions;
+import ... | Java | ```suggestion
if (Functions.isEquals(input, Functions.QUIT)) {
performFunctions(input, inputView);
return
}
```
사소한거지만 return을 사용한다면 아래에 if문을 안만들고 처리할 수 있었을 거 같아요 |
@@ -0,0 +1,34 @@
+package pairmatching.model;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class Pairs {
+
+ private Map<String, List<String>> pairs;
+
+ public Pairs(Map<String, List<String>> pair){
+ this.pairs = pair;
+ }
+
+ public Set<Map.Entry<String, List<S... | Java | for-each와 string Joiner를 써서 해결했어도 됐을거 같아요! |
@@ -54,11 +54,20 @@ export const REVIEW_GROUP_API_PARAMS = {
},
};
+export const WRITTEN_REVIEW_PARAMS = {
+ resource: 'reviews/authored',
+ queryString: {
+ lastReviewId: 'lastReviewId',
+ size: 'size',
+ },
+};
+
export const REVIEW_WRITING_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_WRITING_API_PARA... | TypeScript | ```suggestion
if (!lastReviewId) return defaultEndpoint;
return defaultEndpoint + '&' + `${WRITTEN_REVIEW_PARAMS.queryString.lastReviewId}=${lastReviewId}`;
},
```
이런 구조로 바꾸면 lastReviewId가 없을 때 endpoint 값을 파악하는데 더 쉬울 것 같네요 |
@@ -6,11 +6,17 @@ import {
GroupedSection,
GroupedReviews,
ReviewInfoData,
+ WrittenReviewList,
} from '@/types';
import createApiErrorMessage from './apiErrorMessageCreator';
import endPoint from './endpoints';
+export interface GetInfiniteReviewListApiParams {
+ lastReviewId: number | null;
+ size:... | TypeScript | 함수의 파라미터 타입이라서, 저는 이럴 때 타입명 뒤에 params를 추가하는 편이에요. |
@@ -0,0 +1,57 @@
+import { useGetDetailedReview, useReviewId } from '@/hooks';
+import { substituteString } from '@/utils';
+
+import QuestionAnswerSection from './QuestionAnswerSection';
+import ReviewDescription from './ReviewDescription';
+import * as S from './styles';
+
+interface DetailedReviewProps {
+ $layoutS... | Unknown | sections 관련된 부분 코드가 길어서, header와 questions를 분리하고 각각 useMemo를 사용하는 것은 어떨까요'? |
@@ -6,11 +6,17 @@ import {
GroupedSection,
GroupedReviews,
ReviewInfoData,
+ WrittenReviewList,
} from '@/types';
import createApiErrorMessage from './apiErrorMessageCreator';
import endPoint from './endpoints';
+export interface GetInfiniteReviewListApiParams {
+ lastReviewId: number | null;
+ size:... | TypeScript | 아이고 놓쳤네요 😅 추가할게요! |
@@ -0,0 +1,57 @@
+import { useGetDetailedReview, useReviewId } from '@/hooks';
+import { substituteString } from '@/utils';
+
+import QuestionAnswerSection from './QuestionAnswerSection';
+import ReviewDescription from './ReviewDescription';
+import * as S from './styles';
+
+interface DetailedReviewProps {
+ $layoutS... | Unknown | 만약 이 컴포넌트를 리팩토링한다면 저는 useMemo를 아예 뺄 것 같아요. 이점에 비해 코드가 복잡해지는 단점이 큰 것 같아서요. 제거하는 방향에 대해서는 어떻게 생각하시나요?
1. 리뷰는 수정 불가능하므로 리뷰이 이름 문자열 치환도 1번만 일어남
2. `substituteString`은 useMemo를 사용할 만큼 비싼 동작이 아님
3. 1과 같은 맥락에서, 어차피 리뷰는 갱신되지 않기 때문에 유저도 리뷰 상세 페이지를 계속 새로고침해서 리렌더링을 추가로 트리거할 것 같지 않음 |
@@ -6,11 +6,17 @@ import {
GroupedSection,
GroupedReviews,
ReviewInfoData,
+ WrittenReviewList,
} from '@/types';
import createApiErrorMessage from './apiErrorMessageCreator';
import endPoint from './endpoints';
+export interface GetInfiniteReviewListApiParams {
+ lastReviewId: number | null;
+ size:... | TypeScript | 우리의 코드 컨벤션~ 잊지 말아요~

근데 확인해보니 안 붙인 함수들이 꽤나 있네요😂 |
@@ -0,0 +1,57 @@
+import { useGetDetailedReview, useReviewId } from '@/hooks';
+import { substituteString } from '@/utils';
+
+import QuestionAnswerSection from './QuestionAnswerSection';
+import ReviewDescription from './ReviewDescription';
+import * as S from './styles';
+
+interface DetailedReviewProps {
+ $layoutS... | Unknown | useMemo는 기존 코드에 적용되어있었기 때문이라, 필요가 없다고 느낀다면 사용하지 않아도 돼요. 저의 코멘트는 '긴 코드를 분리해 가독성을 높여보자'에 초점이 있던거라서요. |
@@ -54,11 +54,20 @@ export const REVIEW_GROUP_API_PARAMS = {
},
};
+export const WRITTEN_REVIEW_PARAMS = {
+ resource: 'reviews/authored',
+ queryString: {
+ lastReviewId: 'lastReviewId',
+ size: 'size',
+ },
+};
+
export const REVIEW_WRITING_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_WRITING_API_PARA... | TypeScript | `if (!lastReviewId) defaultEndpoint;`
에 early return이 빠졌네요 |
@@ -0,0 +1,66 @@
+package christmas.domain;
+
+import static christmas.exception.ErrorMessage.DAY_NOT_IN_RANGE;
+import static christmas.exception.ErrorMessage.ENDS_WITH_DELIMITER;
+
+import christmas.domain.constant.EventConstraint;
+import christmas.exception.OrderException;
+
+public class Day {
+ private final i... | Java | EventConstraint에서 선언한 상수를 가져다 쓰지 않은 이유가 있나요? |
@@ -0,0 +1,64 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import christmas.domain.constant.EventConstraint;
+import christmas.exception.ErrorMessage;
+import christmas.exception.OrderException;
+import o... | Java | @ParamiterizedTest의 어노테이션을 활용해서 중복을 줄일 수 있을거 같습니다. |
@@ -0,0 +1,89 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public ... | Java | order를 do 내부에서 선언하는 것이 더 깔끔하지 않을까 생각이 드네요..!
checkEnd() 내부의 updateStore() 를 do 구문 내부로 이동시킨다면 가능할 것 같습니다..! |
@@ -0,0 +1,59 @@
+package store.model;
+
+import static store.utils.ErrorMessage.INVALID_FORMAT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Order {
+ private List<Product> order;
+
+ public Order(String inputOrder) {
+ validateProductFormat(inputOrder);
+ this.order = gen... | Java | replaceAll() 이라는 메서드로도 같은 기능을 구현할 수 있습니다!
이미 아실수도 있지만 혹시나 해서 말씀드립니다..! |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ priv... | Java | `now.after(startDate) && now.before(endDate)` 도 같은 의미인데
현재 코드처럼 작성하신 이유가 있으실까요?
궁금해서 질문드립니다..! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | 파일명을 상수로 사용한다면 더 좋을 것 같습니다! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | 리팩토링한다면 여기 상품의 수량을 구하는 부분을
하나의 메서드로 분리하시는 것도 좋겠네요 |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | 자바 파일 입출력에 여러 방법이 있는데 버퍼리드 형식을 사용하신 이유가 있으실까요?? |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | 해당 메서드는 서비스가 하는 기능 보다는 다른 클래스로 옮기는게 더 적합해보입니다..! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | 이 부분도 나중에 receiptservice로 분류하면 어떨까요..? |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | Math.min을 사용하시면 한줄로 만들수있을거같아요 |
@@ -0,0 +1,14 @@
+package store.utils;
+
+public class ErrorMessage {
+ public static final String ERROR = "[ERROR] ";
+ public static final String RETRY = " 다시 입력해 주세요.";
+ public static final String INVALID_FORMAT = " 올바르지 않은 형식으로 입력했습니다. ";
+ public static final String INVALID_NAME = " 존재하지 않는 상품입니다.";
+... | Java | enum을 사용하지 않고 class로 분리한 이유가 궁금합니다 |
@@ -0,0 +1,89 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public ... | Java | 함수명은 동사로 하는 건 어떨까요?? 예를 들어 `calculatePrice` 처럼 말이죠!! |
@@ -0,0 +1,91 @@
+package store.model;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class Store {
+ private final String name;
+ private int price;
+ private int quantity;
+ private String promotion;
+
+ public Store(String name, int price, int quantity, String promotion) {
+ this... | Java | 각각의 인덱스가 어떤 것을 의미하는지 상수화 했으면 더 좋았을 것 같습니다!!! |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ priv... | Java | 문자열을 프로모션으로 파싱하는 역할을 파싱하는 객체를 만들어서 거기로 넘기는건 어떨까요!! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | answer을 enum 상수로 만드는 것은 어떨까요? |
@@ -0,0 +1,59 @@
+package store.model;
+
+import static store.utils.ErrorMessage.INVALID_FORMAT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Order {
+ private List<Product> order;
+
+ public Order(String inputOrder) {
+ validateProductFormat(inputOrder);
+ this.order = gen... | Java | 개인적으로 위의 앞 뒤 [ ] 확인하는 부분과 빈문자열인지 확인하는 로직을 분리해도 될 것 같습니다! |
@@ -0,0 +1,50 @@
+package store.model;
+
+public class Receipt {
+ private String name;
+ private int individualPrice;
+ private int quantity;
+ private int promotionQuantity;
+ private int promotionBuy;
+
+ public Receipt(String name, int individualPrice, int quantity, int promotionBuy) {
+ th... | Java | 이번 과제에서 게터 사용을 줄이기가 쉽지 않아, 저도 결국 사용할 수밖에 없었습니다ㅜㅜ
게터를 사용하면 객체의 캡슐화를 위반할 위험이 있고, 객체의 상태를 외부에서 쉽게 변경할 수 있게 되어 객체의 책임이 외부로 밀려날 수 있기 때문에 지양해야 한다고 알고 있습니다.
그래서 앞으로 게터 사용을 줄이기 위해 DTO를 활용해보는 것도 좋은 방법이 될 것 같습니다! |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | 서비스에서 View를 호출하는건 개인적으로 layered architecture구조상 적합하지 않다고 생각됩니다!
Layered architecture는 관심사별로 계층을 나눈 구조로 알고 있습니다. Presentation Layer 는 사용자와의 상호작용을 담당하는 역할, business Layer 는 비지니스 로직만 담당하는 역할입니다. 따라서 View 객체들은 presentation layer 에 속한다고 볼 수 있습니다.
하지만 현재 코드를 보면 business layer 가 presentation layer 를 의존하는 것으로 보이는데, 이렇게... |
@@ -0,0 +1,86 @@
+package store.view;
+
+import static store.utils.ErrorMessage.ERROR;
+import static store.utils.ErrorMessage.RETRY;
+
+import java.util.List;
+import store.model.Receipt;
+import store.model.Store;
+
+public class OutputView {
+ private static final String ERROR_ANSWER = "[ERROR] 잘못된 입력입니다. 다시 입력해 ... | Java | 이 부분을 상수로 처리하지 않은 이유가 있을까요? |
@@ -0,0 +1,89 @@
+package store.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.model.Order;
+import store.model.Promotion;
+import store.model.Receipt;
+import store.model.Store;
+import store.service.StoreService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public ... | Java | do while문을 처음 사용해서 잘 몰랐는데 안에서 선언하는 방법은 생각도 못했네요 배워갑니다! |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ priv... | Java | 가독성이 더 좋다고 생각되는 방향으로 작성했습니다 |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | readLine() 을 사용하여 한 줄씩 읽기 좋다고 생각하여 사용했습니다 |
@@ -0,0 +1,14 @@
+package store.utils;
+
+public class ErrorMessage {
+ public static final String ERROR = "[ERROR] ";
+ public static final String RETRY = " 다시 입력해 주세요.";
+ public static final String INVALID_FORMAT = " 올바르지 않은 형식으로 입력했습니다. ";
+ public static final String INVALID_NAME = " 존재하지 않는 상품입니다.";
+... | Java | 값들을 그룹화 하여 사용하지 않고 단순 메세지 출력이기에 상수 클래스로 해도 좋을 것 같다고 생각했습니다 |
@@ -0,0 +1,73 @@
+package store.model;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+public class Promotion {
+ private String name;
+ private int buy;
+ priv... | Java | 역할 분리를 좀 더 상세히 해야 될 것 같네요.. 참고하겠습니다! |
@@ -0,0 +1,50 @@
+package store.model;
+
+public class Receipt {
+ private String name;
+ private int individualPrice;
+ private int quantity;
+ private int promotionQuantity;
+ private int promotionBuy;
+
+ public Receipt(String name, int individualPrice, int quantity, int promotionBuy) {
+ th... | Java | 말씀하신 내용 듣고 제 코드를 다시 살펴보니, 객체내에서는 단순히 데이터만 담아두고 게터 사용으로 대부분 외부에서 로직을 처리하여 객체지향의 의미를 잃은 코드를 작성한 것 같습니다...
구현하는데 너무 급급했던거같네요ㅠㅠ 피드백 감사합니다 |
@@ -0,0 +1,294 @@
+package store.service;
+
+import static store.model.Promotion.parsePromotions;
+import static store.model.Store.*;
+import static store.utils.ErrorMessage.INVALID_INPUT;
+import static store.utils.ErrorMessage.INVALID_NAME;
+import static store.utils.ErrorMessage.INVALID_QUANTITY;
+
+import java.io.B... | Java | OutputView 클래스에서 유일하게 작성한 스태틱 메서드 입니다.
저도 구현하는 과정에서 옳지 않다고 생각했지만,
비즈니스 로직을 처리하는 과정에서 옳지 않은 입력이 왔을 때 outputView 객체를 참조 할 방법이 떠오르지 않아 이렇게 작성하게 됐습니다..
적합하지 않은 이유를 상세하게 말씀해 주셔서 새롭게 하나 더 배워갑니다 감사합니다..! |
@@ -26,11 +26,32 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
- compileOnly 'org.projectlombok:lombok'
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ ... | Unknown | Gradle 형식이 일치하지 않습니다.
다른 곳과 동일하게 조정해주세요.
```groovy
implementaion 'io.jsonwebtoken:jjwt-api:0.11.5'
``` |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transacti... | Java | `@Transactional` 어노테이션을 클래스 레벨로 올리는게 맞는지에 대해서는 의문이 듭니다.
- DB에 접근하지 않는 메서드를 수행할 때도 `@Transactional` 에 의해 앞뒤로 추가 로직이 실행되며.
- readonly 가 아닌 경우엔 아래에서 어차피 또 사용하는지라 불필요한 코드가 늘어나는게 아닌가 싶습니다. |
@@ -0,0 +1,30 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import java.util.List;
+
+import io.study.springbootlayered.api.member.domain.entity.AuthorityType;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.entity.MemberAuthori... | Java | Gradle 설정에 의하면 Java 버전이 21인데, 충분히 Record로 대체 가능한 코드로 보입니다. |
@@ -0,0 +1,30 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import java.util.List;
+
+import io.study.springbootlayered.api.member.domain.entity.AuthorityType;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.entity.MemberAuthori... | Java | Validation 을 사용해서 빈값이 들어오지 않도록 하면 좋겠네요. |
@@ -0,0 +1,19 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import lombok.AccessLevel;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberPasswordResetDto {
+
... | Java | 필드가 두개인데 굳이 빌더를 사용해야 하나 싶은데요,
당장 바로 아래의 MemberSigninDto 에서는 `@Builder`가 없네요. |
@@ -0,0 +1,19 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import lombok.AccessLevel;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberPasswordResetDto {
+
... | Java | 모든 Dto가 내부적으로 또 Dto를 갖고 있는 이상한 구조네요...
그냥 서로 다른 파일로 분리하는게 가독성 측면에서 더 낫지 않을까요?
특히나 내부적으로 같은 이름을 쓰고 있기 때문에, 행여나 실수로 Static Import를 하는 순간 이게 어디에서 온건지 파악할 방법이 아예 없어집니다. |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transacti... | Java | 결국 `SpecialCharactes` 와 `ValidCharacters` 의 조합으로 구성된다고 볼 수 있겠네요.
- 어차피 문자열 섞는건 똑같습니다.
```java
private String createRandomString(String baseStr, int length) {
return random.ints(length, 0, baseStr.length())
.mapToObj(baseStr::charAt)
.collect(StringBuilder::new, StringBuilde... |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transacti... | Java | 매번 Random 객체를 생성하지 말고, 그냥 최상단에 private final 로 올려버리세요.
`private final Random random = new SecureRandom();` |
@@ -0,0 +1,32 @@
+package io.study.springbootlayered.api.member.application;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dt... | Java | 인라인 주석은 // 가 좋겠죠? |
@@ -0,0 +1,23 @@
+package io.study.springbootlayered.api.member.domain.entity;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Embeddable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+@Embeddable
+@Getter
+@EqualsAndHashCode
+public class MemberPassword {
+
+ @Column(name = "password... | Java | 위에는 Equals와 hashCode를 직접 정의하더니, 이번에는 롬복을 사용하네요? |
@@ -0,0 +1,42 @@
+package io.study.springbootlayered.api.member.domain.event;
+
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.event.TransactionalEventListener;
+
+import io.study.springbootlayered.infra.mail.MailService... | Java | 일반적으로 개발 환경에서는 log level을 debug로, 운영 환경에서는 info/warn 수준으로 설정합니다.
운영 환경에서 해당 요청이 들어올 "때 마다" 해당 로그가 출력되게 되면, 에러 디버깅 과정에서 매우 번거로워질 확률이 높습니다.
개발 과정에서의 디버깅용인지, 운영 환경에서 실제로 필요한 로그인지 잘 생각해보시고 로그 레벨을 지정하는게 좋습니다. |
@@ -0,0 +1,15 @@
+package io.study.springbootlayered.api.member.domain.event;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+@Getter
+@RequiredArgsConstructor
+public class SignupEvent {
+
+ private final String email;
+
+ public static SignupEvent of(String email) {
+ return new Signu... | Java | 생성자랑 역할이 똑같네요. |
@@ -0,0 +1,63 @@
+package io.study.springbootlayered.api.member.domain;
+
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Component;
+
+import io.study.springbootlayered.api.member.domain.dto.MemberDetailDto;
+import io.study.springbootlayered.api.member.doma... | Java | ~~Impl 형식의 클래스의 존재 여부를 이해하긴 어렵네요.
- 다른 구현체의 가능성이 존재하나요?
- 위의 다른 Processor는 막상 타 클래스를 상속하는 구조라 Impl을 안 달고 있네요. |
@@ -0,0 +1,63 @@
+package io.study.springbootlayered.api.member.domain;
+
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Component;
+
+import io.study.springbootlayered.api.member.domain.dto.MemberDetailDto;
+import io.study.springbootlayered.api.member.doma... | Java | 해당 쿼리가 다른 곳에서 재사용되지 않을 것이라는 보장이 있나요?
이런 기본적인 Validation 용 쿼리는 분리해서 다루는게 좋을 것 같아요. |
@@ -0,0 +1,32 @@
+package io.study.springbootlayered.api.member.application;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dt... | Java | 로그 미사용인데 해당 어노테이션 사용하고 있네요. |
@@ -0,0 +1,5 @@
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+
+export const PRODUCTS_ENDPOINT = `${API_URL}/products`;
+export const CART_ITEMS_ENDPOINT = `${API_URL}/cart-items`;
+export const CART_ITEMS_COUNTS_ENDPOINT = `${CART_ITEMS_ENDPOINT}/counts`; | TypeScript | 이런 endpoint들을 하나의 객체로 관리해도 좋을 것 같아요! |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.... | TypeScript | fetch에 필요한 중복된 로직을 분리한 부분. 인상적입니다. |
@@ -0,0 +1,25 @@
+import { useEffect } from "react";
+import { useErrorContext } from "../../hooks/useErrorContext";
+import { ErrorToastStyle } from "./ErrorToast.style";
+
+const ErrorToast = () => {
+ const { error, hideError } = useErrorContext();
+
+ useEffect(() => {
+ setTimeout(() => {
+ hideError();
... | Unknown | toast를 띄어줄 시간을 따로 상수로 관리하는 것도 좋을 것 같아요 |
@@ -0,0 +1,51 @@
+import useProducts from "../../hooks/useProducts";
+import ProductListHeader from "../ProductListHeader/ProductListHeader";
+import ProductItem from "./ProductItem/ProductItem";
+import * as PL from "./ProductList.style";
+import useInfiniteScroll from "../../hooks/useInfiniteScroll";
+import usePagin... | Unknown | 현재 새로운 fetch를 통해 새로운 데이터를 가지고 오면 스크롤 위치가 강제로 올라가는 버그가 있습니다. 제가 생각하기에는 ProductListStyle가 조건부로 렌더링되어 컴포넌트가 매번 새롭게 만들어집니다. 그래서 리액트가 동일한 컴포넌트로 인지하지 못해서 발생한 문제 같습니다. 다음과 같은 코드로 문제를 해결할 수 있을 것 같습니다.
```tsx
return (
<>
<ProductListHeader
handleCategory={handleCategory}
handleSort={handleSort}
/... |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.... | TypeScript | fetch의 공통된 로직을 두번이나 감싸서 깔끔하게 정리해 준 것이 마음에 드네요~!
제 미션에도 적용시켜봐야겠어요 ㅋㅋㅋ 🚀 🚀🚀🚀 |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | b... | TypeScript | 아마 key로 접근해서 값을 가져오기 위해서 index signature를 사용하려고 하셨던 걸까요?!
하지만 이렇게 되면, 예상치 못하게 `page = "page1"` 과 같은 prop이나
의도하지 않은 key값이 들어올 경우, queryParams interface에서 걸러지지 않을 것 같아요.
여유있으실 때 한번 생각해 보시면 좋을 것 같아요 :) |
@@ -0,0 +1,34 @@
+import styled from "styled-components";
+
+export const ButtonStyle = styled.button`
+ cursor: pointer;
+ border: none;
+ outline: none;
+`;
+
+export const CartControlButtonStyle = styled(ButtonStyle)`
+ display: flex;
+ position: absolute;
+ right: 8px;
+ align-items: center;
+ border-radius... | TypeScript | 저는 Button의 Prop을 받아서 색상을 바꿔주는 식으로 작성했어요!
```suggestion
export const ButtonStyle = styled.button<ButtonProps>`
cursor: pointer;
border: none;
outline: none;
${({ color }) => {
if (color === "primary") {
return `
background-color: black;
color: white;
`;
}
... |
@@ -0,0 +1,39 @@
+import styled from "styled-components";
+
+export const HeaderStyle = styled.header`
+ display: flex;
+ background-color: #000000;
+ width: inherit;
+ height: 64px;
+ position: fixed;
+ z-index: 1;
+ padding: 16px 24px 16px;
+ box-sizing: border-box;
+`;
+
+export const LogoImg = styled.img`
+... | TypeScript | 프로젝트의 컴포넌트 규모가 복잡해지면, zindex 관리가 힘들더라구요
헤더를 1로 해놨는데, 헤더보다 낮은 어떠한 component가 생길수도 있고...!
그래서 저도 추천받은 방법이 zIndex들을 상수로 관리해서 한곳에서 편하게 볼 수 있도록 하는거였어요
저도 자주 사용하진 않지만, 꿀팁 공유해봅니다 ㅎㅎ |
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useState,
+ ReactNode,
+ useEffect,
+ useCallback,
+} from "react";
+import { getCartItems } from "../api";
+import { useErrorContext } from "../hooks/useErrorContext";
+
+export interface CartItemsContextType {
+ cartItems: CartItem[];
+ refreshCartItems: () => void... | Unknown | 저는 Quantity만을 context로 관리했는데, 전체 List를 context 로 관리하셨군요!!
Provider를 custom 해주는 것도 매우 좋은 것 같습니다 :)
좋은 정보 배우고 갑니다!! |
@@ -0,0 +1,34 @@
+import styled from "styled-components";
+
+export const ButtonStyle = styled.button`
+ cursor: pointer;
+ border: none;
+ outline: none;
+`;
+
+export const CartControlButtonStyle = styled(ButtonStyle)`
+ display: flex;
+ position: absolute;
+ right: 8px;
+ align-items: center;
+ border-radius... | TypeScript | Button에 `hover` 속성도 있으면 어떨까 싶네요! |
@@ -0,0 +1,37 @@
+import { forwardRef } from "react";
+import * as PI from "./ProductItem.style";
+import CartControlButton from "../../Button/CartControlButton";
+import useProductInCart from "../../../hooks/useProductInCart";
+
+interface ProductProps {
+ product: Product;
+}
+
+const ProductItem = forwardRef<HTMLDi... | Unknown | 혹시 try-catch 에서 catch되는 error가 `Error` 타입이 아닌 경우도 있나요?!
단순히 궁금해서 여쭤봅니다...!
catch되는 것은 Error만 catch되는줄 알아서, 이 로직이 필요한가 하는 생각이 들었어요 ㅋㅋ |
@@ -0,0 +1,51 @@
+import useProducts from "../../hooks/useProducts";
+import ProductListHeader from "../ProductListHeader/ProductListHeader";
+import ProductItem from "./ProductItem/ProductItem";
+import * as PL from "./ProductList.style";
+import useInfiniteScroll from "../../hooks/useInfiniteScroll";
+import usePagin... | Unknown | 오... 해결법 제시까지 대단하네요 🚀 🚀🚀🚀🚀🚀🚀 |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.... | TypeScript | `requestBuilder` 라는 이름으로 요청을 만드는 책임을 가진 함수를 별도로 분리해주신 부분이 인상깊네요!👍👍 |
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useState,
+ ReactNode,
+ useEffect,
+ useCallback,
+} from "react";
+import { getCartItems } from "../api";
+import { useErrorContext } from "../hooks/useErrorContext";
+
+export interface CartItemsContextType {
+ cartItems: CartItem[];
+ refreshCartItems: () => void... | Unknown | `useCallback`과`toggle`이라는 상태를 통해 `fetchCartItems`을 재실행시킨다는 발상이 몹시 새롭게 느껴지네요! 한 번도 생각해보지 못했던 방식인데... 상태는 최소화되어야 한다고 생각하는 편이지만, 특정 트리거를 위해 상태를 활용하는 것이 좋은지 저도 한 번 고민해볼 수 있었던 것 같아요!
한편으로는 상태를 만들지않고, `fetchCartItems`로직을 `useEffect` 밖으로 뺀 뒤 refreshCartItems 을 잘 작성해주면 상태가 필요하지 않을 것 같다는 생각이 들기도 합니다! (이 부분은 개발자의 취향이나 선호에 가까울... |
@@ -0,0 +1,15 @@
+import { useContext } from "react";
+import {
+ CartItemsContext,
+ CartItemsContextType,
+} from "../context/CartItemsContext";
+
+export const useCartItemsContext = (): CartItemsContextType => {
+ const context = useContext(CartItemsContext);
+ if (!context) {
+ throw new Error(
+ "useCa... | TypeScript | 현재 `useErrorContext`와 `useCartItemsContext`는 context가 `undefined`인 경우 에러를 던져 타입을 좁히기 위한 커스텀 훅인 것 같습니다. 제가 느끼기엔 두 훅 모두 같은 역할을 해주고 있는 것 같아서 context를 인자로 받는다면 하나의 훅으로 합쳐서 재사용해주어도 좋을 것 같습니다!ㅎㅎ |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | b... | TypeScript | 몹시 흥미로운 함수네요!👍👍 별거 아니지만 이러한 부분은 api 내부 util로 파일을 분리해주셔도 좋을 것 같아요! |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | b... | TypeScript | 추상화된 `fetchWithAuth` 내부에서 이미 `response.ok`가 아닌 경우 에러를 던지도록 처리해두었는데 여기를 포함하여 모든 fetch 함수에서 여전히 에러를 던지시는 이유가 있으실까요..?? |
@@ -0,0 +1,16 @@
+package store.constant;
+
+public enum CommonMessage {
+ YES("Y"),
+ NO("N");
+ private final String commonMessage;
+
+ CommonMessage(final String commonMessage) {
+ this.commonMessage = commonMessage;
+ }
+
+ public String getCommonMessage() {
+ return commonMessage;
+... | Java | 입력이 둘뿐인 경우에 대해서 Enum으로 관리하는 것도 좋은 방법인 것 같아요! |
@@ -0,0 +1,22 @@
+package store.constant;
+
+public enum FileMessage {
+ PRODUCTS_FILE_NAME("products.md"),
+ PROMOTION_FILE_NAME("promotions.md"),
+ NULL("null"),
+ SOFT_DRINK("탄산2+1"),
+ MD_RECOMMEND_PRODUCT("MD추천상품"),
+ FLASH_DISCOUNT("반짝할인"),
+ FILE_START_WORD("name");
+
+ private final Stri... | Java | 파일에 있는 프로모션 데이터를 Enum으로 관리하는건 좋지 않은 것 같습니다
프로모션 종류가 3개 고정이 아니라 각기 다른 수백 개, 수천 개로 늘어날 수 있을 것 같아요! |
@@ -0,0 +1,71 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+
+public class Receipt {
+ private final double THIRTY_PERCENT = 0.3;
+ private final List<ReceiptItem> receiptItems = new ArrayList<>();
+
+ ... | Java | model의 역할을 수행하는 클래스로 보이는데 패키지를 분리하지 않고, domain 패키지에 같이 두신 이유가 있을까요? |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.d... | Java | `userMembership()`에서 멤버십 할인 여부에 따라 최종 계산 금액에서 30% 할인이 되고 있는데,
요구사항에서는 프로모션 상품을 제외한 일반 상품으로 결제된 상품들에 대해서만 멤버십 할인이 되어야 한다고 명시되어 있습니다
이 부분이 처리되지 않은 것 같습니다! |
@@ -0,0 +1,19 @@
+package store.constant;
+
+public enum CommonValue {
+ ZERO(0),
+ ONE(1),
+ TWO(2),
+ EIGHT_THOUSAND(8000);
+
+ private final int value;
+
+ CommonValue(final int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+} | Java | 상수들을 enum으로 잘 관리해주셨는데요!
저는 개인적으로 enum의 값을 꺼내기 위해 `.getValue()` 까지 붙는게 조금 지저분해보입니다.
static 상수의 경우 `Constant.ZERO` 이런식으로 사용할 수 있지만 enum은 `CommonValue.ZERO.getValue()` 로 1depth 더 늘어나는 느낌이랄까요..? |
@@ -0,0 +1,71 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+
+public class Receipt {
+ private final double THIRTY_PERCENT = 0.3;
+ private final List<ReceiptItem> receiptItems = new ArrayList<>();
+
+ ... | Java | int를 double과 곱한 뒤 int로 형변환을 하고 있는데요!
double로 계산되는 과정에서 부동소수점 오류를 피할 수 없을 것으로 보입니다. 이때는 `* 30 / 100` 으로 계산해서 아예 소수점이 안생기도록 계산하시는 것은 어떨까요? |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.d... | Java | 저는 MVC 패턴에 Service 계층을 추가해서 책임 분리에 애먹었었는데, Service가 없으니 좀 더 자연스럽게 데이터 전달이 이루어지네요..!! |
@@ -0,0 +1,141 @@
+package store.view.output;
+
+import java.util.List;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.ReceiptItem;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+
+public class OutputView ... | Java | 프로모션 상품이 소진되고 나서 프로모션 상품도 재고 없음으로 출력되는데,
사용자는 프로모션 상품을 구매할 수 없으므로 아예 노출시키지 않는 것도 좋을 것 같아요!
UX쪽으로도 한번 고민해보시면 좋을 것 같습니다🙂 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.