在OO语言中初始化对象属性的最佳实践 [英] Best practice for initializing object attributes in OO Languages
问题描述
这个问题对Java稍有强调,但适用于任何OO语言. 在类的声明中初始化类变量是否是一种好习惯?在我看来,显然是这样.它最大程度地降低了愚蠢的空指针异常错误的风险.
This question has a slight emphasis on Java but applies to any OO language. Is it good practice to initialize class variables in their declarations? It seems obviously so to me. It minimizes the risk of silly null pointer exception mistakes.
例如:
class myClass{
private String name = "";// initialize here
public myClass(){
//something
}
}
但是在某些教科书中,它们不会立即进行初始化.哪个更好?有关系吗?
But in some text books they don't bother to initialize straight away. Which is better? Does it matter?
推荐答案
最好不要初始化内联的一种情况是,您有多个构造函数以不同的方式初始化字段.在声明时初始化字段,然后将该值替换为稍后传递给特定构造函数的值,这样效率低下.
One case where it is better not to initialise inline is where you have multiple constructors that initialise fields in different ways. It would be inefficient to initialise your field at the declaration and then replace that value with a value passed to a specific constructor later.
这篇关于在OO语言中初始化对象属性的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!