Principle 7.7.2. EFFECTIVE DESIGN: Nested Method Calls.
Nested method calls are fine as long as there are not too many levels of nesting. The goal should be to produce code that is easy to read and understand.
smith:bg1s5xxx
mccarthy:2ffo900ssi
cho:biff4534ddee4w
String
parameter and returns a String
result:String getName(String str);
String getPassword(String str);
String
methods. We use the indexOf()
method to find the location of the delimiter—which is the colon, “:
” —in the name-password pair and then we use substring()
to take the substring occurring before or after the delimiter. It may be easier to see this if we take a particular example:INDEX: 1 2
INDEX: 012345678901234567890
jones:b34rdffg12 // (1)
cho:rtf546 // (2)
substring(0,5)
. To take the password substring, we would use substring(6)
. Of course, in the general case, we would use variables to indicate the position of the delimiter, as in the following methods:posColon
and result , to store the intermediate results of the computation—that is, the index of the “:
” and the name or password substring.return str.substring(0, str.indexOf(':'));
str.indexOf(':')
is passed immediately as the second argument to str.substring()
. This version dispenses with the need for additional variables. And the result in this case is not unreasonably complicated. But whenever you are faced with a trade-off of this sort —nesting versus additional variables —you should opt for the style that will be easier to read and understand.