Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Design & Architecture » The Zen of GUI Programming

The Zen of GUI Programming

This article describes some important rules to follow when creating an application that contains a presentation layer.

Author Rank:
Total page views :  15003
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

 Edited by Nina Miller

 

Figure 1 - Spaghetti Code in Action

Introduction 

On my last two projects I encountered a common design nightmare. The problem to which I am referring is a growing epidemic, familiar to all consultants who take on program applications previously developed by junior software developers. The problem is that the application logic is embedded inside of the GUI code. Code is designed in this faulty manner is the by-product of inexperienced software designers who believe they can simply skip the design phase of a project with no repercussions.. Bad code also results from using the RAD features in Visual Studio as a crutch to do everything conceivable in the GUI. The outcome?  A complete and utter mess of undecipherable code!   How often is this coding flaw seen in the industry? More times than you'd ever want to imagine. 

Why is Putting Application Logic in the GUI bad?  

Some junior programmers reading this article may be asking themselves this question. I certainly asked the question in my early days of programming. If I hear the question now, I cringe. Putting application logic in your GUI is a recipe for disaster for the following reasons: 

1) The code becomes unreadable. 

2) There is a tendency to compound cohesion when lumping application logic into GUI logic. 

3) Combinatorial problems pop up from the many inputs being tracked against the input into the application logic. 

4) The code becomes completely inflexible and almost impossible to maintain. 

5) The only way to change the face of the application will be to rewrite it. 

6) The application logic often contains expertise that you as a GUI programmer don't have, so the real expert (usually not you) has to go wading through your GUI code to tweak it.

 

7) It's hard to swap in  modular behavior. You could end up with a fat-fat client that is a resource hog and memory pig. 

Top Rules of a GUI Programmer 

You are on your way to becoming a very successful GUI programmer if you follow a few simple rules: 

1) Don't mix the application logic code in with the GUI code 

2) Don't mix the application logic code in with the GUI code 

3) Don't mix the application logic code in with the GUI code… 

 ... 

100) Don't mix the application logic code in with the GUI code 

Sound redundant? It is, but if this rule is drilled into your head and you follow it, you will be hailed as a hero by all your cohorts in the field. Another way to think of this is to ask yourself the following question: 

1) "Does every piece of code tailored to a specific function of expertise live in a different assembly or class?"  

What do I mean by this?  Next time you write an application and you are mucking around in the GUI, ask yourself the following question, "Before I go ahead and type this line of code, does the code require knowledge outside of the GUI?".  If the answer is yes, DON'T TYPE!!  Sit back and decide where the code should exist (outside of the GUI). Is there an assembly or class where that expertise belongs? Do I need to create an assembly or class to put that piece of expertise?   

Another question to ask yourself is: 

2) "Does the line of code I'm about to type inside the GUI have anything to do with presentation or input?" 

If the answer to the question is no, DON'T TYPE!!  It probably doesn't belong in the GUI. 

The only exception to putting non-presentation related code in the GUI is to call a nicely encapsulated API that handles the expertise outside the GUI. 

MVC 

A pattern called Model View Controller was created to help the application developer separate out the presentation layer (GUI) from everything else. The View (GUI) talks through the controller to the Model. The model contains the data and application logic.  Unfortunately, the way .NET is designed methods like event handlers which belong in a Controller end up in the View. This is another reason why inexperienced programmers regress into the habit of dumping application logic into the GUI. The environment is encouraging this behavior! Microsoft seems to have intended controller to be "taken care of" through .NET's internal plumbing. The way to tighten the controller concept is to create your own controller that lives in these event handlers and deals with communication from the view to the model through the controller's method calls. The model you are communicating with consist of a separate set of classes, interfaces, legacy dll, database, and/or hardware, that performs all the complex behavior(s) specific to the requirements of your application. The expertise of your application only lives inside the model and is isolated from the GUI (view). To understand more about how model-view-controller can interact with C#, check out Matt's article on MVC. 

Black Boxes 

When you start to design your model and are considering where all your expertise should live, make a clear distinction between the different types of expertise required by the system and create a list of categories to house them.  For example, I may have an application that requires logging, configuration management, reading a list of customers from a database, and running some scripts.  Each one of these functions requires completely different expertise  to implement, and they are all are mutually exclusive. Each function should be controlled by a different assembly or class (none of which live inside a Form class!). You can then define more specific functions that live inside each of these areas of expertise. For example, say you need to be able to log errors and log alerts. You may end up defining a method called LogError and LogAlert or Log(LogType x) or whatever fits your design needs. What you end up with is a black box defining that particular functionality,consisting of inputs and outputs. You don't care what lives inside.  Particularly, your GUI doesn't care what lives inside. In fact, your GUI should never have any knowledge of what lives inside. You may be laughing at this point, and saying, "Duh, I know that—hey, by the way, why not just use the WriteStream class in the middle of my Form to log stuff since it's already part of the .NET framework?". This is where the black box concept often falls apart in the hands of a beginning programmer. Inevitably, down the road the client will say, "Hey, can you print that log to the console, not a file please?"  At that point the novice GUI programmer finds himself going through every WriteStream and replacing it with Console.WriteLine. Multiply this sort of code changing a hundred-fold, and you end up with a pissed-off client.  This leads me to question number three: 

