Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Windows Forms – Form1.cs file is getting rather large

My question is my form file is nearly hitting 800 lines and I still have more of my form to code. I want to know how i should go about in decreasing this in size because i have methods that are getting elements from the form, inputting them, reading, editing files and methods calling other methods for reusability.

As you can see it is becoming very wild in there and i feel that i should have done a partial class at the start but i am unsure if this is still an option? or is it normal for forms to be on the large side?

I know what I will do next time but I need a quick fix if possible as this is for an assessment that is due in a couple of days or should I just carry on down this rabbit hole and use regions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is never too late to refactor. It is in fact a continuous process. You can always split and rearrange your code for better readability and maintainability. You could do it using one or more from these:

  1. Perform a code review to see if there is redundant code which can be extracted as a method and reused within the file.
  2. Split methods into different regions like event handlers, helper methods etc.
  3. If you still think the problem remains, see which features are not directly related to user interface. For instance, you indicate file handling. It may be helpful to extract that code in a different file in a separate class – FileHandler which can be used in the form.
  4. Now you should be left with only event handlers and helpers in the form class file. If this too appears to be unmanageable, you can use partial classes.

Edit: I see MVVM recommendations for this. While the pattern itself is very good for segregation of responsibility, it is more than refactoring. You might need to implement interfaces like INotifyPropertyChanged and ICommand if you want to move to pure implementation. It is doable but compared to WPF, cumbersome.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading