0Pricing
C# Academy · 강의

캡슐화와 불변 조건

내부 상태를 숨기고 안전한 연산을 제공하며, 클래스의 불변 조건을 항상 참으로 유지합니다(예: 음수가 아닌 잔액, 유효한 범위).

캡슐화와 불변 조건은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.

캡슐화 개요

목표: 개체의 상태를 보호합니다.

  • 캡슐화: fields를 숨기고 안전한 APIs를 노출합니다
  • 불변식: 항상 참인 규칙입니다
  • 생성자, 세터, 메서드에서 유효성을 검사합니다

읽기 전용 인터페이스

fields를 비공개로 유지합니다. 호출자에게 읽기 전용 속성과 안전한 연산을 제공합니다.

using System;

// Expose read-only view; mutate via methods only
public class Counter
{
  private int _value;          // hidden state
  public int Value             // read-only to callers
  {
    get { return _value; }
    private set { _value = value; } // keep setter private
  }

  public void Increment()
  {
    Value = Value + 1;
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Counter c = new Counter();
    c.Increment();
    c.Increment();
    Console.WriteLine("Value = " + c.Value);
  }
}

생성자 검증

생성자는 필수 상태를 설정합니다. 잘못된 입력을 차단하여 처음부터 개체를 유효한 상태로 유지합니다.

using System;

// Enforce rules early (constructor guard)
public class User
{
  public string Name { get; private set; }
  public int Age { get; private set; }

  public User(string name, int age)
  {
    if (string.IsNullOrEmpty(name)) throw new ArgumentException("name");
    if (age < 0) throw new ArgumentOutOfRangeException("age");
    Name = name;
    Age = age;
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    try
    {
      User u = new User("Ada", 28);
      Console.WriteLine(u.Name + " (" + u.Age + ")");
    }
    catch (Exception ex)
    {
      Console.WriteLine("Error: " + ex.Message);
    }
  }
}

실제 불변식

불변식을 정의하고(예: Balance ≥ 0) 세터와 메서드에서 이를 적용합니다.

using System;

// Invariant: Balance >= 0 at all times
public class BankAccount
{
  private decimal _balance;

  public decimal Balance
  {
    get { return _balance; }
    private set
    {
      if (value < 0) throw new InvalidOperationException("Balance would be negative");
      _balance = value;
    }
  }

  public BankAccount(decimal opening)
  {
    if (opening < 0) throw new ArgumentOutOfRangeException("opening");
    _balance = opening;
  }

  public void Deposit(decimal amount)
  {
    if (amount <= 0) throw new ArgumentOutOfRangeException("amount");
    Balance = Balance + amount;
  }

  public bool TryWithdraw(decimal amount)
  {
    if (amount <= 0) return false;
    if (Balance - amount < 0) return false;
    Balance = Balance - amount;
    return true;
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    BankAccount a = new BankAccount(50m);
    a.Deposit(20m);
    bool ok = a.TryWithdraw(100m); // fails, invariant protected
    Console.WriteLine("ok=" + ok + " balance=" + a.Balance);
  }
}

컬렉션 보호

내부 목록이나 배열을 직접 노출하지 않습니다. 불변식을 보호하려면 복사본(또는 읽기 전용 뷰)을 반환합니다.

using System;
using System.Collections.Generic;

public class Tags
{
  private readonly List<string> _items = new List<string>();

  public void Add(string tag)
  {
    if (string.IsNullOrWhiteSpace(tag)) return;
    _items.Add(tag.Trim());
  }

  // Expose a copy so callers cannot mutate internal list
  public List<string> GetAllCopy()
  {
    return new List<string>(_items);
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Tags t = new Tags();
    t.Add(" apple ");
    t.Add("banana");
    List<string> view = t.GetAllCopy();
    view.Add("hacker"); // modifies the copy only
    Console.WriteLine("copy count=" + view.Count);
    Console.WriteLine("original count=" + t.GetAllCopy().Count);
  }
}

캡슐화 팁

체크리스트:

  • 비공개 fields, 공개 properties/methods
  • 생성자와 세터에서 유효성을 검사합니다.
  • 모든 호출이 끝난 후에도 불변식이 참이도록 유지합니다.
  • 내부 컬렉션을 노출하지 않습니다.

캡슐화 원칙

빠르게 확인해 보겠습니다. 캡슐화와 클래스 불변식을 가장 잘 보존하는 선택은 무엇입니까?

복습

복습: 비공개 fields와 유효성이 검사된 APIs로 캡슐화합니다. 불변식을 정의하고 생성자, 세터, 메서드에서 이를 적용합니다. 내부 컬렉션을 절대 노출하지 않습니다.

자주 묻는 질문

“캡슐화와 불변 조건” 강의는 무료인가요?

네 — “캡슐화와 불변 조건” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.

“캡슐화와 불변 조건”에서 뭘 배우나요?

내부 상태를 숨기고 안전한 연산을 제공하며, 클래스의 불변 조건을 항상 참으로 유지합니다(예: 음수가 아닌 잔액, 유효한 범위). 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

C# Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.

“캡슐화와 불변 조건” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 필드, 자동 속성, 객체 이니셜라이저
  2. 생성자와 정적 멤버
  3. 캡슐화와 불변 조건
← C# Academy(으)로 돌아가기