Firstly, there are bunch of questions on stackoverflow on null pointers - but could not find this one. It it existed and i did not find it then please spare my mistake.
Question is generic - if a function returns just one element then how to deal with missing 'element' case. Eg: the sample code is just a sample.
public int findSmallestNumberGreaterThanX(int a[], int x) {
// do what ever logic.
if (numFound) { return smallesNumberGreaterThanX; }
else {
// what ??
}
}
If there was no number in array greater than x - what to do ?
Effective java mentions return empty array instead of null pointer - but is it worth creating an array if function returns single element ?
Next option is return null. I have seen bunch of posts which reject the idea of returning null.
Third is to return an object { boolean found; int value; } . This sounds like an overkill.
Please suggest me a best approach here.