Proper class instantiation in C# and Winforms - c#

After spending the last two years as a C#/WPF/MVVM developer, I recently took over a VB/Winform project at a new company.
I've successfully converted the project to C#. I've been doing a large amount of research, trying to figure out the best methods for this project, but I'm trying to figure out exactly how much refactoring and re-configuring to do.
My issue is this: the previous developer created two huge static classes. There are 30+ forms that are used for a variety of tasks. Each form is called from an event driven by a button click on a "main menu" type of screen. When the program initializes, a function from one of these mega-classes is called that instantiates EVERY form. There are also an incredible number of statics and constants.
I've broken the constants out and created a specific class for them. I'm piecing apart the mega-classes into smaller, more manageable (and responsibility specific) classes, but I've got this incredibly large initialization function that instantiates all of these forms.
Thus, my questions (finally) are these: Is what I wrote above a resource nightmare? Or, is this some sort of normal VB/Winform design pattern that I should keep? Should I re-write this so that each form/class is instantiated when the button calling that form is clicked, so it can disposed of when closed?
Thank you for any direction you can give me. If I can provide more information to make this more specific, please comment and I will edit.

Is what I wrote above a resource nightmare?
Yes
Or, is this some sort of normal VB/Winform design pattern that I should keep?
Absolutely not. The design of the system is pretty much identical in VB and C#. With some very minor exceptions the difference between the languages is just syntax.
Should I re-write this so that each form/class is instantiated when the button calling that form is clicked, so it can disposed of when closed?
Yes in theory. The forms should operate just as they would if you were writing in C#. Of course if the original dev liked global state so much there could be all sorts of state lurking between one appearance of the form and the next.
There are a few features of VB that can lead weaker devs astray. The presence of the Module (essentially a static class, but sometimes more convenient) can lure some people into adding much more global state than they should. Also in VB, it automatically creates as needed a single, global instance of each form with the same name as the class. This can cause devs to confuse the form as a class and object - leading to the single instance of a form, rather than constructing and disposing as needed.

Related

Is there a common practice for dynamically generate controls created by Visual Studio Designer?

I am developing an inventory management program. Through the program, administrators can add items to the inventory. Since this is a fundamental feature of the program, it is displayed in the main Form and is not hidden within the menu.
Non-Administrator users should not be able to see this feature. The easiest option for hiding it is to set its Visible property to false. The problem with this approach is that I load the feature to memory, while I do not need it at all. I am looking for a creative solution. Some will say that this is premature micro-optimization (which is the root of all evil, as we all know), but for me, it is more a matter of writing correct code, not hacks.
So I have created a method that dynamically generates the feature, with all its components, and it is invoked if an administrator is logged in. While this approach fixes the memory issue, it does not allow me to use the Visual Studio designer, and I have to write every line of the feature design.
The solution I thought of was to extract the feature into a UserControl, so it could be designed through the designer. The method mentioned before instantiates it and adds it to the Form. I am uncomfortable with this solution since it uses a UserControl for a different purpose than its original: creating reusable controls.
Besides, using a UserControl this conflicts with my program architecture. Changing the architecture in a critical way is not practical now, especially that the real problem is the misuse of the UserControl and not the architecture.
Each Form has its own namespace. For example, the main Form namespace is Main. The Form is built using MVP, so each of these namespaces has a Model, View, and Presenter classes. Each Form has a sub-namespace for UserControls. So Main.UserControls will contain the UserControls that were created especially for Main to use. UserControls that are shared by several Forms are in a different namespace, higher in the namespaces hierarchy.
Because of the UserControl definition, the Main.UserControls namespace is expected to contain small, useful Controls (such as a ComboBox with predefined values), rather than an entire program feature with a connection to the database. Just by looking at the code, another programmer may find it difficult to understand why this UserControl is there.
Additionally, since this UserControl contains a connection to the database, it requires the use of MVP. Suddenly there are two, not-UserControl, unexpected, extra classes in Main.UserControls.
Is there a better, common solution for dynamically?
Note:
I am not looking for opinions, just asking if there is a well known common practice.

Should you use the form class?

I am quite new to programming and want to make sure I am doing things the "industry standard" way as it normally is the best way. I am about to start my second project and had a quick question about how I should design the program. I have thought about it and decided that the program only needs one class to run, the problem I have is if I should use the form class or make another class? I don't know why I think this might be a bad thing, I just feel it could be.
For example is it ok to put my functions into the "public partial class mainForm : Form" class?
EDIT : I think people are confusing me a bit, I simply want to put some buttons on a form and such - should I put all the actual code i.e. functions that do the actual computing within the forms class or should I make another class and then call myClass.function?
I don't think there is any gain from creating class inherited from Form class just "to do things right" (unless you are talking about self-generated code, which in that case inherits from Form class). If there's no point of inheritance don't use it. In case of windows forms if you create new project your form automatically inherits from Form. Don't try to overthink your project, you'll know how to do things right when time comes - it's a matter of experience. Right now, just do as you think you should do, read a lot and make mistakes! You'll learn in time how the project should look like.
So good luck and have fun coding!
WinForm?
For simple utils go with the form, for anything more hardcore I'd recommend starting with a service object that configures and glues things together. Then you can do:
Application.Run(applicationObjectThatIMadeEarlier.InitialForm);
To get back to where you're used to being.
WinForm constructors can be iffy because of the form designer requirements (it runs the ctor) so its nice to keep things out of the constructor of a WinForm so the form designers keep working.
Generally spoken, yes. As long as you only have one class - in this case your form - and the functions won't be required anywhere else outside of the form.
Is it good practice? Well, not really. Sooner or later you'll be working on projects that don't consist of one class or one form and you'll be sticking all your functions in your form, only to figure out later down the line that you'll need them elsewhere too.
In this specific case you could do it, but I'd personally recommend you to put them in their own class(es).

