방어적 프로그래밍
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨. 66개 중 34번째.
방어적 프로그래밍은 null 참조로 인해 발생하는 오류를 방지하는 데 도움이 되는 기법입니다. 객체를 사용하기 전에 null 값을 확인하는 작업이 포함됩니다.
객체를 사용하기 전에 null인지 확인하세요:
string name = GetNameFromSomewhere();
// 방어적 검사
if (name == null)
{
// null 케이스 처리
name = "Default Name";
}
// 이제 name을 안전하게 사용할 수 있습니다
Console.WriteLine(name.ToUpper());메서드에서 매개변수를 검증하세요:
public void ProcessOrder(Order order)
{
// null 매개변수에 대한 방어적 검사
if (order == null)
{
Console.WriteLine("Error: Order cannot be null");
return;
}
// 이제 주문을 안전하게 처리할 수 있음
Console.WriteLine("Processing order: " + order.Id);
}더 깔끔한 null 검사를 위해 조건부 액세스 연산자 (?.)를 사용하세요:
Customer customer = GetCustomerFromSomewhere();
// 대신:
// string city = null;
// if (customer != null && customer.Address != null)
// {
// city = customer.Address.City;
// }
// 이것을 사용하세요:
string city = customer?.Address?.City;챌린지
쉬움ProcessUserData라는 이름의 메서드를 만들고 string 매개변수 userData를 받도록 하세요. 메서드는 다음을 수행해야 합니다:
userData가 null인지 확인합니다. null이면 "Error: User data is null"을 출력하고 반환합니다.userData가 empty인지 확인합니다. empty이면 "Error: User data is empty"를 출력하고 반환합니다.- 데이터가 valid하면 대문자로 변환하고 "Processing: [UPPERCASE_DATA]"를 출력합니다.
직접 해보기
using System;
class ProcessUserData
{
public static void processUserData(string userData)
{
// Hint: 문자열 "null"은 실제 null 값으로 처리되어야 합니다
// 여기에 코드를 작성하세요
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러