tags:

views:

274

answers:

4

I tend to implement UI functionality using fairly self-documenting void doSomething() methods, i.e. if the user presses this button then perform this action then enable this list box, disable that button, etc. Is this the best approach? Is there a better pattern for general UI management i.e. how to control when controls are enabled/disabled/etc. etc. depending on user input?

Often I feel like I'm veering towards the 'big class that does everything' anti-pattern as so much seems to interact with the 'main' form class. Often, even if I'm including private state variables in the class that have been implemented using a relatively modular design, I'm still finding it grows so quickly it's ridiculous.

So could people give me some good advice towards producing quality, testable, decoupled WinForms design without falling into these traps?

A: 

I would only put UI logic in the Form class and put any application logic in its own class:

class Form1 : Form
 {  
    void Button1_Click
     { 
       Program.DoCommand1();
     }
 }


static class Program
{
  internal static void DoCommand1() {/* ... */}
}
Mark Cidade
+11  A: 

You can try MVP if you want to put the logic of the UI in a separate class..

In model view presenter just as Martin Fowler or Michael Feathers say, the logic of the UI is separated into a class called presenter, that handles all the input from the user and that tells the "dumb" view what and when to display. The special testability of the pattern comes from the fact that the entire view can be replaced with a mock object and in this way the presenter, which is the most important part, can be easily unit tested in isolation.

Gulzar
+3  A: 

using the MVP pattern is pretty good with winforms.

have a look at http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf

Keith Nicholas
Also: http://codebetter.com/blogs/jeremy.miller/articles/129546.aspx
KiwiBastard
A: 

One thing I have been dong lately is leveraging the partial class feature of .NET for some of these larger type forms. If I have a tab control with 5 different tabs on it. I'll create partial classes and name the files CardImportMethods.cs, ManageLookupTables.cs, etc. while leaving it all a part of the CentralizedForm class.

Even with just the UI logic, having this breakdown has helped when it comes to managing those things.

Dillie-O