There goes the false dichotomy between recursive and iterative solutions.
Properly formed, you can represent one form just as easily and safely (and verifiably) with the other. In terms of verifying program correctness, it is easier to validate a functional program than an imperative program, but don't confound that with the validity of resursive vs iterative code.
Bad programming leads to bad code, which exists either way.
As to the value of a line of code, I put it at:
does it do what it is supposed to do without leaking?
That is, do I waste code? Or do I use it wisely?
Given, for example, this function to swap two integer values:
1 2 3 4 5 6
|
template <typename T>
inline
void swap( T& a, T& b )
{
a ^= b ^= a ^= b;
}
|
This is short and cute, but it is also
incorrect. There are too many things that can go wrong, besides the fact that it is undefined C and C++. Also, this code forgets to make sure that
&a != &b, a necessary extra line of code for this "one liner".
A better, more correct version is this:
1 2 3 4 5 6 7 8
|
template <typename T>
inline
void swap( T& a, T& b )
{
T x = a;
a = b;
b = x;
}
|
It turns out that the compiler is pretty good at optimizing stuff like this. It turns out that the compiler may, actually, all but eliminate that temporary (keeping it in registers). Even if it doesn't, it works better with modern CPU architectures, and is typically as fast as or faster than the XOR version.
Sure, it is "more" lines of code, but it is easier to read and understand, easier to verify and correct, and more efficient.
Each line does exactly what it should, the first leading directly to the last, without any fuzziness.
Hmm, perhaps I could have chosen a better example.
Also, I googled more reading on the XOR swap for you all:
http://en.wikipedia.org/wiki/XOR_swap_algorithm
Anyway...