views:

61

answers:

3

Are there any opinions on whether or not it is bad design to reuse a Form or Control in a WinForms .NET application by giving it multiple modes? I often find myself wanting to do this. I'll have some UI that needs to be used in multiple places and instead of reusing the code, I'll give the form a mode that determines things like what text is displayed, whether or not certain elements are visible, and also how the elements are positioned.

This always seems like a bit of a kludge though, so I was wondering if anyone solves this problem differently?

+1  A: 

I would say that as long as the form is "small" enough that modes do not create a maintenance nightmare, and, as long as the functionality of each mode is closely related, then it should be fine. At some point, you may need to split things off if maintenance becomes more of a hassle than it's worth.

For example, I have a form that functions as either a list of contact information for a give customer, or a general "search for a contact" form. In the constructor, whether I pass a customer ID or not tells the form what mode to be in.

HardCode
A: 

I do this only if the data being edited by the form is the same, but the context is different. In these cases I often pass the form a context enum and the form uses it to either enable/disable certain fields, or change certain text.

For instance, a form I have in an application right now allows me to edit "Channels" (multiplex channels). The Channel name is an editable field when I'm using the form to create a "new" channel. But when I'm editing an existing Channel the name is a key field that I don't want changed, so the field becomes disabled. It's the same exact form, but with the context the form determines whether that field is disabled/enabled.

In the end, I think it's a fairly common practice.

Chris Holmes
+2  A: 

I think it comes down to the extent that you are adding different modes to a single Form. A mode that hides a single checkbox for example is far easier to maintain than a mode that swaps out the majority of controls . Only you can decide where your Form is in this spectrum.

I would also try to identify and use techniques to minimize the complexity of multiple modes. Some ideas come to mind:

  • Adopt a layered approach to separate business logic from the display
  • Place families of related controls in a single reusable unit (such as a Panel or UserControl)
  • Use organizing controls such as a PropertyGrid which can reflect and display properties of the selected object instead of manually hiding or showing controls in the form baesd on the object's class.
Brian Ensink