Design by Contract etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Design by Contract etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

10 Şubat 2020 Pazartesi

Design by Contract

Giriş
Nesneye yönelik tasarımdaki en önemli eksiklerden birisi değerler için sınırların belirlenememesi.

Örnek
Elimizde şöyle bir kod olsun.
public interface ISomeInterface
{
  int SomeMethod(string a);
}
Bu kod için şöyle bir kısıtlama koymak isteyelim.
1) For every object that consumes ISomeInterface, they assert that the returned int > 5.

2) For every object that implements ISomeInterface, they assert that the int they're about to return is > 5.
Bunu kolayca çözmenin yolu yok. Çözüm önerileri şöyle
1. Type System of the Language
2. Meta Annotations internal/external to the Language
3. Runtime Assertions
4. Documentation Targetted At Humans
Çözüm 1
Bir çözüm olarak şöyle yapabiliriz. Burada Type System ile değişiklik yapılıyor. Ayrıca Runtime assertion ve Documentation'da kullanılıyor.
// should be class, not struct as struct can be created without calling a constructor
public class ValidNumber
{
  public int Number { get; }

  public ValidNumber(int number)
  {
    if (number <= 5)
      throw new ArgumentOutOfRangeException("Number must be greater than 5.")
    Number = number;
  }
}

public class Implementation : ISomeInterface
{
  public ValidNumber SomeMethod(string a)
  {
    return new ValidNumber(int.Parse(a));
  }
}