Following is the code for lazy intialization of an instance member. This leaves me with question of when to perform parameter validation. In the code are 2 differenct functions performing NPE check one delays it, other does not. I chose the first option, but just curios to know whats the industry wide convention / best practice.
public class FreeMain {
private List<Integer> fooList;
FreeMain ( ) { }
/**
* This code does a check null pointer kind of just in time.
*
* @param barList
*/
public void putListExceptionCheckDoneLater(List<Integer> barList) {
if (this.fooList == null) {
if (barList == null) throw new NullPointerException();
this.fooList = barList;
}
}
/**
* In the even that fooList != null,
* throwing an exception would be of no benefit,
* since regardless of input, null or not, net effect would still be a no-op.
*
* @param args
*/
public void putListExceptionCheckDoneBefore(List<Integer> barList) {
if (barList == null) throw new NullPointerException();
if (this.fooList == null) {
this.fooList = barList;
}
}
public static void main(String[] args) {
}
}
This code is custom designed to ask a specific doubt, so please refrain from questions like why not use constructor to pass list ?
etc, or suggest code improvements which are not connected to this question.