构造函数逻辑代码味道是否取决于代码的类型或数量?
构造函数中的逻辑是一种代码味道。然而,是构造函数中的代码数量不好还是代码类型不好(构造函数中是否允许某些代码?)?
谢谢
Logic in a constructor is a code smell. However, is it the quantity of code in a constructor which is bad or the type of code (is there certain code which would be allowed in a constructor?)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
构造函数的主要目的是验证对象创建的上下文(参数、环境...)并在调用任何方法之前初始化实例。
例如,FileStream 的构造函数之一在参数中采用文件路径和文件模式,如果文件不存在,则会抛出异常。
IMO,只要您的代码是验证/初始化逻辑,它在构造函数中就完全有效,即使它代表很多代码。可疑的是构造函数中与上下文验证或实例初始化无关的代码。
The constructor's main purpose is to validate the context of the object creation (parameters, environment...) and to initialize the instance before any method can be called.
For instance, one of FileStream's constructors takes a file path and file mode in parameter and will throw an exception if the file does not exist.
IMO, as long as your code is validation/initialization logic, it is perfectly valid in a constructor even if it represents a lot of code. What could be fishy is code in a constructor that is not related to the validation of the context or the initialization of the instance.
代码是否可能引发异常是我在构造函数中避免的一件事。我尝试限制构造函数代码以严格初始化对象,并且仅在默认值不起作用的情况下 - 而且这种情况不会经常出现。
Whether or not the code could potentially raise an exception is one thing I avoid in constructors. I try to limit constructor code to strictly initialize the object, and only in cases where default values won't do - and that doesn't come up too often.