← all lessons
Branching & Merging · lesson 5 of 18

Branches

Parallel Development

Why it matters

Branches are Git’s superpower. They let you experiment, work on features, and fix bugs without affecting the main codebase. Cheap branches = fearless development.

Key concepts

The idea

The Parallel Universe Analogy

Imagine you could create parallel universes to try different approaches:

In Git, these universes are called branches. Creating a branch is instant. You can switch between them freely. When an experiment works, merge it back. If it fails, just delete the branch—no harm done.

Why Git Branches Are Different

In SVN, creating a branch copies all files. Slow and expensive.

In Git, a branch is just a 41-byte file containing a commit hash. Creating a branch is literally:

echo "a1b2c3d4..." > .git/refs/heads/feature

This is why Git encourages branching for everything. It costs nothing.

Walkthrough

How Branches Work

                        HEAD

                       main

    [A] ← [B] ← [C] ← [D]

                    feature (branch pointer)

A branch is just a pointer to a commit. HEAD points to the current branch.

Essential Branch Commands

# List branches
git branch              # Local branches
git branch -a           # All branches (including remote)

# Create branch
git branch feature      # Create but don't switch
git checkout -b feature # Create and switch (old way)
git switch -c feature   # Create and switch (new way)

# Switch branches
git checkout feature    # Old way
git switch feature      # New way (Git 2.23+)

# Delete branch
git branch -d feature   # Delete (safe - must be merged)
git branch -D feature   # Force delete (even if unmerged)

# Rename branch
git branch -m old-name new-name

Common Workflow

# Start a new feature
git switch -c feature/login

# Make changes, commit
git add .
git commit -m "Add login form"

# Switch back to main
git switch main

# Merge the feature
git merge feature/login

# Clean up
git branch -d feature/login

Branch Naming Conventions

feature/user-auth      # New feature
bugfix/null-pointer    # Bug fix
hotfix/security-patch  # Urgent production fix
release/v2.0           # Release preparation
experiment/new-ui      # Experimental work

Key takeaways

Dos & don’ts

✅ DO

❌ DON’T

Going deeper

Branch storage: Local branches are files in .git/refs/heads/. Remote-tracking branches are in .git/refs/remotes/. The content is just the SHA-1 hash of the commit they point to.

The reflog for branches: Each branch has its own reflog. git reflog show feature shows the history of that branch pointer. Useful for recovering from mistakes.

Common mistakes

Working on wrong branch: Always check git branch or git status before making changes. If you commit to wrong branch, use git cherry-pick or git reset.

Unmerged commits warning: git branch -d refuses to delete branches with unmerged commits. This protects you. Use -D only if you’re sure you don’t need those commits.