미디엄에서 우연히 이 글을 읽다 알게 되었다.
참고:
Guard
Guard
“In computer programming, a guard is a Boolean expression that must evaluate to true if the execution of the program is to continue in the branch in question.”
Guard란 특정 분기(branch)의 실행을 계속하려면 참으로 평가되어야 하는 Boolean 표현식이다.
즉, 해당 조건이 참이 아닐 경우 해당 코드 블록을 실행을 종료하는 역할을 하며 일반적으로 프로그램의 전제 조건을 검사하는데 사용된다.
Guard, Guard Clause, Guard Statement 등으로 불린다.
일반적인 조건 분기 vs Guard Clause
Guard Clause가 중요한 이유는 일반 조건문(Else Clause)을 사용한 코드에 비해 가독성과 유지보수성이 높기 때문이다.
def process_user(user):
if user is not None:
if user.is_active:
print("Processing user")
else:
raise PermissionError("Inactive users cannot be processed")
else
raise ValueError("User must not be None")def process_user(user):
if user is None:
raise ValueError("User must not be None")
if not user.is_active:
raise PermissionError("Inactive users cannot be processed")
print("Processing user")
Early Return Pattern
Guard Clause에서 참이 아닐 경우 함수나 메서드의 실행을 조기에 종료하기 때문에, 이런 방식을 Early Return Pattern이라고 부르기도 한다.
가독성 - Line of Sight
위의 방식을 사용한 코드가 ‘좋은 코드’라고 불릴 수 있는 이유는 다음 이유가 가장 큰 것 같다.
Line of sight is “a straight line along which an observer has unobstructed vision”
의역하면 관찰자(프로그래머)가 명확하게 코드를 관찰할 수 있게 하는 직선(열)을 의미한다.

위의 경우 왼쪽 사진의 직선을 따라가는 코드는 happy path(정상 실행)이고,
오른쪽 사진의 직선을 따라가는 들여쓰기된 코드는 error handling & edge cases에 해당한다.
이렇게 열을 따라 코드의 흐름을 명확하게 이해할 수 있게 되면 가독성이 높아진다.
Else Clause
Guard Clause를 사용한 코드의 대척점에 있는 코드에는 else 문이 자주 사용된다. (Else Clause)
Else Clause를 사용한 코드는 Line of Sight에 말한 것처럼 정상 분기와 오류 분기가 같은 선상에 놓이게 되어 코드 가독성이 떨어진다. else 문을 지양하라는 말도 여기서 기인하는 것 같다. Else Considered Smelly
Else Clause를 활용한 코드가 꼭 나쁘다고 생각하지 않는다.
그래서 Line of Sight을 이해하는 것이 중요하다고 생각한다. 만약 정상/오류 분기가 아닌 같은 레벨에 놓인 분기라면, Else Clause를 사용해도 괜찮다고 생각한다.