プロパティで不変条件を守る
Coddyの「C++開発者のためのC#」コースのレッスン 34/48。
C++では通常、constゲッターメソッドを公開します。C#にはプロパティ構文があり、呼び出し側はフィールドのように読み取れますが、アクセサーによって契約が制御されます。ゲッターのみを公開すれば、メモリ管理モデルの違いに関係なく、残高の更新をメソッド経由にできます。
プロパティは制御されたアクセスを提供し、プライベートフィールドは不変条件を保ちます。ゲッターを使うと、呼び出し側が任意の値を代入できないようにしながら、状態を提示できます。プライベートセッターにするか、ゲッターのみのプロパティにするかは契約上の選択です。更新に検証が必要な場合は、変更可能なフィールドを公開しないでください。
C++の参照例
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Account { int amount; public: explicit Account(int n):amount(max(0,n)) {} void deposit(int n) { if(n>0) amount+=n; } int balance() const { return amount; } };
int main() {
Account account(5); account.deposit(-3); cout << account.balance() << "\n";
}
C#の宣言部分
class Reading { private int raw; public Reading(int raw) { this.raw = raw; } public int Doubled { get { return raw * 2; } } }Main内のC#の文
var reading = new Reading(3);
Console.WriteLine(reading.Doubled);これらは要点を絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれています。上記のスニペットには、関連する宣言と文が示されています。
参照出力:
5C#の出力:
6チャレンジ
簡単Accountを完成させましょう。開始時の残高は0未満にならないようにし、正の入金額は残高に加算し、0または負の入金額は無視します。Balanceは読み取れますが、外部から設定することはできません。
ロックされていないC#ファイルを編集してください。表示されているロック済みのMain.csは、説明されている行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを確認して、最後に改行を1つ付けて結果を出力します。宣言されているAPIを維持してください。2つ目のMainを追加したり、診断用の出力を表示したりしないでください。
ロックされたランチャーは、Solveラッパーだけでなく、エクスポートされたヘルパーまたはクラスのAPIも個別にテストします。
自分で試してみよう
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var accountOne = new Account(-2); var accountTwo = new Account(5); accountOne.Deposit(3); accountOne.Deposit(-9); if (accountOne.Balance != 3 || accountTwo.Balance != 5) throw new Exception("Account API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