应该构造函数接受参数还是应该创建setter? [英] Should constructors accept parameters or should I create setters?

查看:141
本文介绍了应该构造函数接受参数还是应该创建setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个选择。要么在其构造函数中接受许多参数,要么创建许多setter方法和init方法。我不知道哪个是首选项,应该在构造函数中接受一些参数,而其他可以通过setter手动设置?



这是一个相关的问题,我也是:

如果在创建对象之后,您必须调用 set init 才能真正使用它... well ,这只是一个可怕的设计。



如果对象是可用的,没有一些成员初始化你想要的方式,你可以稍后设置。 p>

这里的黄金规则是 - 如果你创建一个对象,你应该能够使用它,而不做任何其他类型的初始化



扩展答案:



假设你有一个有10条边,10个角,一个颜色和一个名字的形状,可以连接到不同的形状。构造函数应该如下所示:

  MyShape(Point c1,Point c2,...,Point c10,Color c,Name n)

如你所见,我省略了连接的形状,因为它可以明智地设置为 NULL 如果当前对象未连接。但是,在没有任何其他参数的情况下,对象是无效的,因此它们应该在构造函数中设置。



可能的重载参数)可以是:

  MyShape(点c1,点c2,...,点c10,颜色c,名称n ,
MyShape * connectedShape / * = NULL * /)


I have two options. Either make a class that accepts a lot arguments in its constructors, or create a lot of setter methods and an init method. I'm not sure which is preferred option, should some arguments be accepted in constructors, while others could be manually set via setter? Or am I over-thinking this?

This is a relevant question, also by me: How to deal with constructor argument names?.

解决方案

If after you create an object you have to call set or init to actually use it... well, that's just an awful design.

If the object is usable without some of the members initialized the way you want them to be, you can set them later on.

The golden rule here is - if you create an object, you should be able to use it without doing any other sort of initialization.

Expanding on the answer:

Say you have a shape with 10 sides, 10 corners, a color and a name, that can be connected to a different shape. The constructor should look like:

 MyShape(Point c1, Point c2,...., Point c10, Color c, Name n)

As you can see, I've omitted the connected shape because it can sensibly be set to NULL if the current object is not connected. However, in the absence of any of the other parameters, the object isn't valid, so they should be set in the constructor.

A possible overload (alternitively a default argument) can be:

 MyShape(Point c1, Point c2,...., Point c10, Color c, Name n, 
                                      MyShape* connectedShape /*=NULL*/)

这篇关于应该构造函数接受参数还是应该创建setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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