DEV Community

The Practical Developer
The Practical Developer

Posted on Originally published at practicaldevblog.blogspot.com

Git Branching Explained: Work Without Breaking the Main Code

Introduction

A branch is a separate line of work in Git. The main branch, usually called main, holds the stable code. When you start a feature or a fix, you create a branch, work there, and merge it back only when it is ready. If the work goes wrong, the main code is untouched.

This is the workflow used by almost every team, and it is worth learning early, before you need it under pressure.

Create and switch branches

Check your current branch first, then create and switch in one step with the modern switch command, or the older checkout command if your Git version prefers it.

git status
git switch -c feature/login-form
# Older Git: git checkout -b feature/login-form
Enter fullscreen mode Exit fullscreen mode

Name branches clearly: feature/login-form, fix/header-bug, docs/readme-update. A good branch name tells the next person what the branch is for, without opening it.

Work normally on the branch, then commit as usual:

git add .
git commit -m "Add login form layout"
Enter fullscreen mode Exit fullscreen mode

Merge back to main

When the work is done, switch back to main, update it, and merge your branch in:

git switch main
git pull
git merge feature/login-form
Enter fullscreen mode Exit fullscreen mode

If the merge is clean, Git combines the changes and you are done. Delete the branch after merging, so old branches do not pile up:

git branch -d feature/login-form
Enter fullscreen mode Exit fullscreen mode

What happens with a conflict

A conflict happens when the same lines were changed in both branches, and Git cannot decide which version to keep. Git marks the conflicted file like this:

<<<<<<< HEAD
Welcome back, Sara!
=======
Welcome back, Ali!
>>>>>>> feature/login-form
Enter fullscreen mode Exit fullscreen mode

Fix it by editing the file to the version you actually want, removing all the marker lines, then marking it resolved:

git add <file>
git commit
Enter fullscreen mode Exit fullscreen mode

Conflicts look scary the first time, but they are normal. They are Git asking you to choose, not Git breaking your code. Always test after resolving a conflict, because a clean merge does not guarantee the combined code still works.

A simple daily workflow

  1. Update main: git switch main then git pull
  2. Create a branch for the task
  3. Commit small, clear changes on that branch
  4. Merge back to main, or open a pull request for review
  5. Delete the merged branch

Takeaway

Branches are cheap, safe, and reversible. Work on a branch, keep main stable, merge when ready, and resolve conflicts by choosing the correct lines and testing afterwards. That one habit prevents most "I broke the project" moments.

Originally published at https://practicaldevblog.blogspot.com/2026/10/git-branching-explained.html

Top comments (0)