2

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?

Danijel
  • 8,198
  • 18
  • 69
  • 133

3 Answers3

5

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.

Community
  • 1
  • 1
Aidanc
  • 6,921
  • 1
  • 26
  • 30
4

Using return code to indicate errors in Java is an anti-pattern. You should use exceptions instead.

If an error is due to a programming error (invalid parameters, incorrect state), throw an instance of unchecked exception.

When the error is because something went wrong in the environment (cannot connect to a server, cannot find a required file), throw a checked exception.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

It is always OK to return something that respects the specifications you define. Hence, if you define in the documentation (javadoc and tests) which situations may cause a null to be returned, then you can return it without further ado.

You must also understand that being hostage to error codes (like your C code) is not the best tactic in Java. Some might even consider it to be an antipattern. It is more common to use exceptions. Given that you are new to Java, consider reading the tutorial at http://docs.oracle.com/javase/tutorial/essential/exceptions/ for more information.

rlinden
  • 2,053
  • 1
  • 12
  • 13