Best way to pass data between forms using C#

This is more of a theory based question. I am working on the design for my final project in C#, which is to create Jeopardy. My question is, what would be the best way to pass data between them? For instance, the rubric requires the game opens with an options screen after the splash shows. Here, they will select the number of players and their names. I know that in my gameform load event, I can just specify those things as parameters and pass them as arguments from the optionsform. This seems messy though, is there a more efficient way to create project wide variables that I could reference no matter the form I am currently using?
Thanks for any answers, it's always appreciated!
-- Young Padawan Coder
How about creating a separate business object (i.e. class) with either static properties or singleton pattern. You would then store all your application values there and you can refer to them from anywhere in your application without the messy work of passing around variables all over the place.

Managing a big WinForm code

I want to ask pro developers out there that how they manage a big windows form class. Is it a good idea to split it with partial keyword across different files? That's the thing that I was doing so far, but it creats unnecessry designer files that when you double click on them in VS, a blank winform will pop up:
So what I do, basically is group events and code logic for each related group of controls in one file.
My answer is "I don't". If you need a lot of code in one single class (in this case a form) it usually means your class is doing a lot of stuff and you need to make it less coupled. A good way to achieve this is to use a sort of MVC or MVP pattern form putting the logic in another place, and to use UserControls so you could have the different functionalities in different controls (with their controller or presenter, depending if you implement MVC or MVP). Divide and conquer.
I not consider me an expert, but once we had a similar problem with a main form that did not stop growing up.
The solution was just OOP, make unattached and reusable classes, those can be in the same namespace with internal visibility.
For Example there you have a ComparisionForm.Menu that looks that can be unattached from your main code in ComparisionForm.
From another point of view 'Readability'.- Partial classes are useful but take into account that even with that division of code in different files, the logic is not always divided, that makes the code hard to read, understand and finally hard to maintain.
Divide logically my classes for my was the solution. You know what say they "Divide and Conquer"
I think the best way to separate the code of a form, it's to use UserControl.
And in my case, when I have a big class, I use region instead of partial class.
Not a pro, but my two cents are: Don't have a large class. Extract most of the code to other classes.
You'll gain, also, that you'll be able to make most of the methods private, thus reducing Intellisense "noise".

Which is the best and appropriate way to write the code in Winforms?

What is the best way to write the code ?
(1) Like directly writing the code in the button_click() event.
or
(2) Make the function of that code which I write in button_click() event and write this function in one class and then that function I should call in the button_Click() event.Like is it called three-tier approach to write the code ?
Like in button_Click() event I write the code to save the records in csv file from datatable.So I should write that code in button_Click() event or I should make one new function and one new class and write that code in that function which is the new class and calling that function in button_Click() event.
This is only one example but I am talking about all the code written in my application that which is the appropriate and best way to write the code and what are the benefits ? Note that I write the code in Winforms with c#.
You should go for the separate function in a different class. You should do that because you'll make the code reusable and create a decent separation between the user interface and application logic. Like this, you could for example change the UI without affecting the rest of the application.
Also take a look at MVC pattern, you'll understand better the whole idea.
The only situation where i think that the first option should be used is when it does some action that will affect the UI, and still i'll create this in a separate function inside the Form class.
If it's affecting the UI, it should be in the same class because it's related and for example if it's a code to refresh a grid i'll put this in a separate method inside the same Form class because this could be used in different places inside it. So changing the UI has no impact on the application, you just make your code reusable & maintainable.
It all depends on situation.
If you are going to make updates to the Form, then it's better to have the updating code in the Form. However, if there are lots of processing, then surely it's better design to have a separate class handle the job.
It all depends on situation.
Generally, you don't want any logic in the event handler, since GUIs tend to provide redundant mechanisms (context menu, menu bar, toolbar, accelerator key) for triggering the same command, and the event signatures aren't compatible for all of these. Then the question becomes whether your common function should go in the Form class or into the data model.
I often start out with the logic in the Form and then refactor it into model classes as needed. Many small apps will never get large enough that multiple classes are required for maintainability. As long as you avoid code duplication (i.e. copy+paste) then refactoring will be straightforward later if you find you need it.
It is always good to develop classes for jobs. As it makes your code reusable and it also implement three tier Architecture. The benefit is that it is easy to understand.
The important thing is that, it is only beneficial if you develop your classes appropriately. Develop methods in the class which can be reusable for you.
The another benefit is that it hides the complexity of your code.
There are two general approaches to adding structure to code: top down and bottom up. Top down structure comes from design work that can involve a formal or informal process and pure design artifacts like UML diagrams or functional specs. The ultimate goal in a top down process is to create classes and interfaces in your code that will provide appropriate structure to make your code maintainable. This can happen before you write the code, or as part of an iteration, but the idea is that you create the structure first, then create the code.
Bottom up structure comes from refactoring. For example, start with all your logic in a button click. When you add a menu item that does the same thing as the button click, move the code for your button click function into a private member function on the form. When you need the same features in a different part of the application, encapsulate the code and state variables used by your private member function into a class.
I'd recommend using both approaches. The right mix for your situation depends on the development team (size, location, ability to communicate) and the size of your application. Generally speaking, large applications require more top down, and on very small applications a minimal amount of top down design is adequate. But there should always be some high level planning, even for a small app.

Categories

Resources