Is it a good practice to initialize variables, specially object references at class level? Please consider the following examples;
public class MyClass {
private static MyObject myObject;
public static void main(String[] args) {
myObject = new MyObject();
}
}
or
public class MyClass {
private MyObject myObject = new MyObject();
public static void main(String[] args) {
// Other code
}
}
Which way is best? Please guide me about the pros and cons of both.
Regards.
In general, lazy instantiation (the first snippet) is preferred since the object has a (potentially) shorter lifetime. You should favor the shortest object lifetime possible.
In my personal experience, its all about how expensive or detailed the object creation is. Secondly, you can also consider it as lazy creation vs active creation. I usually create objects at instance variable level if only constructor is involved. If there are further calls to initialize the member in question, then definitely the call will be moved to constructor or to a method where it needs to be initialized.
Thats why factory method pattern is used, to delegate the actual object creation to another class.
It depends on the scope that you want each field to have, and the memory footprint that you want your method to have. When you declare a field at Class level, the memory area is initialized for your fields at runtime. When you declare them at method level, the memory that is needed and initialized for those fields at execution time, and then when the method is finished the memory is flagged for garbage collection. At method level there is a possibility that the memory foot print of your class might shrink and grow as needed. If the method is never called, then do you really need those fields to be always available?
I have found that Class level fields are good for anything that you want to be static final
, or unchanged and unchangeable. Not necessarily a global variable so to speak, but pretty darn close to it. Unless of course you are creating a class that is a data transfer object, then everything that you want visible, or must be initialized would be at the Class level. Method level fields are good for something you need temporarily to perform a calculation.
Note that everything is initialized in java although objects are initialized to null.
You usually want to fail early (null pointer exceptions) so you don't want to initialize to a made up/arbitrary value so I would say in most cases don't initialize unless you know what the value should be at the outer classes creation time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With