프로그래밍 초식 : if 조건 역으로 바꾸기

Donghun Seol·2023년 4월 25일
0

프로그래밍 초식

목록 보기
5/13

레퍼런스

중첩된 if문을 역으로 바꿔서 중첩없애기

if (a) {
  if (b) {
  	if (c) {
      return true;
    }
  } 
}
return false;

if (!a) return false;
if (!b) return false;
if (!c) return false;
return true;

얻는 장점

else가 없다는 걸 빨리 인지가능
코드 인덴테이션이 줄어들어 복잡도가 감소
코드 가독성이 높아지고, 유지보수가 용이해짐

보호절 (guard clause)

참고: 구현패턴(켄트 벡 저)

보호절(Guard Clause)은 프로그래밍에서 함수나 메서드 등의 입력 파라미터를 검증하고, 
이상이 있을 경우에는 조기에 함수 실행을 중단시키는 방법입니다. 
이를 통해 코드의 가독성과 유지보수성을 향상시키며, 불필요한 예외 발생을 방지합니다.

예시는 ChatGPT 형님의 도움을 받았다.

보호절을 부적절하게 적용한 예시

function calculateArea(height: number, width: number) {
  if (height > 0 && width > 0) {
    return height * width;
  } else {
    throw new Error("Height and width must be greater than zero.");
  }
}

보호절을 효과적으로 적용한 예시

function calculateArea(height: number, width: number) {
  if (!height || !width) {
    throw new Error("Both height and width are required.");
  }

  if (height <= 0 || width <= 0) {
    throw new Error("Height and width must be greater than zero.");
  }

  return height * width;
}
profile
I'm going from failure to failure without losing enthusiasm

1개의 댓글

comment-user-thumbnail
2023년 5월 13일

sample mocking comment for api test

답글 달기