Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In git, why should one work over a branch instead of the main branch?

I keep reading about how one should always work on a different branch than the main one. As soon as I get the job done, I merge them. Why is this any better than simply working on the main branch?

The only advantage I see at first glance is that then there is a somewhat safe way of always knowing what is the "last known working version" -- the main branch. Is that the reason?

like image 887
devoured elysium Avatar asked Feb 24 '23 14:02

devoured elysium


2 Answers

The primary advantage of working in a branch is that you can make commits for an isolated feature while still being able to make fixes on master. You can also do things like "squash" commits with rebase -i if you feel that multiple commits should actually show up as a single commit to other users.

You can also work on multiple experimental features at the same time. You may later decide to scrap that feature or implement it in another way and you can just delete that branch without cluttering your master history.

I often have a handful of experimental feature branches in any given project. Even for just quickly jotting down some thoughts in the form of code they are very useful.

like image 114
Jim Mitchener Avatar answered Feb 27 '23 09:02

Jim Mitchener


Here's one example that happens a lot for me:

Let's say you are working on a feature, its an extensive one, so its going to take many commits. You are about half way done, so the code isn't stable, but it's coming along nicely.

Now, a critical bug is found in the production version of the code, (your master branch, presumably). If you have been committing against the master branch, how do you fix it and push out the fix without pushing out the broken unfinished code?

If you had been working on your new feature in a branch that isn't the master, you can easily just switch to the master branch, fix the bug, and push out the code. Then switch back to your feature branch and continue working.

The ability to do that alone is enough for me to make a branch anytime im working on something.

like image 31
ctcherry Avatar answered Feb 27 '23 07:02

ctcherry