19. March 2008 00:56
by Henrik Stenbæk
I don’t know about you but I for my part often end out writing linear code.
Maybe it’s a hangover from writing to much BASIC code in the mid 80’s or maybe it’s just me thinking linear and not that much object-oriented. After all I often end up with “long functions” that includes code that could be isolated in “sub functions”.
Today one of my colleges pointed out the Refactor->Extract Method function. This function takes a part of your code and isolate it’s in a separate function.
Look at the code in this Page_Load: its includes some silly greeting stuff (just for the demo), the function is long and hard to read, lets try to separate the greetings part in a separate function.
Highlight the code you want to move to a new function, right click and select Refactor -> Extract Metod.
Give the function a nice name (getGreeting). Notice the signature preview show what parameters the function will be created with.
The Page_Load after generating the getGreeting function - nice and easy to read ;-)
The auto generated function takes 2 parameters and return a string