The reason for writing a function is not to reuse its code, but to name the operation it performs.My first pompous thought was something like, "how obvious." I was about to go back to work when a memory hit me out of no where. I remember very early in my career F5-hacking on some code and thinking about creating a method but worrying about not reusing it, or about someone else reusing it incorrectly, or about the extra lines of code the added syntax would add to my already 1000+ line Windows Form class.
— Tim Ottinger (@tottinge) January 22, 2013
I remember programming like that. There was a time, not long ago, when I didn't think I should extract a method unless I meant to use it more than once! And it's weird because I don't remember having the epiphany that took me from where I was then to where I am now. I once thought A, I now think B, and I don't remember changing my mind. It's an interesting lesson in the way the mind works. And it reminded me that everyone was a newbie once, and that most likely, I still am a newbie I just haven't figured it out yet.
It is something I have to explain pretty often. There are really three reasons.
ReplyDelete1) Give it a name so the code makes sense without spelunking
2) Give it independence (so you can pass it around, migrate it, test it)
3) So you can call it from multiple places.
A big "discussion" was going on about whether to extract methods or not (programmers with an average 8 years experience, no less!) and the "don't extract" crowd were all hinging their arguments on paying for a function call when it's not going to be shared.
So, this was my contribution to that argument, and I thought I'd try it out on twitter. You'd be amazed how much it is being retweeted and favorited.
You're right, of course. It should be something we learn in our first year. Heck, it should be in the "how to program" texts. But a lot of people never have that epiphany.
BTW: I've been programming 33 years. :-)
Thanks! Yeah, I knew you weren't really a noob... lol. I've been reading your blog for as long as I've been reading blogs, so no offense intended. I actually updated the post because you made me realize I wasn't communicating what I intended with that... Sorry!
Delete