Search code examples
c#code-reusepartialcode-organization

How to organise large code files?


I am increasingly aware that my code in any single file can often span hundreds of lines quite easily and although I know the implementation might be sound, it still feels messy and unorganised.

I understand that there are situations where a lot of code is neccessary, but whats the best way to organise it all?

I've thought about separating variables from methods, privates from publics and internals but I don't want to because I can't help thinking that the components of ONE class belong in ONE file.

This whole thing is compounded when I'm working with the codebehind of a WPF window, which always seem to grow at an exponential rate into one huge mess very quickly.

Also: C# has a keyword called partial, which allows you to split a class over any number of files without affecting the functionality. However, I have noticed that Microsoft only seem to use partial to hide generated code from you (Winforms / WPF.) Which leads me to question whether splitting a class simply because it has many lines is a legitimate use of partial - is it?

Thanks


Solution

  • Separate your code into responsibilities. For each responsibility, define a single type. That is, follow the Single Responsibility Principal. Doing so will result in smaller units of code, each of which performs a very specific function. Not only does this result in smaller files, but also in better design and maintainability.