A perfect blend of all things Dot Net
Scott Hanselman just posted his latest article in his weekly source code series. He shows various ways of producing the Fibonacci Sequence using various languages. I found it really interesting, for two reasons:
You see, I spend a lot of time refactoring. Sometimes too much. I have to ask myself why. It’s usually so that I can come back to the code later, and still understand what I was trying to do. Most of the time, conciser is better. But not always!
And that’s what I see in this post.
Suppose I had written this C# function (shamelessly stolen from Scott’s post):
Func<int, int> fib = null; fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Compare this to the C# 2.0 version:
static int Fibonacci(int x) { if (x <= 1) return 1; return Fibonacci(x - 1) + Fibonacci(x - 2); }
Apart from the fact that these methods actually give different answers (sorry, Scott), if I were to try to understand these methods 6 months after writing them, which one of the code samples would I be most glad of seeing again?
You see, most code only gets read again for two reasons:
In both cases, clever though it may seem, the first conciser version would probably cause more trouble. Now, don’t get me wrong, I’m all for good concise code, but XSLT is concise, and I hate debugging that.
Now, considering that in order to reuse the Func<int, int> function, I would have to pass the around, thus holding it in a static variable, or wrapping it in another class, it doesn’t actually turn out to be that practical after all. Concise, yes. Practical and readable, hmm.
So, while we have a very-much-by-Ruby-On-Rails-driven trend going to make code as beautiful as possible, don’t forget to not go too far. We have to be able to read code later on, remember.
Nithiwit
March 31st, 2008 at 7:36 am
the result of fibonacci is 0,1,1,2,3,5,8,13,21,…
when i input number 8, i want to output is 13 or input number 13 output is 21
Ps.help me please