OOP 对象构造函数参数
我什么时候应该将参数传递给对象的构造函数?您使用什么标准将它们传递给构造函数而不是对象方法中的参数?
When should I pass arguments to the object's constructor? Which criteria do you use to pass them to the constructor instead of arguments in object's methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将对象的不可变属性传递给构造函数。如果可能,使所有对象属性不可变。充分考虑,这使得整个对象是不可变的。
在构造时分配的不可变属性可以避免各种竞争条件(特别是在多线程环境中),并有助于确保对象始终一致,从而消除多种错误的可能性。通过强制在构造时定义属性,您可以避免大量的错误检查代码。一旦整个对象可以是不可变的,就有机会共享等效对象,从而提高内存性能。
如果参数不是对象的不可变属性,那么在构造函数中分配它只是为了方便。一般来说,应该为它分配一个setter以降低代码复杂性(因为无论如何都需要setter)。如果构造函数被频繁调用,那么参数的便利性可能值得这种额外的复杂性。
Pass things to the constructor that are immutable properties of the object. When possible, make all object properties immutable. Taken to its full extent, this allows the entire objet to be immutable.
Immutable properties, assigned at construction, avoid a variety of race conditions (particularly in multi-threaded environments) and helps ensure that the object is always consistent, eliminating the possibility of many kinds of errors. By forcing properties to be defined at construction, you avoid extensive error-checking code. Once the entire object can be immutable, there are opportunities for sharing equivalent objects, improving memory performance.
If a parameter is not an immutable property of the object, then assigning it in the constructor is merely a convenience. In general, it should be assigned with a setter to reduce code complexity (since the setter is required anyway). If the constructor is called very often, then the convenience of parameter may be worth this extra complexity.
当我的对象非常简单(1 个或两个属性)时,我可以提供带有这些参数的构造函数。
但大多数时候,默认构造函数和我使用设置器设置属性。
When my object is very simple (1 or two attributes) i may provide a constructor with these arguments.
But most of the time, default constructor and i set my attributes with the setters.
通常,您在使用 new 关键字实例化类时将参数传递给类构造函数(这可能因语言而异)。
例如(此处选择 C / Java / C# 样式)
在重新阅读您的问题时,我倾向于对绝对必需的资源使用构造函数参数。这样,您就知道您的对象必须具有某些可用的属性或资源。
Generally you pass arguments to the class constructor when instantiating the class with the
new
keyword (this may differ depending on language).For example (opting for the C / Java / C# style here)
On re-reading your question, I tend to use constructor arguments for absolutely required resources. That way, you know your object must have certain properties or resources available.
基本上,您想要在构造函数中初始化对象的所有基本构建块。
但有时,该对象包含许多元素,从而使构造函数的参数列表太长。
我遵循以下准则:如果构造函数的参数列表超过 5 个元素,
新对象的初始化分为构造函数参数和构造函数参数。设置方法。
Basically you want to initialize all the basic building blocks of the object in the constrctor.
But sometimes, The object contains to many elements, thus making the argument list for the constructor too long.
I follow this guideline: If the argument list for a constructor is more the 5 elements,
the initalization of a new object is divided into constructor arguments & set methods.