被嵌套构造(或工厂方法)好,还是应该在每次做的所有初始化工作 [英] Is nesting constructors (or factory methods) good, or should each do all init work

查看:126
本文介绍了被嵌套构造(或工厂方法)好,还是应该在每次做的所有初始化工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是个好主意(从设计POV)嵌套调用构造函数重载新的或工厂式的方法呢?这主要是简单的构造,其中每个超载基础上的前一个。

Is it a good idea (from a design POV) to nest constructor calls for overloaded New or Factory style methods? This is mostly for simple constructors, where each overload builds on the previous one.

MyClass( arg1 ) { 
    _arg1 = arg1; 
    _otherField = true; 
    _color="Blue" 
}
MyClass( arg1, arg2) : this(arg1) { 
    _arg2 = arg2  
}
MyClass( arg1, arg2, arg3) : this(arg1, ar2) { 
    _arg3 = arg3; 
}

或用工厂方法:

static NewInstance(arg1 ) { 
   _arg1 = arg1;       
}
static NewInstance(arg1, arg2) {
   f = NewInstance(arg1);
   f._arg2 = arg2;
}
//... and so on



我可以看到一个双方的一些缺点

I can see a few drawbacks on both sides


  • 嵌套隐藏什么构造做

  • 未嵌套重复所有功能

那么,这样做是一个好主意,或者它设置了我的东西,我只是没有看到一个问题。出于某种原因,我感到不安这样做,主要是因为它划分为初始化责任

So, is doing this a good idea, or does it set me up for something I'm just not seeing as a problem. For some reason I feel uneasy doing it, mostly because it divides up the responsibility for initializing.

编辑:
@乔恩飞碟双向 :我现在明白为什么这是困扰我这么多。我是这样做倒退!我写了整个事情,甚至没有注意到,它只是闻到。其他大多数情况下,我有(即我写的),做你推荐的方式,但这个肯定不是我所喜欢这个工作唯一的一个。我也注意到,更复杂的问题我做了正确的,但简单的那些我似乎已经马虎。
我爱微编辑。我也很喜欢缩写词!

@Jon Skeet: I see now why this was bothering me so much. I was doing it backwards! I wrote the whole thing and didn't even notice, it just smelled. Most other cases I have (that I wrote), do it the way you recommend, but this certainly isn't the only one that I have done like this. I do notice that the more complicated ones I did properly, but the simple ones I seem to have gone sloppy. I love micro edits. I also like acronymns!

推荐答案

我认为这是合理的链构造在一起,但我做的其他方式 - 用更少的参数调用版本具有更多参数的版本。这样,它非常清楚发生了什么,所有的真正的逻辑(超出默认值)是在一个地方。例如:

I think it's reasonable to chain constructors together, but I do it the other way - the version with fewer parameters calls the version with more parameters. That way it makes it very clear what's happening, and all the real "logic" (beyond the default values) is in a single place. For example:

public Foo(int x, int y)
{
    this.x = x;
    this.y = y;
    precomputedValue = x * y;
}

private static int DefaultY
{
    get { return DateTime.Now.Minute; }
}

public Foo(int x) : this(x, DefaultY)
{
}

public Foo() : this(1, DefaultY)
{
}

请注意,如果您有大量的构造函数重载的,你不妨动静态工厂方法代替 - 这通常使代码更清晰,以及允许多种方法来采取同样的参数设置,如:

Note that if you have lots of constructor overloads, you may wish to move to static factory methods instead - that usually makes the code clearer, as well as allowing multiple methods to take the same set of parameters, e.g.

public static XmlDocument FromText(string xml)

public static XmlDocument FromFile(string filename)

这篇关于被嵌套构造(或工厂方法)好,还是应该在每次做的所有初始化工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