# The Collaborator's Guide to Sharing Code: Best Practices

By the end of this guide you will be able to prepare a research code repository that a collaborator can run on their first attempt, publish a versioned release that reviewers can execute, and handle sensitive data without exposing it. You will need a computer with Git installed, Python 3 or R available on the command line, a free account on a Git hosting service such as GitHub or GitLab, and roughly one afternoon of cleanup time.

Code sharing is no longer an optional courtesy. Analyses underlying published medical research are increasingly expected to be inspectable and runnable by others, a shift captured by the NIH Gold Standard Science emphasis on transparency and reproducibility, which pairs a manuscript's data snapshot with a versioned, environment-specific code release in a companion repository [1]. This article walks through the whole workflow, from organizing files on day one to depositing a citable release at submission time.

## Why Sharing Code Matters in Scientific Collaboration

When you share code openly, other scientists can inspect, run, and validate your analyses, which strengthens reproducibility and invites collaborative extension of your work to new datasets [1]. Sharing also benefits you directly through increased visibility and credibility [1]. Shared code and shared workflows are now recognized components of good research [data management](/blog/guides/data-management-basics-principles-processes-and-best-practices), working together with documentation standards and data management plans to make research outputs reusable [2].

The demand is real even when practice lags. A survey of 1,385 clinical studies in ten leading ophthalmology journals found that only 326 articles, or 23.54 percent, included a data sharing statement, with rates ranging from 3.88 percent to 66.67 percent across journals [3]. Clear statements about whether and how code and data can be accessed are what allow readers to validate findings, and journals increasingly expect them [3].

Barriers are also real, and knowing them helps you plan around them. Interview researchers across the European Union and United Kingdom described barriers and facilitators to reproducible research in five interrelated themes, including the incentive structures of institutions, journals, and funders, disciplinary social norms, and practical constraints of skills, infrastructure, guidelines, time, and funding [4]. Most of these forces are outside your control as an individual. The practices in this guide target the ones you control.

## Core Principles Before You Share

Four principles govern almost every decision that follows.

**Transparency.** A reader of your paper should be able to connect each reported result to the code and data that produced it. Gold Standard Science frames this pairing of data snapshot and versioned code release as the mechanism that lets reviewers directly verify results at submission [1].

**FAIR and TRUST.** FAIR stands for findable, accessible, interoperable, and reusable. TRUST stands for transparency, responsibility, user focus, sustainability, and technology. These principles were developed for data but apply directly to code, and sharing code and workflows alongside documented data is one of the practices that makes FAIR work in practice [2]. A code repository aligned with FAIR principles is also a design goal of large collaborative platforms, which combine standardized data organization, controlled access, and formal governance [5].

**Licensing.** Code without a license is code nobody may legally reuse. Choose a permissive license such as MIT or BSD when you want maximum reuse, or a copyleft license such as GPL when you want derivatives to stay open. State your choice in a LICENSE file at the repository root.

**Integrity.** Codes of conduct for research integrity set expectations for honest, careful, transparent, and accountable work. Researchers evaluating the Netherlands Code of Conduct rated the large majority of its 61 standards as clear and relevant, which suggests these norms are legible even where adherence varies in practice [6]. Sharing code is one of the most concrete ways to demonstrate the transparency those codes demand.

## Step-by-Step: Preparing and Sharing a Research Code Repository

This walkthrough uses a Python analysis project called `biomarker-analysis`. The same logic applies to R projects, with `renv.lock` replacing `requirements.txt`.

### Step 1. Separate code, data, and outputs

Decide early what lives where. A typical layout looks like this:

- `README.md`, the entry point that explains everything below
- `LICENSE`, your chosen license text
- `requirements.txt` or `environment.yml`, the pinned software environment
- `data/raw/` and `data/processed/`, inputs and intermediate files
- `src/`, the analysis scripts or package code
- `notebooks/`, exploratory notebooks, kept separate from final scripts
- `results/`, generated outputs, often gitignored if large
- `tests/`, small checks that the code runs and returns expected values

Keeping raw data read-only and regenerating everything downstream from scripts is the single habit that prevents most reproducibility failures. Movement analysis researchers who wrote life-cycle guidelines for data sharing reached the same conclusion, recommending open formats, comprehensive metadata, and appropriate repositories at each stage of the data life cycle [7].

### Step 2. Pin your software environment

A collaborator on a different machine will have different package versions. Record exactly what you used.

```bash
pip freeze > requirements.txt
```

For a conda environment:

```bash
conda env export > environment.yml
```

Expected output of `pip freeze` looks like this:

