【发布时间】:2012-12-12 03:47:40
【问题描述】:
于是我就一段代码与一位同事发生了友好的争论:
public sealed class NewObject
{
private string _stuff = string.Empty;
public string Stuff
{
get { return GetAllStuff(); }
}
private string GetAllStuff()
{
//Heavy string manipulation of _stuff
}
public NewObject(string stuffToStartWith)
{
_stuff = stuffToStartWith;
}
public static NewObject operator +(NewObject obj1, NewObject obj2)
{
if (obj1 == null)
throw new ArgumentNullException();
if (obj2 == null)
throw new ArgumentNullException();
NewObject result = new NewObject(string.Empty);
result._stuff = String.Concat(obj1._stuff, obj2._stuff);
return result;
}
}
参数超过了运算符覆盖。我的同事认为,在构造函数之外的任何地方设置私有字段的值并不是最佳编程实践。我的同事提出的解决方案是将Stuff 属性的名称重构为AllStuff 并添加一个属性Stuff,该属性具有get 和set 访问器并使用新的Stuff运算符覆盖中的属性。让它看起来像这样:
public static NewObject operator +(NewObject obj1, NewObject obj2)
{
if (obj1 == null)
throw new ArgumentNullException();
if (obj2 == null)
throw new ArgumentNullException();
NewObject result = new NewObject(string.Empty);
result.Stuff = String.Concat(obj1.Stuff, obj2.Stuff);
return result;
}
我不同意。我觉得第一种方法更好,因为它使属性在课堂外保持只读。我的问题是,哪种方式是面向对象设计的最佳实践?
【问题讨论】:
标签: c#