개발/기본) 기본기

기본기) Guard Clause(Guard Statement)

테샤르 2024. 3. 18. 12:30

Guard Clause(Guard Statement)

 

메소드나 함수의 시작 부분에서 입력 매개변수나 조건을 빠르게 검사하여 불필요한 실행을 방지하고 코드의 가독성을 높이는 방법중 하나이다.

보통 조건문(if)를 활용해서 작성을 한다.

 

Guard Clause 를 사용하게 되면 조건에 해당하지 않는 여러가지 많은 조건들이 있는 경우에 조기 종료 / 중지 시키는 것으로 오류를 빠르게 발견하고 코드를 더 쉽게(가독성) 해석하거나 유지보수하기가 쉽게 만든다.

 

반응형

 

 < 예시 코드 -1>

간단하게 음수가 아닌 양수의 값인 경우에만 처리하는 조건 예시이다.

using System;

public class Example
{
    public void CheckPositiveNumber(int number)
    {
        // Guard Clause
        if (number <= 0)
        {
            Console.WriteLine("숫자는 양수여야 합니다.");
            return; // 숫자가 음수이므로 함수를 종료합니다.
        }

        // 나머지 로직
        Console.WriteLine("주어진 숫자는 양수입니다.");
    }
}

 

조건이 여러개로 다양하고  추가로 특정 조건에 대한 에러를 처리할때 주로 사용한다.

< 예시코드 -2 >

using System;

public class UserService
{
    public void ChangePassword(string username, string oldPassword, string newPassword)
    {
        // Guard Clauses
        if (string.IsNullOrEmpty(username))
        {
            throw new ArgumentNullException(nameof(username), "Username cannot be null or empty.");
        }

        if (string.IsNullOrEmpty(oldPassword))
        {
            throw new ArgumentNullException(nameof(oldPassword), "Old password cannot be null or empty.");
        }

        if (string.IsNullOrEmpty(newPassword))
        {
            throw new ArgumentNullException(nameof(newPassword), "New password cannot be null or empty.");
        }

        if (oldPassword.Equals(newPassword, StringComparison.InvariantCultureIgnoreCase))
        {
            throw new ArgumentException("New password cannot be the same as the old password.");
        }

        // 메서드의 나머지 부분은 여기서 계속됩니다.
        // 예를 들어, 사용자 검색, 암호 일치 확인 및 암호 업데이트 등

        Console.WriteLine("Password has been changed successfully.");
    }
}

 

단점으로는 과도한 Guard Clause를 사용하면 코드가 굉장히 세분화 될 수 있고 성능 저하가 생기기도 한다. 적당한 수준에서 조건문에 대한 예외처리를 하는 것을 추천한다.

 

★★★☆☆

 

반응형