The return type of a method gives the developer clues on what its function is doing.

For example:

Return Type

Meaning

boolean

There can be a valid/successful result (true) or an invalid/unsuccessful result (false).  Returning true or false is a normal occurrence.  

Tip: Any event that is not normally expected to occur can be identified with a thrown exception, but avoid using an exception to indicate an invalid result that will occur regularly.

Often a method that returns a boolean will have a name prefixed with “is....” or “has...” much like a getter for a boolean bean property.

eg. isValid( )

integer, long, float

The method does a calculation/lookup/comparison for which the result is a number.

Integer, Long, Float

The method does a calculation/lookup/comparison for which the result is a number.   The result of the method can also be null, which usually means “not set” or “invalid”.

String

The method does a calculation/lookup/comparison for which the result is a single word or phrase.  The result of the method can be null unless otherwise defined in the javadoc.

The following code is incorrectly using a non-blank string to indicate an invalid situation.

/**
 * Check if it is a 'valid' company name
 */
public static String checkCompanyName(String companyName)  
{
    if (!cs.isCompanyIn(companyName))  
    {
       return "Invalid company name:  " + companyName;
    }
   return "";
}

The checkCompanyName method uses its return value for two completely different purposes and neglects to explain important things:

  1. If a non-blank String is returned, it contains an error message.

  2. Will the method ever return a null String?

  3. If an empty “” String is returned, it is a valid company name.

This method should be changed to not use an error message at all:

/**
 * Checks a company name to see if it is one we will accept orders from.
 * @param companyName A company name.
 * @return true if the company name is known, false if not
 */
public static boolean isValidCompanyName(String companyName)  
{
    return companies.contains(companyName);
}

Much cleaner.  Note the appropriate use of javadoc as well.

blog comments powered by Disqus