At the moment my Form1 code is extremely heavy, mainly full of menu and control events. One thing I would like to do is organize it in some way, so I could expand or collapse "related code" (in Visual Studio).
My first attempt at this was to put code relating to the main menu, for example, inside a nested class called "MainMenu", which was within the Form1 class, so that I could simply collapse the nested class when I don't need it. This resulted in all sorts of problems (i.e. I couldn't find a way to set up the main menu inside this nested class).
Is there a simpler solution to this that I'm missing? Or can someone shed some light on why my nested class idea is faulty?
While #testalino's answer certainly does what you ask for, I would say that your real problem is probably related to code design. Chances are that the form class simply contains more code than it should, and that some of it ought to move into other classes.
If done in a good way, this might give you some benefits:
You will likely get more encapsulated (and less coupled) behavior, when various functions operates on data passed to the methods through parameters and return values instead of fetching and setting values directly in UI controls.
You might get a more testable code base (you do have unit tests, right?).
It will be easier for several persons to collaborate on the code, since the code is spread across several different code files. This reduces merging conflicts (you do have a source control system, right?). This point may not be as applicable if you are working on something alone, but it doesn't hurt to have this habit anyway.
You can use #region and #endregion to organize code within a class. These regions are then collapseable.
I suggest you using User Controls to encapsulate some of Form's behavior. This is the simplest solution available for you right now, I guess. You just pick some piece of user interface and extract it to user control and define some public properties accessible from the form.
Keeping all handlers in Form.cs is a bad, bad practice. You must avoid it because it's unmaintanable (I've seen much code like that, and at later stages adding or changing functionality is proven to be impossible without breaking anything, let alone changing the UI without affecting the way app works).
In future, you may want to try different approaches to separation UI from application logic, e.g. explore MVP/MVC patterns.
If your form has become so big and complex that you suddenly desire to organize it in some way it is a strong hint towards the need of refactoring, which will improve readability, testability and maintainablity of your code. How you actually refactor depends upon your actual code.
Is it a form that has a lot of controls? Think about splitting it up in separate UserControls where each of them displays a certain aspect of your domain data. Do you have a lot of interaction logic, reacting to a lot of events? Maybe introduce a some sort of Controller or EventAggregator.
There are a lot of well known patterns that can help you organize your UI and domain code. This series talks about just that and introduces you to patterns MVC, MVP, EventAggregator and much more. It discusses the patterns in the context of windows forms just as you need it.
Use the partial class keyword in order to split your class into several files.
I agree with what the other answers say about grouping alike event handlers together in #regions is solid given a massive number of events. In addition, if the code itself in the handlers is voluminous as well, you might want to think of refactoring those into logical business logic classes. Example:
pseudocode before:
private void SomeButton_Click(...)
{
using (FileStream fs = ...)
{
fs.Write(some form data);
fs.Write(some more form data);
}
DoMoreBusinessLogicStuff();
...
// lots more stuff
...
}
pseudocode after:
private void SomeButton_Click(...)
{
IBusinessObject obj = new BusinessObject(injectable form data);
using (IPersistence store = new FilePersistence(...))
{
obj.Persist(store);
}
obj.DoBusinessRules();
}
This should move business, persistence and support logic to their own classes and leave your event handlers as lightweight shells designed only to gather UI input and pass it along.
Nested classes are generally frowned upon as being only a slight upgrade from god-classes for one thing, and encapsulation and code reuse being pretty murky.
You should be aiming to express the objects you actually have as individual business classes within your code: one class, one file. Is there any particular reason you aren't doing this?
Depending on the type of code it is doing will depend on where you can move it.
If its processing data code then you can move this out into separate classes in a different namespace returning the processed data to controls to allow for data binding etc.
If Form1 is getting very heavy with code then is this because you've got too much going on in Form1? Could you break it out into a different/new form?
You could use the summary which is collapsible but I think this is more intended for providing other developers with information, always good practice though!
In VB:
''' <summary>
'''
''' </summary>
''' <remarks></remarks>
In C#
/// <summary>
///
/// </summary>
/// <remarks></remarks>
Related
My specific issue is an attempt to execute the Telerik DataBoundListBox method StopPullToRefreshLoading(true) from my ViewModel. The difficulty is that I do not want to break MVVM convention by putting application logic in the code behind.
I'm relatively new to MVVM and I'm not sure what the proper convention is for interacting with methods on controls on the view. I've done numerous searches on the topic and I've yet to find a solution that I can apply to my situation. I suspect I've probably come across the answer but I'm not drawing the proper conclusions.
It seems like this would be a common situation with 3rd party controls but maybe I'm just not thinking about the problem in the proper way.
I'm building my first Windows 8 Phone app using MVVM Light.
A lot of people get very hung up thinking that when following MVVM you MUST NOT HAVE CODE IN THE CODE BEHIND!!! This simply isn't the case, a design pattern like MVVM is there to make the code more maintainable. If something relates directly to the UI only and doesn't care about information in the viewmodel class then by all means put it in the code behind. I had the same situation when I was using third partly controls, sometimes there is no other option that isn't as bad or worse than putting code in the code behind.
First I agree with Chris McCabe on this, design patterns are a guideline, a framework, a suggestion. They are not rules to live-or-die by. That being said, you should be able to join the two (VM/Telerik) without introducing 'real' business logic into the UI.
The first possibility is to use an event on the controller. The UI can subscribe to this event to forward the call to the Telerik control; however, the UI should not decide when it is called.
class MyModel {
public event EventHandler StopRefreshLoading;
}
class myForm : Form {
public myForm(MyModel data)
{
data.StopRefereshLoading += (o, e) => this.CustomControl.StopPullToRefreshLoading(true);
// ... etc
}
Frankly, I prefer using interfaces for this type of behavior. It's then easy for the controller to force implementations to update to a new contract requirement. The downside is that the interfaces can become too verbose in a complex UI making them difficult to write tests for.
interface IMyModelView {
void StopRefreshLoading();
}
class myForm : Form, IMyModelView {
void IMyModelView.StopRefreshLoading()
{
this.CustomControl.StopPullToRefreshLoading(true);
}
Either direction you go some violation of the UI design pattern is likely to occur; however, in the real world there are no points for strictly adhering to a specific pattern. The patterns are there as an aid to make the code more reliable, testable, flexible, whatever. Decide why you are using a pattern and you will be able to evaluate when can safely violate that pattern.
I realize there is much discussion about singletons and why that are bad. That is not what this question is about. I understand the drawbacks to singletons.
I have a scenario where using a singleton is easy and appears to make sense. However, I want an alternative that will accomplish what I need without a lot of overhead.
Our application is designed as a client that typically runs on laptops in the field and communicates with a back end server. We have a status bar at the bottom of the main application. It contains a few text areas that show various statues and information as well as several icons. The icons change their image to indicate their state. Such as a GPS icon that indicates if it is connected or not as well as error state.
Our main class is called MobileMain. It owns the status bar area and is responsible for creating it. We then have a StatusBarManager class. The StatusBarManager is currently a static class, but could also be a singleton. Here is the start of the class.
public static class StatusBarManager
{
static ScreenStatusBar StatusBar;
/// <summary>
/// Creates the status bar that it manages and returns it.
/// </summary>
public static ScreenStatusBar CreateStatusBar()
{
StatusBar = new ScreenStatusBar();
return StatusBar;
}
The MobileMain asks the StatusBarManager for a StatusBar. It then uses the StatusBar. No other classes see the StatusBar, just the StatusBarManager.
Updates to the status bar can come from pretty much anywhere in the application. There are around 20 classes that can update the text areas on the status bar and additional classes that update the icon states.
There will only every be one StatusBar and one StatusBarManager.
Any suggestions for a better implemention?
Some thoughts that I had:
Make the StatusBarManager an instance class. In my MobileMain class hold onto a static public instance of the StatusBarManager class. Then to do status bar updates you would call MobileMain.StatusBarManager.SetInformationText or some other method of the manager. The StatusBarManager would not be a singleton, but the MobileMain would only be creating a static instance of it. The issue here is that MobileMain now has a StatusBar and a StatusBarManager, which just manages the StatusBar it owns. Still also have a globally avaialble static instance to the StatusBarManager, just a different owner.
Another idea was to use something like an EventEggregator class. I've never used one, but have read about them. I guess the concept is that it would be a globally available class. In each class that wants to update the status bar it would publish a StatusBarUpdate event. The StatusBarManager would be the only classes subscribing to the StatusBarUpdate event, and receive all of the notifications. I've read though that can end up with leaks with this approach if you are not carefull with unsubscribing from events when cleaning up objects. Is this approach worth looking into?
I prefere Static classes that hold your objects. So the amount of objects you can access is restircted by the interface your static class offers. Static is not bad as long as your application still scales.
Another good alternative to singletons is the Monostate pattern, where you have a class that implements private static fields to represent "singleton" behavior.
See:
Monostate
Monostate vs. Singleton
UPDATE:
It often helps me to keep a REST like api in mind, even for internal program structures. Having one class that is updated from everywhere and sends notices to everybody is hard to control in respect to raise conditions and infinity loops (Update -> Event -> Update -> ...)
Build an (static or not) Status bar interface that you can access where you need it. Through a Static class where you get access to your Status bar interface or by dependency injection if you use such techniques (not recommended for smaller projects). Every call to your status bar interface has to be independent from any events that might be raised by the Status bar to avoid further issues with raise conditions. Think of the status bar interface like a website that can be called from other parts of the program to push and pull information.
Having a StatusBar class or a StatusBarManager class or not is not a big deal. But having many classes in your app know about StatusBars and StatusBarManagers is a bad idea, it will cause strong coupling, and some day probably pain.
How?
Imagine that the components that currently report status to a status bar have to be reused in another app that
- uses a text console to report status?
- reports status to multiple places?
or
- doesn't report status at all!
Best alternative:
-Event listening. Expose a Status Changed event on your class (you can use a callback), or perhaps on an existing shared resource that your classes have in common. Other parties, like your status bar, can subscribe to the event. And should unsubscribe whenever the subscription is no longer needed/valid, to prevent leaks, as you mention!
-Since you've tagged WPF, for WPF, having a dependency property 'StatusText', might seem like another tempting option, with this approach when you have multiple status properties, you need a way of figuring out which one is telling you the most interesting status that needs to be displayed on your status bar now! Which could be a binding, multibinding (blech, complexity), or dependency property changed event handler.
However - I would advise you to keep DependencyObjects and DependencyProperties limited to your UI layer as much as possible. The reason is that they rely implicitly on a Dispatcher on the UI thread, and so can't be adapted easily for non-UI chores.
Since there are many different parts of your app you may also possibly find it's reasonable to have a combination of both of these, using some one place and some another.
You could simply use the Observer pattern and add the StatusBar as a listener to your 20 objects. This will eliminate the singletons and better follow SRP and DIP, but you will have to consider whether it is worth the effort. A singleton may be better if the indirection adds too much complexity and dependency injection is not possible.
public class StatusBar implements StatusListener {
}
public interface StatusListener {
public statusChanged(String newStatus)
}
Classes will depend implicitly on any use singleton and explicitly to any parameters in the constructor. I would suggest adding an interface to the singleton, so just the methods needed would be exposed to the classes using the IStatusBar. This is more code, but will ease unit testing.
It's hard to give advice without knowing more of your application's architecture, but perhaps you should consider dependency injection. For example, pass a StatusBar instance to the constructor of each class that directly uses it.
I have a big winform with 6 tabs on it, filled with controls. The first tab is the main tab, the other 5 tabs are part of the main tab. In database terms, the other 5 tabs have a reference to the main tab.
As you can imagine, my form is becoming very large and hard to maintain. So my question is, how do you deal with large UI's? How do you handle that?
Consider your aim before you start. You want to aim for SOLID principles, in my opinion. This means, amongst other things, that a class/method should have a single responsibility. In your case, your form code is probably coordinating UI stuff and business rules/domain methods.
Breaking down into usercontrols is a good way to start. Perhaps in your case each tab would have only one usercontrol, for example. You can then keep the actual form code very simple, loading and populating usercontrols. You should have a Command Processor implementation that these usercontrols can publish/subscribe to, to enable inter-view conversations.
Also, research UI design patterns. M-V-C is very popular and well-established, though difficult to implement in stateful desktop-based apps. This has given rise to M-V-P/passive view and M-V-VM patterns. Personally I go for MVVM but you can end up building a lot of "framework code" when implementing in WinForms if you're not careful - keep it simple.
Also, start thinking in terms of "Tasks" or "Actions" therefore building a task-based UI rather than having what amounts to a create/read/update/delete (CRUD) UI. Consider the object bound to the first tab to be an aggregate root, and have buttons/toolbars/linklabels that users can click on to perform certain tasks. When they do so, they may be navigated to a totally different page that aggregates only the specific fields required to do that job, therefore removing the complexity.
Command Processor
The Command Processor pattern is basically a synchronous publisher/consumer pattern for user-initiated events. A basic (and fairly naive) example is included below.
Essentially what you're trying to achieve with this pattern is to move the actual handling of events from the form itself. The form might still deal with UI issues such as hiding/[dis/en]abling controls, animation, etc, but a clean separation of concerns for the real business logic is what you're aiming for. If you have a rich domain model, the "command handlers" will essentially coordinate calls to methods on the domain model. The command processor itself gives you a useful place to wrap handler methods in transactions or provide AOP-style stuff like auditing and logging, too.
public class UserForm : Form
{
private ICommandProcessor _commandProcessor;
public UserForm()
{
// Poor-man's IoC, try to avoid this by using an IoC container
_commandProcessor = new CommandProcessor();
}
private void saveUserButton_Click(object sender, EventArgs e)
{
_commandProcessor.Process(new SaveUserCommand(GetUserFromFormFields()));
}
}
public class CommandProcessor : ICommandProcessor
{
public void Process(object command)
{
ICommandHandler[] handlers = FindHandlers(command);
foreach (ICommandHandler handler in handlers)
{
handler.Handle(command);
}
}
}
The key to handle a large UI is a clean separation of concerns and encapsulation. In my experience, it's best to keep the UI free of data and functionality as much as possible: The Model-View-Controller is a famous (but rather hard to apply) pattern to achieve this.
As the UI tends to get cluttered by the UI code alone it's best to separate all other code from the UI and delegate all things that don't concern the UI directly to other classes (e.g. delegating the handling of user input to controller classes). You could apply this by having a controller class for each tab, but this depends on how complicated each tab is. Maybe it's better to break a single tab down into several controller classes themself and compose them in a single controller class for the tab for easier handling.
I found a variation of the MVC pattern to be useful: The passive view. In this pattern, the view holds nothing more than the hierarchy and state of the UI components. Everything else is delegated to and controlled by controller classes which figure out what to do on user input.
Of course, it also helps to break the UI itself down into well organized and encapusalted components itself.
I would suggest you to read about the CAB ( Composite UI Application Block ) from Microsoft practice and patterns, which features the following patterns : Command Pattern, Strategy Pattern, MVP Pattern ... etc.
Microsoft Practice and patterns
Composite UI Application Block
What's your opinion about using #region folding using application semantic, instead of folding for "syntax".
For example:
#region Application Loop
#region User Management
#region This Kinf of stuffs
instead of
#region Private Routines
#region Public Properties
#region ThisRoutine // (Yes, I've seen this also!)
In this logic, I'm starting fold even routine bodies. I'm starting to love #region directive (even using #pragma region when using C++!).
That would suggest you're doing too much in one type - why would an "application loop" be in the same type as "user management"? If you find yourself wanting to do this, consider splitting the functionality into different types.
Typically I use regions for interface implementations, Equals/GetHashCode overrides, and operators - but that's usually all.
The only time I use a region is to hide something like a bunch of non-implemented interface methods or a bunch of code which is for the chop but I'm not quite ready to kill it.
I tend to think if it needs folding to help you keep track of it all there is too much code in the file (or maybe another general code smell [or is the folding the smell?]) and if it doesn't need folding the only thing folding will achieve is frustrating people who have to go looking for code which should be on display.
I'm not a fan of hiding code from myself.
I prefer dividing my code into regions based on syntax, because I can easily find the constructor, overridden methods and so on...
I use regions to group methods with a common/related purpose.
So, rather than public, protected, private regions, think of "Initialisation", "Load and save", "Event handlers", etc.
The purpose of this is for the folded class to act as a summary or overview of the functionality, and make it easy to find the parts you are looking for. Ideally, you will generally settle on a few standard region "types" that you use throughout your application's classes so that they are all consistently subdivided.
I've seen developers who do this in the past and the end result is rarely good. The problem is with the expectation that those who follow will understand the groupings and correctly identify the correct region for their additions. In my experience what tends to happen is that, at best, one ends up with a proliferation of new regions, one per each functional change and, at worst, new methods junked in any old place or regionless at the end of the class.
I'd say go with a scheme that is obvious. The most common is the 'Private Fields/ Public Fields / Private Properties / Private Methods / Public Properties / Public Methods' scheme. (Personally I favour grouping by visibility: 'Public / Internal / Private' with the more visible members at the top as that is what a casual visitor to a class is going to be interested in first and what goes where is still blindingly obvious.)
This question already has answers here:
Order of items in classes: Fields, Properties, Constructors, Methods
(16 answers)
Closed 9 years ago.
Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?
Here's what I normally do, but I'm wondering if there's a standard way?
Nested Classes or Enums
Fields
Properties
Events
Constructors
Public Methods
Private Methods
Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.
Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.
I tend to use Microsoft StyleCop, which has a set order according to rule SA1201:
Cause An element within a C# code
file is out of order in relation to
the other elements in the code.
Rule Description A violation of this
rule occurs when the code elements
within a file do not follow a standard
ordering scheme.
To comply with this rule, elements at
the file root level or within a
namespace must be positioned in the
following order:
Extern Alias Directives
Using Directives
Namespaces
Delegates
Enums
Interfaces
Structs
Classes
Within a class, struct, or interface,
elements must be positioned in the
following order:
Fields
Constructors
Finalizers (Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Complying with a standard ordering
scheme based on element type can
increase the readability and
maintainability of the file and
encourage code reuse.
When implementing an interface, it is
sometimes desirable to group all
members of the interface next to one
another. This will sometimes require
violating this rule, if the interface
contains elements of different types.
This problem can be solved through the
use of partial classes.
Add the partial attribute to the class, if the class is not already
partial.
Add a second partial class with the same name. It is possible to place
this in the same file, just below the
original class, or within a second
file.
Move the interface inheritance and all members of the interface
implementation to the second part of
the class.
I think there's no best way. There are two important things to consider when it comes to layout. The first most important thing is consistency. Pick an approach and make sure that the entire team agrees and applies the layout. Secondly, if your class gets big enough that you are searching for where those pesky properties live (or have to implement regions to make them easier to find), then your class is probably too large. Consider sniffing it, and refactoring based on what you smell.
To answer the reshaper question, check under Type Members Layout in Options (under the C# node). It's not simple, but it is possible to change the layout order.
I don't believe regions are necessarily a sign of bad code. But to determine that you will have to review what you have. As I've stated here this is how I regionize my code.
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
But the main thing is keeping it consistent and purposeful.
I tend to clump private data and tend to clump related methods/properties in functional groups.
public class Whatever {
// private data here
int _someVal = kSomeConstant;
// constructor(s)
public Whatever() { }
#region FabulousTrick // sometimes regionize it
// fabulous trick code
private int SupportMethodOne() { }
private double SupportMethodTwo() { }
public void PerformFabulousTrick(Dog spot) {
int herrings = SupportMethodOne();
double pieces = SupportMethodTwo();
// etc
}
#endregion FabulousTrick
// etc
}
You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.
As said, I don't think there is a best way as such. But some organisation does help you the programmer.
How often in a long project have you spent time going up and down one or more source files trying to find one of your functions.
So I make use of the #region a lot to in this sort of way -
region Events : All of the event references that this class uses (at least in this particular partial class).
region Controls : All functions that directly interact with controls on a form.
region MDI : set the mdi up
Then there will be some to do with functionality rather than interface,
region Regex searches
I sort of make it up as I go along, but using the same pattern I always use. I must say I have been told by some programmers picking up my work that it is easy to follow and others that its messy.
You can please half the people half the time and the other half a quarter of the time and the other quarter of the time you confuse everyone including yourself. I think Winston Chrchil said that.
Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.
Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.
Each to their own, but I tend to follow the same order that the MSDN help follows.
I also don't like to nest classes or enums, instead create separate files for them, that also makes writing unit tests easier (since it's easy to find the associated test file when you need to add/fix/refactor a test).
IMHO the order isn't that important because VS makes it very easy to find all members (especially if you follow the one class/interface/enum per file approach), and Sandcastle will group them if you want to build docs, so I'd be more concerned about giving them meaningful names.
On top of keeping a consistent set of regions in your class files, I keep all components of a region in alphabetical order. I tend to have a bit of "visual memory" when it comes to reading code and it drives me crazy having to use the navigation dropdown to find code in a file because it's all over the place.
I use the following layout:
events
globals/class-wide fields
private/internal
properties
methods
public/protected
properties
methods
nested classes (although I try to avoid these whenever possible)
I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.