I come from C world, and there we used “defines” to define different return values, values returned from C functions, like so:
#define RETURN_SUCCESS 0
#define RETURN_ERROR -1
int myFunc()
{
if(...) return(RETURN_SUCCESS);
else if(...) return(RETURN_ERROR);
}
How is this done in Java, the right way?
Suppose I have:
public MyObject findMyObject()
{
MyObject tempObject = search();
if( tempObject.type == myType )
{
return tempObject;
}
else
{
return null;
}
}
Is it ok to return null?
Is there a more proper way of doing it?
It’s fine to return null. You’ll notice in the Java API it returns null sometimes or -1 where an Int is expected. Another option which is used often is to simply throw an exception if something goes wrong.
The question that tends to get most people and one you’re probably asking yourself now is “Well, when do I throw an exception and when do I just return null?” that question is answered pretty well here.