This article is from the Bicycles FAQ, by Mike Iglesias with numerous contributions by others.
From: Bob Fishell <email@example.com>
For all Shimano SIS and Hyperglide systems, the chain is sized by shifting to
the smallest rear cog and the largest front sprocket, then sizing the
chain so that the derailleur pulleys are on a vertical line, or as close
as you can get to it. Note that this will result in the same chain length
for any freewheel within the capacity of the derailleur, so it usually is
not necessary to re-size the chain for a different cogset with these systems.
The other rule I've used (friction systems) involves shifting to the largest
chainring and the largest rear cog, then sizing the chain so that the pulleys
are at a 45 degree angle to the ground.
The rules probably vary from derailleur to derailleur. In general,
you may use the capacity of the rear derailleur cage as a guideline. You
want the chain short enough so the cage can take up the slack in the
smallest combination of chainwheel and rear cog you will use. The chain
must also be long enough so that the cage still has some travel in the
largest combination you will use.
For example, if you have a 42x52 crank and a 13x21 freewheel, the smallest
combination you would use would be a 42/14 (assuming you don't use the
diagonal). If the cage can take up the slack in this combo, it's short enough.
If the cage has spring left when you are in the 52/19 combo (again, you are
not using the diagonal), it's long enough.