Ever since entering the world of programming, I’ve been bombed with tips like “file should be only x lines”, which is fair since new programmers tend to stuff everything into one file. But, having done programming professionally for more than a year now, I’ve mostly found myself getting hindered by the small size of the files, rather than than the large size of them. One of the biggest hindrances I have, is having to shuffle between 10-20 different files when investigating how something works, when some of those files contain only a couple of lines.
So I guess my question is: how do I know I’ve split my program into too small pieces?
7
File size doesn’t seem to be your problem – in real world development you’ll eventually encounter projects that would have hundreds of files, even if every one of them contained serveral thousand lines of code.
If working with many files is a problem, you need better organization and tooling. Modern IDEs have many features that help with that (e.g. when programming Java in eclipse, “Open Call Graph” will bring tears of joy to your eyes if you haven’t seen it before), so learn to use one of those well. As for organization, well-designed code should have low coupling and high cohesion, which means that code that does related things is close together (high cohesion) and to understand a given piece of code you don’t need to look at many others (low coupling).
All that being said, the average size of a file in well-designed code should be perhaps 300 lines of code, give or take (depends on the language too). There is no minimum: sometimes the design calls for an empty class.
Instead of having to shuffle with 20 files, you’d have to shuffle with 20 locations in the same file. In my experience, editors make it easier to shuffle with 20 files and keeping some context — such as the cursor position — for each than to shuffle with 20 locations in the same file and trying to keep some context for each. You’ll have trouble to even jump easily from one to the other.
4
I would suggest that file size isnt really that important, to me object complexity and function / method size is a lot more important. Assuming you are using an object oriented language, just be sure to make objects that have a clear function and be sure that they only have code for those specific functions.
As a general rule dont have any method / function that is longer than 25 lines (Excluding comment lines), if it is longer than that break it up.
As for the files themselves, they become irrelevant if you follow the tips above because you can always break them up later, but try to separate the files logically, or do what a lot of languages do as a guidline and put one class to a file, if its a procedural language, try to break up functionality using the files, ie. IO in one file, UI in another file and so on.
Just my 2c.