Reputation: 238
Is it a good practice to have all the fields equal to null and just create them when they are required ?
public class Products {
private Map listofProducts = null;
private Owner owner = null;
private List<listOfProductsResults> listofProductsResults = null;
private String fileName = null;
private long id = 0L;
public Products(){
}
In this way whenever a method needs each of them I do the following
if(listOfProducts == null){
this.listOfProducts = new HashMap();
}
Upvotes: 2
Views: 862
Reputation: 27356
private Map listofProducts = null;
and
private Map listOfProducts;
Are equal statements, so no. It is pointless and I really don't like the look of the code with this.
Upvotes: 1
Reputation: 6410
Java auto initializes objects to null, but sometimes setting it to null explicitly can be a form of documentation if nothing else. For example, normally one would expect a constructor to initialize instance attributes. The one property explicitly initialized to null could say "this is not initialized in the constructor" or "this uses lazy initialization, beware". That might signify to always proxy through a getter or expect access to be protected with a null check. But it would be up to you to establish such a pattern.
Upvotes: 0