Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using classes to organize code?

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?

like image 515
Zach Whitfield Avatar asked Nov 27 '22 00:11

Zach Whitfield


2 Answers

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.
like image 108
Fredrik Mörk Avatar answered Dec 10 '22 22:12

Fredrik Mörk


You can use #region and #endregion to organize code within a class. These regions are then collapseable.

like image 36
testalino Avatar answered Dec 10 '22 21:12

testalino