views:

38

answers:

2

In Windows Forms, C#, .NET 3.5, VS2008...

What's a good way to isolate the code for a MenuStrip (or any complex control group), and it's child menu items, from the rest of my form?

For example, when I have a MenuStrip with a number of menus and each menu has a number of menu items, which all have click events, a ton of code is spewed into both the Form.Desinger.cs file and also the Form.cs file. This is not causing any problems technically, but just feels wrong to have so much stuff all dumped in one place (along with everything else in the form).

Running the Code Metrics on my entire project, the form is flagged as having the worst Maintainability index of any project file. Normally, I'd not be too dogmatic about heeding the direction of the Code Metrics tool, but in this case I totally agree.

According to Code Metrics, the form violates these best practices:

  1. Too much class coupling
  2. Too many lines of code
  3. Overall low maintainability

Possible solutions to isolate the MenuStrip from the rest of the form:

  1. Stuff it into a UserControl
  2. Other ideas?
A: 

I think you should take care about isolate business logic from presentation logic, for instance does not place too much code in click handlers or implement commands for menu items.

Get sure your code metrics does not touch generated code or don't pay attention to bad metrics in autogenerated code.

STO
A: 

Can you disable or filter your CodeMetrics from grabbing *.Designer.cs, for example?

If not, I would use a Factory class so that you can create these structures in one line. The down side to this, is that it reduces the functionality of the Designer. In the factory, you could name each component based on a template string + "_FileMenu", for example, so that you could set the base "name" in the Factory constructor.

To reduce code spew in your Form.cs file, consider more of a MVC approach, so that when the designer generates, say a private void button1_Click method, you abstract some business logic to other methods of other classes. So instead of moving all your files, button1_Click will call InitiateMoveFileMethod( string source, string destination ), for example.

maxwellb