Modular approach to coding

+2 Chris Blum · October 20, 2014
Hello,
I've started writing a program for my company and the code is getting a little lengthy.
I'd like to start splitting up each event handler into a separate class to make the code cleaner and easier to read. (it's a windows form application)

The basic breakdown is like this

namespace
-form class
--variable class
--event handlers

Could I just separate the variable class (holds all my global variables for easy referencing within events) and event handler methods into different classes and call them from the main project? What would the procedure be and what should I look out for?
How do I include the other classes in the header of my program?

class Variables{
public static List<string> a = new List<string>();
}

private void Form1_Load(object sender, EventArgs e){
var reader = new StreamReader(File.OpenRead(@"C:\text.txt"));
//more loading code
}

private void buttonInitialize_Click(object sender, EventArgs e){
//more code
}

How could I move these classes and methods into their own file that is called by the main program?
Thanks for any help, tips or links!
-Chris Blum

Post a Reply

Replies

Oldest  Newest  Rating
+2 Eugene Botma · October 24, 2014
A class isn't just a group of variables. I've never been able to explain to anyone what a class is. It is a very abstract concept, the best analogy that I can think of, is a Human. For example:

humans have arms, legs, hair, eyes, nose, mouth, family, friends, a name and what else. So a class for a human might look something like:



int arms;
int legs;
color hairColour;
double hairLength;
int eyes;
human[] family;
human[] friends;
string name;
string gender;



Since a human cannot survive without a mouth and nose, it should be logical that they have them, so no need to add a property. A person can be born without Arms, legs or eyes, or they can lose them during their lifetimes, so we want to specify how many of each they have. But, a class does not only have variables, it can have methods as well. So, we can have something like:


public void Walk(string Location)
{
//human walks to this location using the move legs methods
while (currentposition != location)
{
if (!MoveLeftLeg())
{
 //somethings wrong, i'm falling! trigger falling event
 return;
}
if (!MoveRightLeg())
{
  //somethings wrong, i'm falling! trigger falling event
  return;
}
}
}

private bool MoveLeftLeg()
{
//move left leg, when done, return true; If fails, return false
}

private bool MoveRightLeg()
{
//move Right leg, when done, return true; If fails, return false
}



So I guess you can say that a class is a programatical model of something. The variables are features of this thing that can be changed and methods are things that it can do or be done to it. From what I remember from your earlier posts, you should try to model the students, the lessons and the courses and add the applicable methods and properties to each class. Then use these classes whenever you need to access the information. 




Now on to your question:

(holds all my global variables for easy referencing within events)


It's generally a bad idea to store global variables for a certain class in another one. There is no need to create a class only to store variables for another. A class should always store its own variables.

 event handler methods into different classes and call them from the main project


Yes, you can. You just need to create a method that corresponds with the applicable delegate for the event. For most windows forms events that delegate is:
delegate void EventDelegate (object sender, EventArgs e);
This means that all methods that can be triggered by the event HAS to return void, and needs 2 paramaters, the first being of type object, the second of type EventArgs. EventArgs is the base class, There are events that use inherited versions of the class, but EventArgs will always work.

So, to trigger a method in an external class, try something like this:

   class Class1
    {

        public void ExternalEventHandler(object sender, EventArgs E)
        {
          //do some class specific stuff here. This will be triggered whenever button 1 on the form is clicked.
        }
    }


   public partial class Form1 : Form
    {
        public Form1()
        {
            Class1 tmp = new Class1();
            InitializeComponent();
            button1.Click += tmp.ExternalEventHandler;
        }
     }

Just be sure that the variable that handles the event is always instantiated by the time the event happens, otherwise an exception will be thrown. Thats the only pitfall i can think of when using this. Ofcourse, variables available in the form will not be available in the event handler. Only the classes properties and local variables will be available.

How do I include the other classes in the header of my program?


I'm assuming you are using visual studio. In that case, you can right click on the project name, hover over add. In the newer versions of visual studio, there should already be a class listed at the bottom of the list that pops up, otherwise pick "new item" and search for class. A new file will be created in the explorer window. When the program is compiled, the class will be compiled together with it. You can simply use the classes as i did in the example above.

I am not sure what the command line argument is for csc to compile multiple files, and I am not familiar with other IDE's for working in C#, so I do not know how they handle multiple files. A solution could be to do it all in one file, but that defeats one of the purposes.

All of the classes and files will be compiled into a single executable.



Hope this clears things up a bit. Feel free to ask if you don't understand something.


Edit: Just saw this part:

I'd like to start splitting up each event handler into a separate class to make the code cleaner and easier to read. (it's a windows form application)


I have to say, this is a bad idea. Try to keep variables and events for related things in the same class and file. There's no point in making a whole new file for the fall event for a human on its own. It's much easier to read through one file with 1000 related lines, than to try and make sense of 100 files with 10 lines each. Besides, if you put each event handler into it's own class, it will not be in the same scope as your variables, which means, it cannot do a thing with them. Not even look at them funny.
0 Çağlan Turgut · October 27, 2014
@Eugene Thank you for this explanation! Very useful.
  • 1

C#

107,055 followers
About

C# is an object-oriented language designed for improving the development of web applications.

Links
Moderators