TIL

APPENDIX A. 계약에 의한 설계

계약에 의한 설계가 왜 필요한가

01 협력과 계약

부수효과를 명시적으로

class Event 
{
  public bool IsSatisfied(RecurringSchedule schedule) { ... }
  
  public void Reschedule(RecurringSchedule schedule) 
  {
    Contract.Requires(IsSatisfied(schedule));
    ...
  }

계약

02 계약에 의한 설계

// 가시성, 반환 타입, 메서드 이름
public Reservation reserve(
  Customer customer, // 파라미터 타입과 이름
  int audienceCount
) { ... }

사전 조건

public Reservation Reserve(Customer customer, int audienceCount)
{
  Contract.Requires(customer != null);
  Contract.Requires(audienceCount >= 1);
  return new Reservation(...);
}

사후 조건

public Reservation Reserve(Customer customer, int audienceCount)
{
  Contract.Requires(customer != null);
  Contract.Requires(audienceCount >= 1);
  Contract.Ensures(Contract.Result<Reservation>() != null);
  return new Reservation(...);
}
public string Middle(string text)
{
  Contract.Requires(text != null && text.Length >= 2);
  Contract.Ensures(Contract.Result<string>().Length < Contract.OldValue<string>(text).Length);
  text = text.Substring(1, text.Length - 2);
  return text.Trim();
}

불변식

public class Screening
{
  private Movie movie;
  private int sequence;
  private DateTime whenScrenned;
  
  [ContractInvariantMethod]
  private void Invariant() {
    Contract.Invariant(movie != null);
    Contract.Invariant(sequence >= 1);
    Contract.Invariant(whenScreened > DateTime.Now);
  }
}