Branches are Git's way of creating parallel universes of your project. You can have multiple branches at once and switch between them instantly. Think of it like having a main storyline with different side quests โ you can explore each without disturbing the main plot.
Working with Branches
Start by listing all branches with git branch. Use git branch new-branch to create, then git checkout new-branch to switch. You can also combine them with git checkout -b new-branch to create and switch in one step. Each branch has its own set of commits that are independent.
$ git branch
$ git branch feature-login
$ git checkout feature-login
$ git checkout -b hotfix
$ git branch
Why Use Branches?
Branches are essential for collaborative development. Here are the main reasons to use them:
- Feature development: Build new features on a separate branch without affecting the stable main branch.
- Bug fixes: Create hotfix branches to fix critical bugs quickly, then merge back to main.
- Experimentation: Try out new ideas on branches. If they don't work, just delete the branch โ no harm done.
- Code review: Push branches to the remote and create pull requests for team review before merging.
Branch Naming Conventions
Good branch names communicate purpose at a glance. Common conventions include:
# Feature branches
git checkout -b feature/user-authentication
git checkout -b feature/shopping-cart
# Bug fix branches
git checkout -b fix/login-error
git checkout -b bugfix/payment-timeout
# Hotfix branches
git checkout -b hotfix/security-patch
Use lowercase with hyphens or slashes. Avoid spaces and special characters. Keep names short but descriptive enough that you know what the branch is for.
Switching and Deleting Branches
Switching branches is instant in Git. Your working directory changes to match the branch's last commit:
# Switch to an existing branch
$ git checkout main
# Or use the newer switch command
$ git switch main
# Delete a local branch (only if fully merged)
$ git branch -d feature-old
# Force delete an unmerged branch
$ git branch -D feature-abandoned
# Delete a remote branch
$ git push origin --delete feature-old
Always delete branches after merging them. A clean branch list makes it easier to focus on active work.