Feature Branches

When I am creating a new feature for an app, I sometimes realize halfway through that the way I am building it, is not the proper way to do so. Or the specification changes. Or there was a misunderstanding. Or there’s an unexpected bug that needs to be fixed and go onto the production server as soon as possible.
Then, when you did all development on the main branch (we use Git, so that’s the master branch in that case), undoing things and/or doing a quick deployment can get very inconvenient. You can’t just deploy a quick bug fix, because all other half-finished features and fixes would have to be deployed, too. You can’t easily revert the existing commits for that feature, especially if the commits are mixed with all the other commits of unrelated features.

A good way to get rid of this problem is to create a local feature branch every time you want to work on a new feature. That branch doesn’t need to be pushed to the remote repository on the server. It’s just for you.
Then, all development for that feature happens in this branch exclusively. For every new feature a new branch is created. After a feature has been implemented completely, merge it back to the master branch (or whatever branch is appropriate). With Git, that’s super easy:

# create a new branch new_feature based on master and switch to it
git checkout -b new_feature master

# when you're done, merge it back
git checkout master
git merge new_feature

# when you are sure everything is working properly
# and no further work needs to be done for this feature,
# you can delete the feature branch again:
git branch -d new_feature

Too often I thought, “I won’t need an extra feature branch for that”. But all it takes is one simple Git command to create one (and it’s probably equally simple in other modern DVCSes). It will make your life easier when coding new features.

Bonus tip

If you decide you want to discard all the development on a particular branch, except for one or two commits, you can cherry pick these commits from the discarded branch:

# say, you have a commit 'bd42c4e7' you would like to keep
# switch to the branch you want to copy the commit to
git checkout master

# copy it
git cherry-pick bd42c4e7

Update: there’s a nice post on the Giant Robots blog which I like to recommend for further reading: Streamline your git workflow with aliases.

Notes

  1. spinexrave reblogged this from danielpietzsch
  2. cylberachee reblogged this from danielpietzsch
  3. danielpietzsch posted this