DEV Community

Discussion on: Rebase or merge

Collapse
 
pushkar8723 profile image
Pushkar Anand

I might be restating what is already known. But the difference between rebase and merge is that in rebase your commits are put on top of the branch being merged while in merge a seprate new commit is created to merge the two branches. Now, I know it doesn't help but had to get basics out of the way. Lets see with an example.
Suppose there are two branches where first brach has commit A, B and C and second branch has commit D and E. So initially the repository will look something like:

X ┬ A - B - C
  └ D - E

Now, if you rebase second branch, all its commits will be put on top of fisrt branch.
This is done by simply changing parent commit of D from X to C and then moving subsequent commit on top of it. So the end result will look something like.

X - A - B - C - D - E

While, during merge, a new merge commit Y will be created to combine two branches. So, final result in this case would be:

X ┬ A - B - C -┬ Y
  └ D - E -----┘

Now, people prefer rebase as it results in very clear history (straight line). While in merge, if done very often, the history becomes unreadable because of frequent branching for just 1 or 2 commits.

So we should always rebase right? No!

Because in rebase, all your commits are put on top of other branch one by one. So, if there are some conflicts, then you might end up fixing conflicts for each commit. Imagine doing 10 conflict resolution for 10 commits. While in merge you have to do it only once.

So coming back to original question, when to rebase and when to merge?

There is no hard rule for it, however :
If I have to push just a few commits for some minor non-related changes (bug fixes) then I prefer to rebase.
If I a working on a new feature which tends to have a lot more commits and probably changes which might got reverted / rewritten later in the branch. It makes sense to do a merge. Also, in this case, the history kind of group these feature realated change together in seprate branch.

But again there is no hard rule.