Javaв„ў EE 5 Tutorial, The (3rd Edition)

One way to eliminate the duplication would be to send all the menu commands to the same handler method, look at the menu item that was actually clicked, and decide what to do then. The code might look sort of like this (untested):

void MenuAllInserts(object obj, EventArgs ea) { model.SetLines(textbox.Lines); model.SelectionStart = textbox.SelectionStart; string item = MenuItem(obj); if (item == "Insert &Section" ) model.InsertSectionTags(); else if (item == "Insert &Code" ) model.InsertCode(); PutText(textbox, model.LinesArray(), model.SelectionStart); }

In this code, the fiddling with the textbox and model would occur only once. Mission accomplished, if it can be made to work.

I did some experimenting with menus , and sure enough, you can cast the object obj to MenuItem and ask for its Text, as suggested there by the MenuItem(obj). So code like that just shown could work.

But now I m worried about something else. The Form object, in which this menu handler lives, is doing the translation between the menu item and the method to send to the model. That troubles me, as I ve mentioned before, because it doesn t feel like the proper function of the Form to do that, and it s hard to test.

Now, in Smalltalk, my favorite language, a common solution would be to use the menu item to look up the name of the method in a hash table and then just tell the model to perform that method. That would be much nicer. Transformed to C#, it would let our current method look like this:

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

And the extension to the method with the if statements is obvious. Of course, we would still need to do something nicer than the if statements, to factor the decision out of the Form, but we already have that problem, so we would be at least a bit better off. It might even be possible to send the textbox to the model and let everything happen over there. That would be good.

You may have noticed that we could already send the textbox over to the model, in the original code earlier, and that that would at least push the duplication issue over to the other side. Or we could send a standard message to the model, like InsertSomething(string menuItemText), and let the model decide what to do. If you noticed that, you re doing better than I did, because this particular chapter is a report on something already accomplished, not something I m working out as I go. And I did not think of that approach.

Категории