[Profile] 클린 코드
재사용성, 가독성 중요!
- 화려한 테크닉 보다 단순한 코드로 어떤 개발자가 봐도 알기 쉬운 코드를 짜는 게 목표입니다.
클린 코드를 위해 __합니다.
- 반복되는 코드는 하나의 모듈로 분리
- 함수는 한 가지 기능을 담당하도록
- 코드를 짤 때 매직넘버, 반복적인 문자열은 상수화
- 가독성을 위해 prop 또는 기능 단위로 컴포넌트 분리
하지만
- 짧은 코드가 무조건 클린코드라고 생각하지 않습니다.
- 너무 추상화되거나 코드분리가 심하면 오히려 이해가 잘 되지 않기에 응집도 있는 코드를 짜려고 노력합니다.
예시
- 함수 단일책임
const showPassword = useCallback((name) => {
if (name === "password") {
setShowPassword((showPassword) => !showPassword);
} else {
setShowPasswordConfirm((showPasswordConfirm) => !showPasswordConfirm);
}
}, []);
const showPassword = useCallback(() => {
setShowPassword((showPassword) => !showPassword);
}, []);
const showPasswordConfirm = useCallback(() => {
setShowPasswordConfirm((showPasswordConfirm) => !showPasswordConfirm);
}, []);
- 핵심 액션만 남기고 상세 구현은 추상화
<ProfileModal
visible={isProfileModalOpen}
onClose={handleProfileModalClose}
className="profile"
>
<ModalTitle>프로필을 바꾸시겠어요?</ModalTitle>
<ImageUploader
shape="circle"
size={14}
onChange={handleProfileChange}
value={user.image}
isReset={isReset}
/>
<Message>* 사진을 클릭 후, 파일을 등록해 주세요.</Message>
<ModalButton type="submit" onSubmit={handleProfileSubmit}>
확인
</ModalButton>
</ProfileModal>
<ProfileModal
visible={isProfileModalOpen}
onClose={handleProfileModalClose}
onChange={handleProfileChange}
onSubmit=
className="profile"
/>
- 추상화는 적절히, 응집도 있도록
function MyInfo() {
const [openProfileModal] = useModal("profile");
return (
<UserImage
src={user.image}
alt={user.nickName}
width={140}
height={140}
objectFit="cover"
onClick={openProfileModal}
/>
);
}
- 만약 위처럼 코드를 짜면 코드양을 확 줄일 수 있습니다. user의 이미지를 누르면 useModal 훅이 알아서 뜨고 거기서 한 action은 전부 useModal 훅에서 처리합니다.
- 하지만 무슨 일을 하는지 모달엔 어떤 정보가 담기는 지 알 수 없습니다.
- 따라서 유지 보수할 때 파일을 왔다갔다 해야합니다.
수정
- 아래처럼 수정하면 세부 사항은 숨기면서 어떤 값이 모달에 담기고 어떤 액션을 취하는 지 알 수 있습니다.
function MyInfo() {
const [user] = useRecoilState<User>(currentUser)
const [openProfileModal] = useModal('profile');
const handleSubmitNewProfile = async() {
await patchProfile();
}
const handleClickProfile= async(e) {
const profileModal = await openProfileModal({
title: '프로필을 수정하시겠어요?',
placeholder: user.image ,
});
if (profileModal) {
/** 수정 버튼 클릭 action */
await handleSubmitNewProfile();
}
}
return (
<UserImage
src={user.image}
alt={user.nickName}
width={140}
height={140}
objectFit="cover"
onClick={handleClickProfile}
/>
)
}
댓글남기기