```
numpy==1.26.4
pandas==2.2.2
scikit-learn==1.4.2
scipy==1.12.0
matplotlib==3.8.4
```

Exact version numbers are the point. A study of multicenter clinical research emphasized standardization and auditability of data infrastructure so that future reanalysis is possible [8]. An unpinned environment defeats that goal, because a package released next year can change your results silently.

### Step 3. Write a README that lets a stranger run your code

A usable README answers four questions in order: what this project does, what data it needs, how to install it, and how to run it. A minimal example:

```markdown
# Biomarker analysis for the Smith et al. 2026 cohort study

Reproduces all figures and tables in the manuscript.

## Requirements
Python 3.11. See requirements.txt for pinned package versions.

## Setup
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

## Run
python src/analysis.py --config config.yaml

## Data
Place de-identified cohort CSV in data/raw/cohort.csv.
Columns are described in data/raw/README_data.md.
```

A README of roughly one page is usually enough. What matters is that every manual step a stranger needs appears in writing, including where files go and what the expected runtime is.

### Step 4. Run a quick self-test

Add at least one test that runs the pipeline on a tiny synthetic input and checks a known output value.

```bash
pytest tests/
```

Expected output:

```
============================= test session starts ==============================
collected 2 items

tests/test_analysis.py ..                                          [100%]

============================== 2 passed in 0.31s ===============================
```

If the test passes on your machine after a fresh environment install, a collaborator's chances of success rise sharply.

### Step 5. Put the project under version control

Version control is the practice of recording every change to your files with a timestamp and a message, so any earlier state can be recovered. Git is the standard tool.

```bash
cd biomarker-analysis
git init
git add README.md LICENSE requirements.txt src/ tests/
git commit -m "Initial analysis code for Smith 2026 [cohort study](/blog/guides/cohort-studies-a-practical-guide-to-design-conduct-and-interpretation)"
```

Expected output:

```
[main (root-commit) a3f8c21] Initial analysis code for Smith 2026 cohort study
 9 files changed, 412 insertions(+)
 create mode 100644 README.md
 create mode 100644 LICENSE
```

Add a `.gitignore` file listing `data/raw/`, `.venv/`, and `__pycache__/` before your first commit so that large or sensitive files never enter history by accident.

### Step 6. Push to a hosting service

Create an empty repository on GitHub or GitLab, then connect and upload:

```bash
git remote add origin https://github.com/yourname/biomarker-analysis.git
git push -u origin main
```

Expected output:

```
Enumerating objects: 12, done.
Counting objects: 100% (12/12), done.
Writing objects: 100% (12/12), 4.31 KiB | 4.31 MiB/s, done.
To https://github.com/yourname/biomarker-analysis.git
 * [new branch]      main -> main
```

At this point a collaborator can clone the repository and run the test from Step 4. Have at least one colleague outside your office do exactly that before you go further. Their failures are your documentation gaps.

### Step 7. Tag a versioned release when the manuscript is submitted

A release is a frozen, labeled snapshot of the repository. Tag it:

```bash
git tag -a v1.0.0 -m "Code release for Smith 2026 manuscript submission"
git push origin v1.0.0
```

Expected output:

```
To https://github.com/yourname/biomarker-analysis.git
 * [new tag]         v1.0.0 -> v1.0.0
```

Then deposit the archived release in a repository that issues a persistent identifier for code. A persistent identifier, usually a DOI, is a permanent link that survives hosting changes and can be cited in the manuscript. This is the companion code repository model recommended under Gold Standard Science, which pairs each manuscript with a versioned, environment-specific code release so that readers and reviewers can verify results directly [1].

### Step 8. State clearly how your code can be accessed

Add a code and data availability statement to the manuscript naming the repository, the release version, and the DOI. A formal declaration of whether and how outputs can be accessed and reused is what allows validation, and the ophthalmology survey shows these statements are far from universal, appearing in fewer than a quarter of the studies analyzed [3]. Do not rely on "available from the corresponding author on reasonable request." Reviewers increasingly read such phrases as a red flag rather than an assurance.

## Key Decisions at a Glance

| Decision | Common options | Best fit |
|--|--|--|
| Hosting service | GitHub, GitLab, institutional Git servers | Public work on GitHub or GitLab, restricted work on institutional servers |
| License | MIT, BSD, Apache, GPL | Permissive for broad reuse, copyleft to keep derivatives open |
| Environment file | requirements.txt, environment.yml, renv.lock | Python uses the first two, R uses the third |
| Archive and identifier | Zenodo, institutional repositories, journal-endorsed archives | Any service issuing a persistent identifier for the tagged release |
| Access model for sensitive data | Open repository, controlled-access repository, trusted research environment, federated analysis | Match the sensitivity level of the data, never the convenience level of the team |
| Collaboration model | Shared main branch, feature branches with pull requests | Feature branches for teams of two or more |

