Some methods try to do too many tasks at once.  To do this they usually encode lots of different unrelated return values in a String or similar type.  Consider the following method.

 * @return all the ability strings, separated by a '#' character.
 * If the returned string doesn't contain a '#' then it's an error
 * A return value of “0” means the player has no abilities
 * A return value of “dead” means the player is dead
public String getAbilities(String playerName)  

The special return values from getAbilities are many:

  • “healing#speed#strength#levitation” - delimited ability strings

  • “Error: Player not found” - an error message

  • “0” - an indication that no abilities are present

  • “dead” - the player is dead.

A nightmare for the caller who has to cater for each case.  As it turns out, the developer has coded what should probably be two separate methods into one.

public String[] getAbilities(String playerName)  
                                             throws PlayException;
public String isDead(String playerName);

Using the new methods:

  • Rather than use '#' to separate ability names, a neatly prepared array of values is returned by getAbilities().

  • Rather than return an error in getAbilities(), a PlayException is thrown.  The caller can defer handling this exception.

  • Rather than return “0”, getAbilities() returns an empty array to indicate no abilities, not null.

  • Rather than return “dead” a new method isDead( ) is called.

blog comments powered by Disqus