【发布时间】:2016-06-13 17:15:32
【问题描述】:
给定以下具有这样一个基类的场景:
internal class ResolveVariableStrategyBase
{
...
protected static EntityFieldVariable EntityFieldVariable { get; private set; }
protected static EntityPropertyLoader EntityPropertyLoader { get; private set; }
protected static FunctionInvoker FunctionInvoker { get; private set; }
protected static string Variable { get; private set; }
protected static object EntityValue { get; private set; }
protected static object VariableValue { get; set; }
...
protected ResolveVariableStrategyBase() { }
internal ResolveVariableStrategyBase(
EntityFieldVariable entityFieldVariable,
EntityPropertyLoader propertyLoader,
FunctionInvoker functionInvoker,
string variable,
object entityValue,
object variableValue)
{ ... }
internal virtual object Execute() { ... }
}
还有几个这样的派生类:
internal sealed class RelationStrategy : ResolveVariableStrategyBase
{
internal override object Execute()
{
var result = resolveRelation();
base.VariableValue = result;
return resolveRelation();
}
...
}
真的是个好主意吗
-
在基类中具有静态属性,以便为所有派生类编写与基类相同的(内部)构造函数,所有参数设置基类的字段,如下所示:
internal RelationStrategy( EntityFieldVariable entityFieldVariable, EntityPropertyLoader propertyLoader, FunctionInvoker functionInvoker, string variable,
object entityValue, object variableValue) : base (entityFieldVariable,propertyLoader,functionInvoker,variable,entityValue,variableValue)
或者这只是懒惰优先于精心设计的代码?
什么是最优解?
【问题讨论】:
-
这是一个快速的解决方法,但代码的作者可能有其他解释,应该听到。
-
我对这段代码感觉不太好,想知道是否必须更改它。我自己编写了它,试图将现有功能重构为策略模式,但我并不完全幸运,因为我不确定这些静态属性是否是好的设计。
-
如果它有效,请不要修复它。 KISS 原则在这里很有帮助,因为我相当确定即使您不想向客户端发布蹩脚的代码,您也真的不想通过不必要的重构引入新的未知错误甚至没有被破坏的代码。
-
那么,如果我必须为尚不存在的代码做出设计决定,那么以这种方式实现它是否是一个好习惯?
-
不幸的是,有时良好实践会阻碍快速解决方案:/只要它有效,我认为它没有什么可怕的。但这并不完美,可能比在最上层的基类中拥有
static成员更好。
标签: c# oop properties static