## Working with Collaborators During a Project

Sharing code is not only an end-of-project event. Most productive scientific collaboration happens through the repository itself, and a few working agreements prevent most friction.

### Agree on roles and governance early

Multicenter clinical research frameworks recommend clearly defined roles, formalized data-sharing agreements, and quality-control procedures as part of team infrastructure [8]. Translated to code, that means deciding who is the maintainer who merges changes, who reviews analyses, who owns the data pipeline, and what happens when two collaborators disagree about an analysis choice. Write these decisions down in a CONTRIBUTING file. Ambiguity about authority is a leading source of stalled collaborative projects.

### Use branches and pull requests

Each collaborator works on a branch, a parallel line of development, and proposes changes through a pull request that others review before merging. This creates a readable record of who changed what and why, and it lets a senior collaborator catch statistical errors before they propagate. For teams spread across institutions, this review trail doubles as evidence of methodological transparency.

### Standardize data organization across sites

Collaborative platforms in clinical neuroscience solved international collaboration problems by adopting a standard data organization scheme, controlled access, shared software environments, and governance through formal agreements [5]. If your collaboration spans institutions, agree on file naming, variable coding, and directory structure before the first data transfer. Researchers working across four European countries found that differences in coding practices and data quality caused substantial harmonization problems at the analysis stage, so the cheapest time to fix heterogeneity is before it exists [9].

### Pair code with reusable analysis tools

When your analysis becomes something collaborators want to explore interactively, wrapping it in a web application can lower the barrier dramatically. Chemical genomics researchers built an interactive Shiny application that lets users visualize profiles and run enrichment analyses on shared or uploaded datasets, explicitly to improve accessibility and collaboration [10]. You do not need to build a platform. Even a well-documented command-line script with a configuration file serves the same purpose.

## Sensitive Data: When Code Must Travel Instead of Data

Not every project can be shared openly, and pretending otherwise produces either noncompliance or fake openness. Health research data involving patients falls under legal frameworks such as the Health Insurance Portability and Accountability Act in the United States and the General Data Protection Regulation in Europe, and newer instruments including the European Health Data Space extend these obligations [11]. If your repository cannot be open, you still have good options.

**De-identification and controlled access.** Remove or transform direct identifiers before any transfer, document your de-identification procedure, and share code through a controlled-access repository where requesters agree to terms of use. Privacy-preserving techniques and careful review of the applicable regulatory framework are the baseline for responsibly sharing patient-derived datasets [11].

**Trusted research environments.** A trusted research environment, or TRE, is a secure remote workspace where approved researchers analyze data without ever downloading it. The Human Intracerebral EEG Platform hosts 34 institutions and provides private institutional spaces, collaborative shared spaces, standardized data organization, and formal data-sharing agreements within a cloud-based TRE [5]. Setting up a TRE is beyond most individual labs, but joining an existing one is often the fastest compliant route for sensitive data collaborations.

**Federated analysis.** Federated computing sends the analytic code to each institution's local data and returns only encrypted, aggregated results, preserving privacy and institutional control while reducing the need for complex data-use agreements [12]. This model suits multicenter studies of rare outcomes where centralizing patient data is impossible or undesirable.

**Respect community data governance.** When research involves Indigenous knowledge or community-held data, the CARE principles, which stand for collective benefit, authority to control, responsibility, and ethics, provide a framework ensuring that sharing respects the originating community's authority over its own data [13]. Obtain consent for data sharing explicitly, as recommended in the movement analysis guidelines [7], and record that consent in your metadata.

The unifying principle is that the code moves more freely than the data. Share code as openly as you can, share data at whatever level the ethics approval and law allow, and document exactly which level applies so downstream users waste no time guessing.

## Common Mistakes and Limitations

![Four warning cards: no README, unpinned dependencies, hard-coded paths, and sensitive data left in Git history.](/article-images/illustrations/sharing-code-research-collaboration-best-practices-common-mistakes.webp)

**Shipping a repository with no README.** A repository without setup instructions transfers your debugging burden to every user. The reproducibility case studies in bioimaging found that missing methodological detail limited how deeply published analyses could be reproduced, even with good will on both sides [14].

**Leaving dependencies unpinned.** Without exact versions, your results depend on the day the collaborator installs packages. Pin everything, as described in Step 2.

**Hard-coding absolute paths.** Paths like `C:/Users/jane/Desktop/data` break on every other machine. Use relative paths from the repository root, or read paths from a configuration file.

