LoginSignup
1
3

More than 3 years have passed since last update.

C#でコードコントラクトを書いてみた(使ったとは言ってない)

Posted at

概要

.NETのエンタープライズアプリケーションアーキテクチャ 第2版 (マイクロソフト公式解説書)を読んでいて、コードコントラクトというのを知りました。

というわけで実験しようと思ったのですが、Code Contracts for .NET が Visual Studio 2017で使えないため、試すことができませんでした。

試したこと

コードコントラクトをみると、CONTRACTS_FULL が定義されている必要があるみたい。

image.png

で、いい感じに Contract.Requires を追加してみる。

        /// <summary>
        /// 割り算
        /// </summary>
        /// <param name="divisor">割られる数</param>
        /// <param name="dividend">割る数</param>
        /// <returns></returns>
        private double div(double divisor, double dividend)
        {
            Contract.Requires(dividend != 0);
            return divisor / dividend;
        }

が、エラー。
image.png

Extentionsを入れる

Code Contracts for .NET をダウンロード&インストール。

[Code Contracts]ペイン どこ??

Works with
Visual Studio 2010, 2012, 2013, 2015

えー・・。

先人のソースコード

GitHubで使い方を検索してみた。
Requires も、if-then-throwも書かれてる。
Contract はあくまでデバッグ用だったのかな??
今はもう使われないのかな??

housnberg/inf3project/game/game/client/Connector.cs

        public void connect(String ip, UInt16 port)
        {
            Contract.Requires(ip != null);
            Contract.Requires(ip.Length > 6);
            Contract.Requires(ip.Length < 16);
            Contract.Requires(port >= 0);
            Contract.Requires(port <= 65535);

                try
                {
                    if (ip == null || ip.Length > 16 || ip.Length < 7)
                    {
                        throw new ArgumentException("parameter cannot be null and parameter length must be bigger 7 and smaller 16");
                    }
                    else
                    {
                        if (client == null || !client.Connected)
                        {
                            client = new TcpClient(ip, port);
                            buffer.clear();
                        }
                        else
                        {
                            throw new SystemException("the client is already connected!");
                        }
                        Console.WriteLine("client connected");
                    }
                }
                catch (Exception exeption)
                {
                    Console.WriteLine(exeption.Message);
                }


            Contract.Ensures(client != null);
            Contract.Ensures(client.Connected);
            Contract.Ensures(receiverThread.IsAlive);
        }

参考文献

以上。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3