Reordering arguments using recursion (pro, cons, alternatives)
Posted
by polygenelubricants
on Stack Overflow
See other posts from Stack Overflow
or by polygenelubricants
Published on 2010-04-04T08:42:37Z
Indexed on
2010/04/04
8:53 UTC
Read the original article
Hit count: 515
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
trueif 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
ifstatement 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?
© Stack Overflow or respective owner