**Storing sensitive data in Git history.** Removing a file in a later commit does not remove it from earlier commits. Keep sensitive data out of the repository from the first commit using `.gitignore`, because retrofitting is painful and incomplete.

**Writing "code available on request" as a substitute for a statement.** Data sharing statements are meant to be formal declarations of how outputs can be accessed, and their absence or vagueness undermines validation [3]. A vague promise is functionally no sharing at all.

**Leaving exploratory notebooks as the only record.** Notebooks with hidden state, out-of-order cells, and manual tweaks are a documented source of irreproducibility. Convert final analyses to plain scripts and keep notebooks clearly labeled as exploratory.

**Forgetting the manual steps.** A reproducibility initiative in bioimage analysis concluded that sharing example datasets, depositing manual annotations, and documenting manual decision criteria and consensus procedures are essential for reproducible workflows [14]. If a human chose which cells to annotate or which points to exclude, write down the criteria.

**Confusing sharing data with sharing code.** They are separate outputs with separate repositories, licenses, and access rules. A companion code repository complements, rather than replaces, established research data repositories [1].

**Underestimating time and skill costs.** Interview researchers consistently named resourcing, including skills, infrastructure, and time, as a real constraint on reproducible work [4]. Budget a day for cleanup before submission rather than discovering the cost during revision.

A final limitation: this guide describes broadly accepted practice, not a guarantee of replicability. Reproducibility also depends on study design, measurement quality, and factors outside any repository. Review your institution's and journal's specific policies before submission.

## Practical Tips for Everyday Scientific Collaboration

- Start the repository on the first day of analysis, not the last. Retroactive cleanup takes far longer.
- Commit small and often, with messages that say why the change happened.
- Have a collaborator outside your institution attempt a full run of your pipeline before submission and log every failure they hit.
- Keep one canonical version of each dataset with a documented checksum or identifier so collaborators can confirm they have the same input.
- Write the data and code availability statement while you write the methods section, not during proofs.
- When sharing an analysis interactively, prefer tools that consolidate exploration and analysis in one accessible place, following the pattern of interactive platforms built for community reuse [10].
- Reuse existing community standards for metadata and file formats where they exist, since bespoke formats are a documented obstacle to reuse [7].
- Treat your own future self as a collaborator. Six months from now, you will have forgotten as much as any stranger.

## Frequently Asked Questions

### Do I need to share code before my paper is accepted?

Usually not. The common practice is to prepare the repository during analysis, tag a versioned release at submission, and include the availability statement in the manuscript, so reviewers can verify results at review time [1]. Check your target journal's specific policy, since expectations vary by field and journal.

### What license should I use for research code?

A permissive license such as MIT is the safest default for research code because it allows broad reuse with attribution. If you need derivatives of your code to remain open, choose a copyleft license such as GPL. Any license is better than no license, because unlicensed code cannot legally be reused by others.

### Can I share code that contains patient data?

Never place identifiable patient data in a code repository. Share the code openly and the data through a compliant route such as de-identified controlled access, a trusted research environment, or federated analysis where code travels to each site's data and only aggregate results return [11][12][5].

### How do I get a citable identifier for my code?

Tag a release in your Git repository, deposit that archived release in a repository service that issues [persistent identifiers](/knowledge/bioinformatics/persistent-identifiers-in-bioinformatics-selection-criteria-and-implementation-workflow), and cite the resulting DOI in your manuscript's availability statement. This creates the versioned, citable companion code release recommended for medical research manuscripts [1].

### What if my code is messy?

Share it anyway, with an honest README. Reviewers and readers value a runnable, pinned, documented repository over polished code that cannot be executed. Messy code that reproduces a published result is more useful than elegant code that cannot be run at all.

### How much documentation is enough?

Enough for a stranger to install the environment, obtain the data, run the pipeline, and recognize the published results without emailing you. In practice this means a README covering setup and execution, a pinned environment file, a description of every required input file, and documentation of any manual analysis decisions [14].

### What is the difference between sharing code and sharing data?

Code is the analysis instructions, data are the inputs. They belong in separate repositories with separate access rules and licenses, because code is usually shareable while data may be restricted by privacy law or consent terms. A code repository complements, rather than replaces, a research data repository [1].

### How do collaborators at different institutions work on the same code?

