The meaning of life is to explore the world

Returning null trap

Posted on By Jason Liu

Problem
In the example below, GetData_1() throws null pointer exception whereas GetData_2() returns a value. Why?

Class Example
{
	// DbRepo implements DbInterface which has a `Data Query()` method
	DbInterface dbRepo = new DbRepo();
	// Class Data is already defined with public member m
	public Data GetData_1 () { Data d = dbRepo.Query(); return d.m; }
	public Data GetData_2 () { return dbRepo.Query()==null ? new Data().m : null; }
}

Cause
The Query() function may be unmanaged that the return value is destructed.
Or Query() fails to convert the return value into the Data class.