プロパティで不変条件を守る
Coddyの「Ruby開発者のためのC#」コースのレッスン 34/48。
Rubyのattr_readerはパブリックな読み取りメソッドを生成します。また、attr_writerを省略すると、account.balance = 3は、その行が実行されたときにのみNoMethodErrorを発生させます。C#のゲッターのみのプロパティは値の型を宣言し、コンパイラーによってチェックされるため、無効な代入を含むコードはビルドできません。どちらの言語も、強い意志を持つ呼び出し側を完全に止めることはできません(Rubyにはinstance_variable_setがあります)が、Depositのようなメソッドを使えば、通常の変更のたびに不変条件を保てます。
プロパティは制御されたアクセスを提供し、プライベートフィールドは不変条件を保ちます。ゲッターを使えば、呼び出し側が任意の値を代入できないようにしながら、状態を公開できます。プライベートセッターやゲッターのみのプロパティを使うかどうかは、契約上の選択です。更新時に検証が必要なら、変更可能なフィールドを公開しないでください。
Rubyの参考例
class Account
attr_reader :balance
def initialize(amount)
@balance = [0, amount].max
end
def deposit(n)
@balance += n if n > 0
end
end
account = Account.new(5)
account.deposit(-3)
puts account.balanceC#の補助的な宣言
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);これらは要点を絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言と文が示されています。
Rubyの出力:
5C#の出力:
6チャレンジ
簡単Accountを完成させましょう。開始時の残高は0未満にならないようにし、正の入金額は残高に加算し、0以下の入金額は無視します。残高は読み取れますが、外部から設定することはできません。
ロック解除されている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);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Ruby開発者のためのC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