IsSatisfied()
가 true
일 때만 Reschedule
메서드를 호출할 수 있다는 사실을 명확히 표현 가능class Event
{
public bool IsSatisfied(RecurringSchedule schedule) { ... }
public void Reschedule(RecurringSchedule schedule)
{
Contract.Requires(IsSatisfied(schedule));
...
}
// 가시성, 반환 타입, 메서드 이름
public Reservation reserve(
Customer customer, // 파라미터 타입과 이름
int audienceCount
) { ... }
customer
값으로 null
전달 불가audienceCount
로 음수 전달 불가Reserve
메서드의 경우 customer
가 null
이 아니여야 하고 audienceCount
는 1보다 커야한다 등의 조건public Reservation Reserve(Customer customer, int audienceCount)
{
Contract.Requires(customer != null);
Contract.Requires(audienceCount >= 1);
return new Reservation(...);
}
ContractException
이 발생할 것이다.Ensures
메서드로 사후 조건을 명시할 수 있다.
Reservation
인스턴스가 null
이어선 안된다는 것이다.public Reservation Reserve(Customer customer, int audienceCount)
{
Contract.Requires(customer != null);
Contract.Requires(audienceCount >= 1);
Contract.Ensures(Contract.Result<Reservation>() != null);
return new Reservation(...);
}
Contract.Result<T>
메서드를 통해 Reserve
메서드의 실행 결과에 접근할 수 있다.
Contract.OldValue<T>
를 통해 메서드 실행 전 상태에도 접근할 수 있다.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();
}
Contract.Invariant
메서드로 불변식을 정의할 수 있다.
ContractInvariantMethod
애트리뷰트가 지정된 메서드를 불변식 체크하는 모든 지점에 자동으로 추가한다.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);
}
}