Usability, MVC, ASP.NET

19. März 2008 00:56
by Henrik Stenbæk
1 Kommentare

Refactor: Extract Method

19. März 2008 00:56 by Henrik Stenbæk | 1 Kommentare

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.

refactor-extract-method1

Highlight the code you want to move to a new function, right click and select Refactor -> Extract Metod.

refactor-extract-method2

 

Give the function a nice name (getGreeting). Notice the signature preview show what parameters the function will be created with.

refactor-extract-method3 

The Page_Load after generating the getGreeting function - nice and easy to read ;-)

 refactor-extract-method4

The auto generated function takes 2 parameters and return a string

refactor-extract-method5

kick it on DotNetKicks.com