How to avoid duplication of logic on two similar WinForms?

I have two forms: Form A and Form B. These forms should vary in appearance, but they have a lot of logic. The problem is that this logic is tied to appearance (push-button verification, triggering of events, etc.). For example, I have a name field, and when the save button is clicked, I need to fire an event that forces the parent form to check the record name to avoid duplication. Both forms need this logic, but their save buttons are in different places, and the tooltip displayed when an error occurs should also be displayed in another place. This is just one example, but does anyone know how I can avoid copying and pasting code here? Perhaps I am missing something obvious ...

+4
source share
5 answers

You can create an object with the data presented in both forms and place the verification logic in this object. The presentation level should fill this object with the entered data, ask the object to verify itself, and then process the verification errors formally.

+12
source

If the general logic is UI-related, you need to create your own form class (which inherits from the Form class) with the desired logic. then all you have to do is inherit this class in your forms.

If the common logic is smaller than the one associated with the UI, create an inner class that encapsulates the common logic and calls it from both forms.

+3
source

You need to add a controller between the two views and your common model. So you just need to do: myController.save (); instead, you need to call the model object to save them in both winform.

+3
source

There are several ways in which you can reorganize these forms to exchange logic. You can use one or more of them together:

  • Create user-specific bean objects that wrap your business object and add extra features that are shared between forms. This bean can do things like create tool tips, help with validation, events, etc.
  • Create a helper class with common functions. Summarize the logic of the two forms to call this helper class for common functions.
  • Enhance your business objects to complete your validation. I do not want to say that your BOs must know any user interface, but they can / must enforce business rules. This can bring some of the validation logic out of your forms and into a common place.
  • Create custom controls that are specific to the type of data you are working with, and use these controls in two forms.
+1
source

You can also take a look at the CSLA Framework , I have used it quite successfully in past projects to help reduce the number of duplicate code between different user interfaces. It uses the capabilities of .NET data binding, but I do not think that for this it was necessary to use data binding in order to make maximum use of it.

+1
source

All Articles