Invite-Only Early Access — Think Throo GitHub App is currently invite-only. Request access here.
2024April

Lessons from open-source: How obsessed are you with following Single Responsibility Principle?

This lesson is picked from Next.js source code. In this article, you will learn how deep the imports are nested for a simple hasBasepath utility function.

hasBasepath

This above code snippet is from next/src/client/index.ts. hasBasePath is imported from base-path.ts

Learn the best practices used in opensource.

This is level 1. I usually take it 2 levels but never beyond. I resort to put the functions in the same file that are in the “proximity”. all hasBasePath does is call pathHasPrefix

pathHasPrefix is imported from path-has-prefix.

This is level 2 in the nested imports. Again, I would have just the put the parsePath in this path-has-prefix file as it is in “proximity”.

parsePath is imported from parse-path.ts

This is level 3. Phewww! I never took it this far, but at this level, I realised, the imports are from shared folder that are used in client and server. If you strictly follow SRP (single responsibility principle) for your functions and files, you can reuse these functions across your codebase as these do not contain side-effects.

About me:

Hey, my name is Ramu Narasinga. Email: ramu.narasinga@gmail.com

Tired of AI-generated code that works but nobody understands?

I spent 3+ years studying OSS codebases and wrote 350+ articles on what makes them production-grade. I built an open source tool that reviews your PR against your existing codebase patterns.

Your codebase. Your patterns. Enforced.

Get started for free —thinkthroo.com

Conclusion:

hasBasePath, a simple utility function comes from 3 nested imports in Next.js source code. I stop at second level of nested imports and put the functions in the “proximity”. You can strictly adhere to single responsibility principle but this also depends on how much time you can allocate.