미디엄에서 우연히 이 글을 읽다 알게 되었습니다.
참고:
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를 사용해도 괜찮다고 생각합니다.