Alex Rivera | Logout

Separating UI and logic in C#

Asked 2010-06-25T12:05:05.503
19

Does anyone have any advice on keeping logic out of my GUI classes? I try to use good class design and keep as much separated as possible, but my Form classes usually ends up with more non-UI stuff mixed in than I'd like, and it tends to make maintenance a real pain.

(Visual Studio 2008 Professional, C#, Windows apps).

Many thanks.

Edit
Report

2 Answers

6

The 3 layer architecture is what you are looking for.

You build 2 reusable layers:

  • Data Access Layer (DAL) which contains only the code needed to read/write from the database
  • Business Logic Layer (BLL) which consumes the DAL, contains business rules, validation, and provides a facade for the UI to use

Then on your UI project your reference the reusable layers and handle only the UI specific stuff. The UI project talks only to the BLL, with no direct connection to the DAL:

UI <---> BLL <---> DAL

You can have multiple UI layers that consume your reusable components, as well as multiple interchangable DALs if you want to support multiple database types.

answered 2010-06-25T12:14:03.013
5

You need to look into design patterns like:

Model-View-Controller (MVC) often used by web sites (ASP.NET)
Model-View-View Model (MVVM) often used by WPF

By keeping to one of these you should be able to keep the various parts of your application separate.

There are other patterns that do a similar job.

Also, developing with WPF can help as the UI is defined by the XAML and the code that does the work is the C#. This can provide a basic degree of separation. If you find yourself writing C# code that just manipulates the UI you can take a step back and think "should I do this in XAML?". Obviously there might be things you have to do in the code behind, but it's a start.

answered 2010-06-25T12:09:43.297

Your Answer