A Little Refactoring


As we were browsing, Paul noticed a menu item in my copy of Microsoft Visual Studio. The Edit menu had a new item: Refactor. He asked what that was, and I told him that I was trying the C# Refactory from Xtreme Simplicity, http:// www.xtreme-simplicity.net . To show him how it worked, I tried my first ever Extract Method using the tool. The two lines (SetLines and SelectionStart) that load the model seem to be at a different level of abstraction than the one line (PutText) that loads the TextBox, so I extracted a method with the tool, resulting in

 void MenuInsertSection(object obj, EventArgs ea) { 
GetText();
model.InsertSectionTags();
PutText(textbox, model.LinesArray(), model.SelectionStart);
}
private void GetText() {
model.SetLines(textbox.Lines); model.SelectionStart = textbox.SelectionStart;
}

That worked nicely , so I used that method in the other parts of the code, resulting in

 void MenuInsertPre(object obj, EventArgs ea) { 
GetText();
model.InsertPreTag();
PutText(textbox, model.LinesArray(), model.SelectionStart);
}
public void XMLKeyDownHandler(object objSender, KeyEventArgs kea) {
GetText();
if (kea.KeyCode == Keys.Enter && kea.Modifiers == Keys.None) {
model.Enter();
kea.Handled = true;
}
else if (kea.KeyCode == Keys.Enter && kea.Modifiers == Keys.Shift) {
model.InsertReturn();
kea.Handled = true;
}
PutText(textbox, model.LinesArray(), model.SelectionStart);
}

Very nice ”that simple change reduces duplication already. Still whining about the remaining duplication of the GetText() and PutText(), I mentioned that I thought delegates would handle the problem and that we d probably have to subclass MenuItem to get it to work. Paul asked me to explain delegates to him. Like most of us, he had used them in forms, and like me, the concepts wouldn t all fit into his brain at the same time. So we babbled about delegates for a while.

Paul asked why I thought we d have to subclass MenuItem, and I explained that we would want all the menu items to go to just one handler, and that if we did that, the handler would have to interrogate the menu to find out what method to call in the model. I had been holding off on removing that duplication, because building that subclass seemed like too big a bite and I couldn t see a smaller one.




Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net