Menu
CoddyTech

プロパティで不変条件を守る

Coddyの「PHP開発者のためのC#」コースのレッスン 34/48。

PHPでは従来、状態を非公開プロパティに保持し、getBalance()メソッドを公開していました。PHP 8.4では、同じ考え方を実現するためにプロパティフックとprivate(set)が追加されました。C#のプロパティでは、そのゲッターをフィールドのような構文で記述でき、アクセス修飾子とフィールドの型はコンパイル時に検査されます。状態を非公開に保ち、任意の値を公開フィールドに書き込めるようにするのではなく、メソッド内で検証しながら、残高を読み取れるようにしましょう。

プロパティを使うとアクセスを制御して公開でき、非公開フィールドを使うと不変条件を保てます。ゲッターを使えば、呼び出し側が任意の値を代入できないようにしながら、状態を提示できます。非公開のセッターにするか、ゲッターのみのプロパティにするかは、契約上の選択です。更新時に検証が必要な場合は、変更可能なフィールドを公開しないでください。

PHPの参考例

class Account {
    private int $amount;
    public function __construct(int $n) { $this->amount = max(0, $n); }
    public function deposit(int $n): void { if ($n > 0) $this->amount += $n; }
    public function getBalance(): int { return $this->amount; }
}
$account = new Account(5); $account->deposit(-3); echo $account->getBalance(), "\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);

これらは要点に絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれています。上記のスニペットには、関連する宣言とステートメントが示されています。

参考出力:

5

C#の出力:

6
challenge icon

チャレンジ

簡単

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);
}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

PHP開発者のためのC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