Should you use the form class? - c#

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).

Related

Object Oriented Programming - Basic informations on Methods with WindowsForm

I studied in programming and graduated in 1998... yeah i'm old LOL Long story made short, I never worked in that field, but decided to get back to it to make myself a membership management program.
There is one thing I can't recall about object oriented programming and I'd need help if someone could please clarify a few things for me.
I have a program I'm working on that has a main Windows Form calling on different other forms to perform different actions on a database containing information about a sports center that I own.
After a while working on the project, I realized that a few methods I'm using in my different child forms are exactly the same. For example, if the user enters a first and last name, i often have to find what's the memberID. I just copied the code to fasten the process.... BUT !
I DO remember my teachers kept saying:
"If you need something to be accessed by many, then why should it
belong to someone?"
and I know it's not a good way to program.
My question is: How do I work that correctly? Should I put my method in the main parent form and call it from the others? Is that the right way to do it? Do I just need to use a class containing these methods and then I can call them from anywhere in the app? I'm confused.
Thank you for your time and help.
To solve these kind of issues we have some options:
1. Helper Class: Create Helper class. Make it public, this class will be available for all forms. Now you can use methods of this class in all forms.
2. Static class: Create a static class with static properties. by using this you can access use this property value any where throughout application. Main advantage of this you don't need to hit database again and again to get same record.
Hope this will help you.

Proper class instantiation in C# and Winforms

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.

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".

polymorphism with Windows Forms

I'm making a project to get myself more familiar with Windows Forms and Graphic User Interfaces.
I have created this program for the Department of Motor Vehicles that uses polymorphism in CONSOLE. So when I input a taxi, it will call the base class of an industrial vehicle rather than a personal vehicle.
The program works fine in console.
But I'm wondering if that's implementable through a Graphical Interface. I know I can just have buttons with the types of vehicles, then have a new form open up to input that data for that specific type of vehicle. But that wouldn't be polymorphism....
Is this a type of project that could be done with polymorphism? and GUI's or no?
I think you would get more bang for the buck if only one form was created which handled the base class as mentioned. But it would turn on/off or make visible items as required by the derived classes. The GUI doesn't have to be polymorphic, it just needs to handle the polymorphism of the data. HTH
You'll have to be more specific about what you want to achieve. Polymorphism can be applied to most problems, if you like. Whether or not it's a good technique varies, and depends very much on how you use it. You seem to be forming ideas about how your object hierarchy will work early on, whereas I would suggest that you don't start there - instead specify what your application should do and how it should do it, and design your object model around that. It may turn out that your idea of how to represent (given your example) a taxi actually isn't useful.
There is no reason why you can't benefit from polymorphism in any object-oriented application, regardless of what user interface you elect to use. In your scenario, it may make sense to use only references to the base class in your list view, and then open up the appropriate details view suited to the specific type of the object.
Also, I recommend WPF for what it's worth. There's no use learning Windows Forms now unless you have a very good reason.
Perhaps what you are looking for is a way to dynamically build your GUI according to the type of (polymorphic) object you are passing? This can be done by using reflection, asking the object passed to the Form which attributes or properties it has and generate automatically input fields, text boxes etc. for each attribute.
For some examples, read this SO post:
Dynamic options dialog (using reflection)

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