3) "Does the line of code I am about to type in my GUI have any low level framework calls?" 

If the answer to this question is yes, DON'T TYPE!!  All low level calls should be delegated into specific areas of expertise in the model and should never live inside the GUI (ever). 

Keeping it Simple 

How can someone tell at a quick glance whether a software design was applied to a C# Windows Form GUI or not? One way to tell is to open the main Form and look at the methods. If there are more than 20 lines of code in most of the methods there is a good chance that the GUI code contains application specific logic.  If the code is littered with loops within loops, if-else structures, and switch statements, I guarantee that the application logic is in the GUI. If the form is rigorously using the .NET library and low level classes, it probably contains application logic that doesn't belong there. Which brings me to my final question to ask yourself as a GUI programmer: 

4) "Does the lines of code I am about to type in my GUI require a lot of thinking?" 

If the answer to this question is yes, DON'T TYPE!!  You are probably ready to type in some horrendous structure that the next programmer will spend a good portion of his formative years debugging.  All the thinking should be in your well-designed model.  The GUI is stupid, mindless, and uncomplicated. Its only purpose in life is to accept input and present output. It should require very little thinking. The moment you find yourself thinking of some logic structure to put inside your GUI, please stop. It belongs in the model, period. 

Conclusion 

In my entire programming career, half of my responsibility was to clean up messy applications which had no boundaries between the presentation layer and the application logic. If you adhere to some of the rules in this article, a lot of bad code can be avoided. I know I am not alone here, so please feel free to tell your story in the comments at the bottom of the article. As more programmers become aware of the disasters that are easily created and difficult to fix, this knowledge will hopefully lead to better design and happier clients (and less work for me!), In the meantime, if you are new at this game, my best advice is: model your programming so that others will view your efforts with respect and admiration when working with C# and .NET.

 

 


Login to add your contents and source code to this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
I'm with ya Mike! by Matthew On March 13, 2008

It's always easier to just throw all our laundry in a pile in the corner of the room right now and get down to playing some serious XBox rather than folding everything neatly, organizing it and putting it away where it should go but in the long run it ends us being a MUCH bigger problem (especially when you can't find your pants and have to be at work in 15 minutes).

I think this is the reason many people find programming tedius and confusing. It really can be a fun and creative problem solving process if everyting is organized neatly and we don't have to spend time matching socks.

Knowing where things should go and having clear and consistant code organization (not only for ourselves, but also our fellow developers) is really the key to having a maintainable product and ultimately a rewarding career with C#.

Nobody likes digging through the pile of laundry to find the matching socks -- it is really mind-numbing.

Reply | Email | Delete | Modify | 
Re: I'm with ya Mike! by Mahesh On March 14, 2008
Unless you're a neat freek ;-)
Reply | Email | Delete | Modify | 
Very Helpful by Asif On March 14, 2008
Thanks for this great article. It surely "ll help in devolping a good software architectre
Reply | Email | Delete | Modify | 
Do I understand? by Greenway On March 21, 2008
I'm starting out on my first real WPF project and I want to get it right. Can you tell me if I understand the first 100 rules? I'll use a radio controlled car as the vehicle for communicating my understanding. Let the remote control be equal to the UI, the car is the business logic and the radio waves the communication between them. The car only understands forward, backward, left, right and sends out a speed signal in feet per minute. In the UI's code behind I'll do the calculations to convert the movement of a pen input via ink and sent those four directional messages to the car code. The UI code behind, can also listen for the speed signal and calculate and convert the speed into MPH for instance. Why do I need any more separation? The radio controller / UI doesn't know or have anything to do with how the car turns or how it is propelled. All the calculations in the UI are only for the UI. I can see an improvement, make it possible for them communicate via the inevitable better carrier wave. Provide snap in modules for car and remote that can use any communication standard. This way I can drive the car with a beat up old (winforms) remote or use a shinny new silverlight remote and I can move from 'class to class' communication on one machine to 'web services' for the really long distance stuff. There is code in the UI, but this ain't your daddies UI. Did I get it or am I screwed up?
Reply | Email | Delete | Modify | 
Re: Do I understand? by Mike On March 21, 2008

If you have a class that is separate from the remote that handles communication and another class that controls the car, these classes encapsulate the functionality for each.  You can call these classes through the UI.  If however, you are putting assembly code in your UI (Remote Control), however, to send signals like  PORT 1 = HIGH, then your code will look like cr*p.  It is okay to put UI related stuff in your form that is related to the form itself.  If the UI stuff is related to hardware or remote control, then it does not belong in the form directly.

 

 

 

Reply | Email | Delete | Modify | 
Re: Re: Do I understand? by Greenway On March 21, 2008
 

Thanks Mike

Separation of concerns or responsibility seems easy enough to implement in WPF. The other thing that get talk about allot is testability. I can see times when there will be lots of UI only code, say to convert some business valve into a 3D gizmo in silverlight, the complexity of the UI code may surpass that of the business and communication code. Then We'll need to break out a UI controller for testing. I think I'm getting it, maybe.

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.