One Function per File #3
karlrwjohnson
started this conversation in
Ideas
Replies: 1 comment
-
Hi @karlrwjohnson 👋 , thanks for nice write up, I'm basically following similar approach in projects! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
One rule I started using on my team (and got positive feedback on) is "only define one (public) function per file".
This is mainly applicable to "utility" function files.
In my experience with Java, tons projects are littered with "utility classes" that group similar functionality, e.g.
StringUtils
,DateUtils
, and the like. These files run into a couple of problems:(I pick on Java because the fact it forces you to use classes seems to encourage people grouping functions together unnecessarily.)
All of these are solved by putting each function in its own file. Filesystems don't care about sort order, and Git doesn't think a file "changed" if you move it into a child folder.
Obviously this isn't a hard-and-fast rule. For example, "helper" functions that are only called by one other function can stay in the same file -- they're never exported anyways.
There's a side benefit in that in Typescript, your function is sometimes accompanied by type definitions or constants. When there's only one function in the file, it's obvious what those typedefs and constants belong to. If your file is littered with a bunch of other functions that are only incidentally related, it gets harder to track what's going on.
Beta Was this translation helpful? Give feedback.
All reactions