Use a shared hosted repository with feature branches and pull requests, agree on roles such as who merges and who reviews, and write the working rules in a CONTRIBUTING file. For multicenter work, formal data-sharing agreements and clearly defined team roles are recommended practice, and standardized data organization should be settled before the first data transfer [8][5].

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Do I need to share code before my paper is accepted?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Usually not. The common practice is to prepare the repository during analysis, tag a versioned release at submission, and include the availability statement in the manuscript so reviewers can verify results at review time. Check your target journal's specific policy, since expectations vary."
      }
    },
    {
      "@type": "Question",
      "name": "What license should I use for research code?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "A permissive license such as MIT is the safest default for research code because it allows broad reuse with attribution. If you need derivatives to remain open, choose a copyleft license such as GPL. Any license is better than none, because unlicensed code cannot legally be reused."
      }
    },
    {
      "@type": "Question",
      "name": "Can I share code that contains patient data?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Never place identifiable patient data in a code repository. Share the code openly and the data through a compliant route such as de-identified controlled access, a trusted research environment, or federated analysis where code travels to each site and only aggregate results return."
      }
    },
    {
      "@type": "Question",
      "name": "How do I get a citable identifier for my code?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Tag a release in your Git repository, deposit the archived release in a repository service that issues persistent identifiers, and cite the resulting DOI in your manuscript's availability statement."
      }
    },
    {
      "@type": "Question",
      "name": "What if my code is messy?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Share it anyway, with an honest README. A runnable, pinned, documented repository is more valuable to reviewers and readers than polished code that cannot be executed."
      }
    },
    {
      "@type": "Question",
      "name": "How much documentation is enough?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Enough for a stranger to install the environment, obtain the data, run the pipeline, and recognize the published results without emailing you. This means a README covering setup and execution, a pinned environment file, input file descriptions, and documentation of any manual analysis decisions."
      }
    },
    {
      "@type": "Question",
      "name": "What is the difference between sharing code and sharing data?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Code is the analysis instructions and data are the inputs. They belong in separate repositories with separate access rules and licenses, because code is usually shareable while data may be restricted. A code repository complements, rather than replaces, a research data repository."
      }
    },
    {
      "@type": "Question",
      "name": "How do collaborators at different institutions work on the same code?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Use a shared hosted repository with feature branches and pull requests, agree on roles such as who merges and who reviews, and write the rules in a CONTRIBUTING file. For multicenter work, formal data-sharing agreements and standardized data organization should be settled before the first data transfer."
      }
    }
  ]
}
</script>

## Sources

1. [Research Code Sharing in Support of Gold Standard Science.](https://pubmed.ncbi.nlm.nih.gov/41532590/)
2. [Waste Not, Want Not: How to Make Your Data Futureproof Through Good Data Sharing Practices.](https://pubmed.ncbi.nlm.nih.gov/41427491/)
3. [Evaluating the prevalence and application of data sharing statements in high-impact ophthalmology journals.](https://pubmed.ncbi.nlm.nih.gov/41495441/)
4. [What helps and hinders reproducible research? Researchers' perspectives from a cross-disciplinary interview study.](https://pubmed.ncbi.nlm.nih.gov/42160297/)
5. [The Human Intracerebral EEG Platform: A Cloud-Based Trusted Research Environment for Collaborative SEEG Research in Epilepsy and Neuroscience.](https://pubmed.ncbi.nlm.nih.gov/42626911/)
6. [How do PhD candidates perceive good research practices in the Netherlands Code of Conduct for Research Integrity?](https://pubmed.ncbi.nlm.nih.gov/42271526/)
7. [Open research data in human movement analysis: Swiss-initiated-guidelines for broader scientific communities.](https://pubmed.ncbi.nlm.nih.gov/40756426/)
8. [[Building High-Quality Evidence in Endoscopic Neurosurgery : Practical Clinical Research Strategies and Multicenter Collaboration].](https://pubmed.ncbi.nlm.nih.gov/42036850/)
9. [User journeys in cross-European secondary use of health data: insights ahead of the European Health Data Space.](https://pubmed.ncbi.nlm.nih.gov/40926479/)
10. [ChemGenXplore: an interactive tool for exploring and analysing chemical genomic data.](https://pubmed.ncbi.nlm.nih.gov/41530107/)
11. [Data sharing for responsible artificial intelligence in dentistry: a narrative review of legal frameworks and privacy-preserving techniques.](https://pubmed.ncbi.nlm.nih.gov/40998104/)
12. [Federated Computing in Orthopaedic Surgery: A Paradigm Shift in Collaborative Multicenter Research.](https://pubmed.ncbi.nlm.nih.gov/42424418/)
13. [The case for data sharing in traditional, complementary, and integrative medicine research.](https://pubmed.ncbi.nlm.nih.gov/39834890/)
14. [Presynaptic actin nanostructures: A reproducibility case study.](https://pubmed.ncbi.nlm.nih.gov/42496587/)