>How to separate WinForm code

>A “normal” form contains lots of event handlers. Everything from click handlers to drag’n’drop and OnPaint. After a while they grow numerous and entangled enough to be a bug source of their own; whenever something is corrected there is a risc a new bug pops up.

I have a way of writing code to avoid this. For some time at least. :-)

The rule is that no control should be aware of another. (except in some simple cases) So the myButtonOnClick does not update any other control but only try-catch and call a method.
This means there are 50 event handlers in the form and as many methods. Some buttons do the same thing and call the same method but more often two different methods call a third one.

I split the form into regions. One is called “Event handlers” and another “Presentation logic”. Then there are other regions too when needed.
This way the code and logic is split naturally into the graphics and the logic behind it. If it smells like the top of 3 tier then you are right. Just because we talk about n-tier in a solution doesn’t mean it is not applicable on smaller parts too.

It comes naturally to work in one of the regions then, mostly in the Presentation logic region, and to not worry about the controls and their rendering.
If the form is Big then use partial class of dotnet2 and split the class into several files.

I have not found a natural way to name the methods handling the presentation logic.

Leave a Reply