如何组织供多命令调用的Stata子例程?命名与存放最佳实践
Let’s break down your options and the standard conventions for Stata package development:
Option Breakdown & Recommendations
1. Copying code to both .ado files (Option 3)
Avoid this at all costs. Duplicating code creates unnecessary technical debt—any bug fix, feature update, or tweak to rex will need to be applied twice, and it’s easy to miss one instance. This makes your package harder to maintain and more prone to inconsistencies.
2. Using include with a .do file (Option 2)
This works for simple use cases, but it’s not the most robust approach:
- Pros: Keeps shared code in a single file, so updates only happen once.
- Cons: The
includecommand just inserts raw text into your calling programs, which means local macros inrex.docan clash with locals infoo.adoorbar.adoif they share names. It also doesn’t leverage Stata’s program scoping rules, which can lead to unexpected behavior with globals or shared resources. Managing the file path correctly (even withc(sysdir_plus)) adds a small layer of overhead too.
3. Creating an internal .ado file (Option 1)
This is the preferred approach for Stata package development:
- Pros:
- Encapsulates
rexas a proper Stata program, following the language’s native structure. - Uses Stata’s scoping rules, so locals inside your subroutine won’t interfere with the calling programs (unless you explicitly pass variables/arguments).
- Calling the subroutine from
foo.adoandbar.adois as simple as running_foobar_rex(plus any arguments it needs). - With the right naming convention, it stays hidden from users (won’t appear in
helpor defaultwhichsearches).
- Encapsulates
- Cons: Adds one extra file to your package, but that’s a tiny tradeoff for better maintainability and structure.
Naming Convention Rules
Stata has standard conventions to keep internal subroutines organized and avoid conflicts:
- Start with an underscore: Programs prefixed with
_are treated as internal, so users won’t accidentally run them or see them in standard documentation. - Add a package-specific prefix: To prevent name collisions with other packages (e.g., another developer might have a
_rexsubroutine), prepend your package name. For example, if your package is calledfoobar, name the subroutine_foobar_rex. This guarantees uniqueness. - Keep the name descriptive:
_foobar_rexmakes it clear this is an internal subroutine for yourfoobarpackage, andrexhints at its purpose.
Final Recommendation
Create an .ado file named _foobar_rex.ado (replace foobar with your actual package name) containing your rex subroutine. Call it from both foo.ado and bar.ado using _foobar_rex (with any required arguments). This keeps your code DRY, follows Stata’s best practices, and avoids common pitfalls.
内容的提问来源于stack exchange,提问作者ChrisP

