프로그램 초식: 쿼리에서 로직 빼기(취향?)

Donghun Seol·2023년 5월 6일
1

프로그래밍 초식

목록 보기
12/13

레퍼런스

로직이 삽입된 쿼리

update member set status = 20 where member_id = ? and status = 10
update account acc
join contract ct on ct.cntr_id = sp.cntr_id
set acc.status = 'CLOSE'
where ct.cntr_id = ? and ct.status = 100

로직이 잘 안보인다.

주요 로직이 어플리케이션과 쿼리에 걸쳐 분산되어 분석이 어려워진다.
유사한 쿼리를 중복해서 만들 수 있다.
주요 로직을 단위 테스트하기 어렵다.

  • 쿼리와 결합되어 있으므로 쿼리를 실행해야 로직을 검증 할 수 있다.
  • 따라서 통합테스트와 유사한 환경에서 단위테스트를 수행해야 한다.

쿼리의 로직을 코드로 옮기는 것이 바람직하다.

이 쿼리를

update member set status = 20 where member_id = ? and status = 10

이렇게 어플리케이션 코드에 녹인다.

const member: Member = memberRepository.findOne({where:{id}});
if (!member) throw Error;
if (member.status != 10) throw Error;
member.status = 20;
membereRespository.save(member)

분리함으로써 얻는 장점

코드 가독성 개선된다. 명시적인 보호절과 에러로 전반적인 로직이 더 잘 드러난다.
상태 변경 기능과 관련된 쿼리가 단순해진다.
단위 테스트로 로직 검증 가능해진다.

따라서 상태 변경과 관련된 로직은 쿼리에서 분리하자.
단, 배치와 같이 대량 데이터를 다룰 땐, 성능하락 문제를 고려해야한다.

profile
I'm going from failure to failure without losing enthusiasm

6개의 댓글

comment-user-thumbnail
2023년 5월 12일

sample mocking comment for api test

답글 달기
comment-user-thumbnail
2023년 5월 13일

sample mocking comment for api test

답글 달기
comment-user-thumbnail
2023년 5월 13일

sample mocking comment for api test

답글 달기
comment-user-thumbnail
2023년 5월 24일


성능을 위해서는 쿼리를 사용하는 것이 좋다.

좋은 자료:

답글 달기