I find that I often make a recursive call just to reorder arguments.
For example, here's my solution for endOther
from codingbat.com:
Given two strings, return
true
if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note:str.toLowerCase()
returns the lowercase version of a string.
public boolean endOther(String a, String b) {
return a.length() < b.length() ? endOther(b, a)
: a.toLowerCase().endsWith(b.toLowerCase());
}
I'm very comfortable with recursions, but I can certainly understand why some perhaps would object to it.
There are two obvious alternatives to this recursion technique:
Swap a
and b
traditionally
public boolean endOther(String a, String b) {
if (a.length() < b.length()) {
String t = a;
a = b;
b = t;
}
return a.toLowerCase().endsWith(b.toLowerCase());
}
- Not convenient in a language like Java that doesn't pass by reference
- Lots of code just to do a simple operation
- An extra
if
statement breaks the "flow"
Repeat code
public boolean endOther(String a, String b) {
return (a.length() < b.length())
? b.toLowerCase().endsWith(a.toLowerCase())
: a.toLowerCase().endsWith(b.toLowerCase());
}
- Explicit symmetry may be a nice thing (or not?)
- Bad idea unless the repeated code is very simple
- ...though in this case you can get rid of the ternary and just
||
the two expressions
- ...though in this case you can get rid of the ternary and just
So my questions are:
- Is there a name for these 3 techniques? (Are there more?)
- Is there a name for what they achieve? (e.g. "parameter normalization", perhaps?)
- Are there official recommendations on which technique to use (when)?
- What are other pros/cons that I may have missed?
Another example
To focus the discussion more on the technique rather than the particular codingbat problem, here's another example where I feel that the recursion is much more elegant than a bunch of if-else's, swaps, or repetitive code.
// sorts 3 values and return as array
static int[] sort3(int a, int b, int c) {
return
(a > b) ? sort3(b, a, c) :
(b > c) ? sort3(a, c, b) :
new int[] { a, b, c };
}
Recursion and ternary operators don't bother me as much as it bothers some people; I honestly believe the above code is the best pure Java solution one can possibly write. Feel free to show me otherwise.