なぜ冗長なプライベート変数なのか?これらの2つの戦略は異なりますか?誰でもこれに光を当ててください。
変数の読み取り/書き込みだけを行う場合は、いいえ。それ以外の場合、プライベート変数が必要になる理由は2つあります。
データ検証
// Data validation
public class IntWrapper
{
private int _value;
public int Value
{
get { return _value; }
set
{
if (value < 0) { throw new Exception("Value must be >= 0"); }
_value = value;
}
}
}
ゲッター/セッターは、基盤となるデータストアをまとめます
public class StringBuffer
{
List<char> chars = new List<char>();
// Wraps up an underlying data store
public string Value
{
get { return new String(chars.ToArray()); }
set { chars = new List<char>(value.ToCharArray()); }
}
public void Write(string s) { Write(chars.Count, s); }
public void Write(int index, string s)
{
if (index > chars.Count) { throw new Exception("Out of Range"); }
foreach(char c in s)
{
if (index < chars.Count) { chars[index] = c; }
else { chars.Add(c); }
index++;
}
}
}