プロパティで不変条件を守る
Coddyの「Go開発者向けC#」コースのレッスン 34/48。
Goでは制御された読み取りにメソッドを使い、エクスポートされていないフィールドはパッケージ内でのみ使用できます。C#のプロパティはgetter構文を公開し、privateフィールドは型内でのみ使用できます。パブリックsetterを公開するのではなく、検証済みのメソッド内で残高の変更を行いましょう。
プロパティはアクセスを制御し、privateフィールドは不変条件を保ちます。getterを使えば、呼び出し側が任意の値を代入できないようにしながら、状態を提示できます。private setterにするかgetterのみのプロパティにするかは、契約上の選択です。更新時に検証が必要なら、変更可能なフィールドを公開しないでください。
Goの例
package main
import ("fmt")
type Wallet struct{balance int}
func(w Wallet)Balance()int{return w.balance}
func main() {
wallet:=Wallet{balance:5};fmt.Println(wallet.Balance())
}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以下の入金額は無視されます。残高は読み取れますが、外部から設定することはできません。
ロック解除されている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);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Go開発者向けC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