I spent some time today debugging a huge, huge function. I remember one of the quotes a professor of mine told me about function length. It might of been about class length, actually.
"Never write a function longer than your screen."
I think its a good rule. There's something to be said for being able to sum up a piece of code just by looking at it. Did you know that .NET does the same thing behind the scenes? And that it has trouble with huge functions?
Enter Inlining
From what i understand, back in the C++ days, programmers used to be able to specify what functions would be embedded into the calling function. The advantage was one less function that the execution would have to call--because on execution of a function "some stuff happens" that i'm not going to go into here. The point i'm trying to make is that if you didn't call that function, you wouldn't have to do "that stuff." So, instead of putting that piece of reusable code in every place they wanted it to go, they kept DRY and marked it to be inlined--for the compiler to manually place it in every place it was called.
.NET Inlines for You
It's true. .NET will inline your code for you during JIT if it deems it a good place to do so. But here's the catch: if you're writing functions that are miles long, there's no chance whatsoever that .NET can inline it and you'll never get the performance benefits of letting .NET upgrade your code.
Keep It Simple
Write functions that do one thing, really well. Make them reusable, testable pieces, and short enough that even .NET can sum them up...
No comments:
Post a Comment