java 应该在构造函数中放入多少代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/531282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How much code should one put in a constructor?
提问by user42155
I was thinking how much code one should put in constructors in Java? I mean, very often you make helper methods, which you invoke in a constructor, but sometimes there are some longer initialization things, for example for a program, which reads from a file, or user interfaces, or other programs, in which you don't initialize only the instance variables, in which the constructor may get longer (if you don't use helper methods). I have something in mind that the constructors should generally be short and concise, shouldn't they? Are there exceptions to this?
我在想应该在 Java 的构造函数中放入多少代码?我的意思是,你经常创建辅助方法,在构造函数中调用这些方法,但有时会有一些更长的初始化内容,例如从文件中读取的程序、用户界面或其他程序,在这些程序中,你不需要'不要只初始化实例变量,其中构造函数可能会变长(如果您不使用辅助方法)。我有一些想法,构造函数通常应该简短明了,不是吗?这有例外吗?
回答by krosenvold
If you go by the SOLIDprinciples, each class should have one reason to change (i.e. do one thing). Therefore a constructor would normally not be reading a file, but you would have a separate class that builds the objects from the file.
如果你遵循SOLID原则,每个类都应该有一个改变的理由(即做一件事)。因此,构造函数通常不会读取文件,但您会有一个单独的类来从文件构建对象。
回答by Marc Novakowski
Take a look at this SO question. Even though the other one is for C++, the concepts are still very similar.
看看这个 SO question。尽管另一个是针对 C++ 的,但概念仍然非常相似。
回答by Marc Novakowski
As little as is needed to complete the initialization of the object.
只需完成对象的初始化即可。
If you can talk about a portion (5 or so lines is my guideline) of your constructor as a chunk of logic or a specific process, it's probably best to split it into a separate method for clarity and organizational purposes.
如果您可以将构造函数的一部分(我的指导方针是 5 行左右)作为逻辑块或特定过程进行讨论,那么为了清晰和组织目的,最好将其拆分为单独的方法。
But to each his own.
但每一个他自己。
回答by Zach Scrivena
Constructors should be just long enough, but no longer =)
构造函数应该足够长,但不再是 =)
If you are defining multiple overloaded constructors, don't duplicate code; instead, consolidate functionality into one of them for improved clarity and ease of maintenance.
如果你定义了多个重载的构造函数,不要重复代码;相反,将功能整合到其中之一,以提高清晰度和易于维护。
回答by cletus
As Knuth said, "Premature optimization is the root of all evil."
正如 Knuth 所说,“过早的优化是万恶之源”。
How much should you put in the consructor? Everything you need to. This is the "eager" approach. When--and only when--performance becomes an issue do you consider optimizing it (to the "lazy" or "over-eager" approaches).
你应该在构造函数中投入多少?你需要的一切。这就是“急切”的做法。当 - 并且仅当 - 性能成为一个问题时,您会考虑对其进行优化(针对“懒惰”或“过度热切”的方法)。
回答by Paxic
Constructors should create the most minimal, generic instance of your object. How generic? Choose the test cases that every instance or object that inherits from the class must pass to be valid - even if "valid" only means fails gracefully (programatically generated exception).
构造函数应该创建对象的最小通用实例。有多一般?选择从类继承的每个实例或对象必须通过才能有效的测试用例 - 即使“有效”仅意味着正常失败(以编程方式生成的异常)。
Wikipedia has a good description :
维基百科有一个很好的描述:
http://en.wikipedia.org/wiki/Constructor_(computer_science)
http://en.wikipedia.org/wiki/Constructor_(computer_science)
A Valid object is the goal of the constructor, valid not necessarily useful - that can be done in an initialization method.
Valid 对象是构造函数的目标,valid 不一定有用——可以在初始化方法中完成。
回答by quant_dev
My customary practice is that if all the constructor has to do is set some fields on an object, it can be arbitrarily long. If it gets too long, it means that the class design is broken anyway, or data need to be packaged in some more complex structures.
我的习惯做法是,如果构造函数要做的只是在对象上设置一些字段,则它可以任意长。如果它变得太长,则意味着类设计无论如何都被破坏了,或者数据需要封装在一些更复杂的结构中。
If, on the other hand, the input data need some more complex processing before initializing the class fields, I tend to give the constructor the processed data and move the processing to a static factory method.
另一方面,如果在初始化类字段之前输入数据需要一些更复杂的处理,我倾向于将处理过的数据提供给构造函数并将处理移动到静态工厂方法。
回答by Swapnonil Mukherjee
Your class may need to be initialized to a certain state, before any useful work can be done with it.
您的类可能需要初始化为某种状态,然后才能使用它完成任何有用的工作。
Consider this.
考虑一下。
public class CustomerRecord
{
private Date dateOfBirth;
public CustomerRecord()
{
dateOfBirth = new Date();
}
public int getYearOfBirth()
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfBirth);
return calendar.get(Calendar.YEAR);
}
}
Now if you don't initialize the dateOfBirth member varialble, any subsequent invocation of getYearOfBirth(), will result in a NullPointerException.
现在,如果您不初始化 dateOfBirth 成员变量,任何后续的 getYearOfBirth() 调用都将导致 NullPointerException。
So the bare minimum initialization which may involve
所以可能涉及的最低限度的初始化
- Assigning of values.
- Invoking helper functions.
- 赋值。
- 调用辅助函数。
to ensure that the class behaves correctly when it's members are invoked later on, is all that needs to be done.
为确保类在稍后调用其成员时正确运行,这就是需要做的全部工作。
回答by Ramiz Uddin
Constructoris like an Application Setup Wizardwhere you do only configuration. If the Instanceis ready to take any (possible) Actionon itself then Constructordoing well.
Constructor就像一个应用程序安装向导,您只需在其中进行配置。如果实例准备好对其自身采取任何(可能的)操作,那么构造函数就做得很好。

