Live geek or die tryin'

Review Your Code With Git

Whether you want to commit a part of your changes only or simply check your work before you commit it, one of the Git commands you probably use the most, add, can help you doing it throught its option -p (patch).

This option allows to choose the changes you want to stage.
Or word for word, from Git’s man:

Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.

This is how it works, or rather how I use it:

After executing git add -p ., git enters an interactive mode, from where many actions can be taken. Below are the ones I use the most.

  • If the diff is too long, you can try splitting it with s. That will split it into the smallest possible parts.
  • If you want to stage the diff, simply choose yes.
  • Otherwise, say no.
  • When the whole diff has been viewed, the interactive mode will quit automatically. You can do it yourself tough, through the classic ^C, or by selecting q.
    Note that this will simply quit the interactive mode and won’t undo your actions.

Feel free to ask ? about the other commands meaning, they might be useful in some cases.

git add -p your best friend to review your code and not to commit stuff like console.log().
Make the most of it!

Why Are Trailing Whitespaces Bad

Whenever I see a trailing whitespace, my teeth gnash and I realize that some people just want to see the world burn.

Trailing whitespaces suck, please, don’t use them and ask your code editor to highlight them. Below are some reasons why.

Revision control systems and diff tools

This is the most important point.
For a diff tool, basically the thing used by CVS to detect code changes, this code:

function updateRepositoriesList($scope, Repository) {

Is not the same as:

function updateRepositoriesList($scope, Repository) {..

This, along with wrong indentation or using tabs instead of spaces, leads to unnecessary conflicts and is annoying when merging commits.

Moving inside the code

When I tell my editor to go to the end of the line, I obviously mean the end of the meaningful code, not some spaces after it.

Code display inside editors

On editors that wrap long lines, such as VIM, few spaces at the end of the line may lead to a useless line wrap.

function updateRepositoriesList($scope, Repository) {..|
...                                                    |
    loadingAnimation('show');                          |

Other reasons

Additional spaces increase the file size

That’s a very important point… If you store your code on floppy disks.

The parser will have to skip an extra character when compiling

Yet another important point. When coding on a Intel 8086 processor.

How to fight trailing whitespaces

By correctly configuring your editor

Highlighting them

If you don’t use VIM, skip this part.

If you do, add set list to your .vimrc, this will display unprintable characters such as our lovely trailing whitespaces and non-breaking spaces.
You can customise the characters used for that purpose thanks to the listchars command:

set listchars=trail:◃,nbsp:•

Wiping them

By searching and replacing them: %s/\s\+$//g.

I personally created a function that does the dirty work for me:

function! FutureShock()
  silent! %retab        " Replace tabs by spaces
  silent! %s/\%u00a0/ / " Replace nbsp by spaces
  silent! %s/\s\+$//    " Replace twsp by spaces
endfunction

And mapped it to <LEADER>f:

map <LEADER>f :call FutureShock()<CR>

Future Shock is a Stratovarius song.

Check my VIM configuration for more awesome commands.

By looking for them before you commit

You review your code before committing it, don’t you? ;)
Thanks to the Git diff tool, you can clearly see trailing whitespaces highlighted in red when using git diff; git show, or git add -p (among others).

You now have no excuse for having these abominations in your code.

Don’t Comment Your Code, Write Good One

Dislaimer: I don’t claim to have the absolute truth and I’m open to your feedback and critics.

Whether you’ve learned programming alone or had classes about the subject, you’ve probably been taught to use comments.
The more I write code and read about good practices, the more I realize that advice is exactly the one you shouldn’t give. It only encourages laziness, writing dirty code, and filling the cracks in by commenting every piece of code.

I believe that most of the time you should not use comments, but instead think every time before you write one: why are you doing this? Is your method or function name not explicit enough? Fix it. Is it complex? Refactor it and move its main parts to new methods or functions. Is it hard to understand? You’re writing bad code.

When I say exception, I mean specific cases where you really need to explain what you are doing: you’re hacking to get the shit done, writing some complex algorithm, etc.
Also, if one needs to specify where you did copy some code from, comments might be a good place for this purpose.

/**
* Source: http://stackoverflow.com/a/9261887/604041
*/
function getPopoverPlacement(popover, element) {
}

The reason why I’m writing this post is that I’ve seen this piece of code

// The logo's copyright checksum
const CHECKSUM = "herpderp";

used to justify the use of comments.

Wrong. I didn’t need to think twice before recommending to name that constant LOGO_COPYRIGHT_CHECKSUM.
That’s quite an easy example to counter, but one could improve almost any code out there as effortlessly as shown above.

Another downside of using comments, as mentionned by my friend Nicolas, is that comments need to be maintained, just like the code.
Not only this means more things to take care of and more work to do, but in real life the code gets updated while comments don’t.

Let’s see some examples of how we can avoid comments by writing better code:

From Jeff Atwood’s Coding without comments blog post

A simple but efficient example:

// square root of n with Newton-Raphson approximation
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
    r = 0.5 * ( r + (n/r) );
}

System.out.println( "r = " + r );

Could be refactored to:

private double SquareRootApproximation(n) {
    r = n / 2;
    while ( abs( r - (n/r) ) > t ) {
        r = 0.5 * ( r + (n/r) );
    }

    return r;
}

System.out.println( "r = " + SquareRootApproximation(r) );

I recommend reading his article where he too, calls to avoid comments.
After all, Jeff Atwood’s word’s more valuable than mine, right? ;)

From the awesome Objects Calisthenics manifesto

Here, it isn’t about comments, but a complex code that a lazy-ass would have used comments to explain:

String board() {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++)
        buf.append(data[i][j]);
        buf.append(“\n”);
    }

    return buf.toString();
}

Well written, it looks like:

String board() {
    StringBuffer buf = new StringBuffer();
    collectRows(buf);
    return buf.toString();
}

void collectRows(StringBuffer buf) {
    for (int i = 0; i < 10; i++)
      collectRow(buf, i);
}

void collectRow(StringBuffer buf, int row) {
    for (int i = 0; i < 10; i++)
        Buf.append(data[row][i]);
    buf.append(“\n”);
}

Is that a lot of code? Oh, sorry. :( I didn’t know you pay a fee for each single LoC you write.

Objects Calisthenics is a wonderful book about improving the object oriented thinking and coding. Read it, and if you can’t follow all the rules, start with some and improve accordingly.

Some code of mine

Take a look at this code:

def find_user_repos(username)
  resp = @http_client.call("/users/#{username}/repos")
  raise UserNotFound.new(username) if resp['message'].to_s == 'Not Found' if resp.is_a? Hash

  repositories_array = Array.new
  resp.each do |repository_hash|
    repo = RepositoryConverter.fill_object_from_hash repository_hash
    repositories_array.push(repo)
  end
  repositories_array
end

Starting from line 5, you have to carefully read the code to understand it. One might think let’s just add a comment!. No.
Let’s clean that mess.

def find_user_repos(username)
  resp = @http_client.call("/users/#{username}/repos")
  raise UserNotFound.new(username) if resp['message'].to_s == 'Not Found' if resp.is_a? Hash

  create_repos_array(resp) do |hash|
    RepositoryConverter.fill_object_from_hash hash
  end
end

private
def create_repos_array(repositories)
  repositories_array = Array.new
  repositories.each do |repository_hash|
    repo = yield repository_hash
    repositories_array.push(repo)
  end
  repositories_array
end

Here, I simply moved the code that creates a repositories array in another method, this has many advantages:

  • One can read the code and understand what’s happening, without caring about the implementation.
  • This method can be used elsewhere.
  • It can be tested… If it wasn’t private.

Where to explain how the big parts of my app fit together?

Probably not in the code itself.
I’d suggest doing this in a separate or in the README file.

Yet Another Blog That Migrates to Octopress

I recently migrated my blog from Wordpress to Octopress.

Octopress is a framework for Jekyll, the blog aware static site generator powering Github Pages. To start blogging with Jekyll, you have to write your own HTML templates, CSS, Javascripts and set up your configuration. But with Octopress All of that is already taken care of. Simply clone or fork Octopress, install dependencies and the theme, and you’re set.

Here are some reasons behind this choice:

Markdown

I’m become a fluent Markdown speaker after spending a decent amount of time at GitHub and Stack Overflow. Not only it’s a pleasure to write using it, but it also let focusing on the most important thing — writing, and not to worry about pointless things such as HTML formatting for example.

Speed

The blog posts being written in Markdown, there’s a HTML version of them generated before each deploy. You can add /index.html at the end of this page’s URL to understand what I’m talking about.
That basically means that the blog is simply a bunch of HTML files and doesn’t require or have a database, which makes it fast to load and search engines friendly.

Portabiliy

Many points here:

  • Posts are born in Markdown: I can easily version them.
  • Posts reborn as HTML: I can server them from anywhere, and they’ll just work.
  • Since the blog is static, the comments are hosted elsewhere, Disqus in my case, thus making them protable from a blog platform to another.

Other random detail

Octopress ships with a nice theme, which is perfect in my eyes: it’s simple, responsive and its font size is big enough to not screw up the reader’s eyes.

The migration

Now I’ll show you how you can migrate your own blog to Octopress.

Migrate your blogs comment to Disqus

As I mentioned above, the blog doesn’t have a database; you have to use an external comments provider for your Octopress blog.
I personnaly went for Disqus because it’s popular and well integrated with Octopress.

What you need to do is:

  • Creating a Disqus account
  • Installing the Disqus Wordpress plugin
  • Importing your Wordpress blog comments to Disqus (this feature is available in your user panel)

Create an Octopress blog

You don’t say?!
Start reading the Octopress Setup chapter from Octopress’ documentation. It’ll guide you through the installation steps.

Migrate Wordpress’ posts

For this, use the exitwp tool.
It’s pretty easy to install and use:

  • Clone it
  • Export your Wordpress blog
  • Run the tool on it

You’ll now have a _post/ directory that you’ll need to move to your fresh created blog source/ folder.

More in depth use explanations can be found in exitwp’s README.

Fix the generated posts syntax

Heh, you really believed it would be that easy?! ;)

Although exitwp helps a lot in the migration process, it sometimes doesn’t convert stuff as it should do. That’s especially true if you have some fucked up HTML formatting, some specific tags, such as the Syntax Highlighter plugin ones.

What you need to do now is going throught all the posts, one by one, and fix what should be fixed.
Good luck.

Deploy it!

Now that the migration is complete, you want to show your blog to the internets.

You can either host it on your own server as you would do for a classic Wordpress blog, for free on Heroku, or, if you’re as cool as me, as GitHub pages.

Whatever the way you choose, the Deploying chapter on Octopress’ doc will help deploy your blog.

Keeping the blog on the same domain name

This part was straightforward for me, it is well explained in the docs.

There was little problem though, with Disqus: my blog was hosted at www.dinduks.com, the comments were correctly imported as coming from the www subdomain, except that new comments, on the new blog, were detected as coming from the TLD dinduks.com and not the subdomain www.dinduks.com.
I made sure www was mentioned everywhere, but it didn’t fix the problem.

I solved this problem by migrating the old comments from the correct domain (www.dinduks.com), to the one Disqus was detecting (dinduks.com).
It’s not logical, but it’s better than having no comments at all.

The Migrate Threads feature can be found in the the Tools section of your Disqus admin panel.

Conclusion

Now that I migrated, I’m disappointed to see that the Octopress project is (almost) deserted by its maintainer. As I’m writing this, there’s 73 opened Pull Requests and 138 issues. And the commits rate is low.

Nevertheless, I’m still convinced that Octopress suits my needs more than Wordpress or any dynamic blogging platform outta here, and I encourage you to, at least, give it a try.

Git: More Control Over Git Push

I’ve recently had to do a git push -f which not only pushed the branch I’m on, but also all my other local branches, overriding the remote ones. Fortunately for my teammates and I, the other branches were not crucial.

This behavior is due to Git’s push.default option set to matching, which means Push all matching branches. That’s nonsense to me considering the problems it may cause.

This can be changed of course, by setting the push.default to another value:

  • nothing: do not push anything.
  • matching: push all matching branches. All branches having the same name in both ends are considered to be matching. This is the default.
  • tracking: push the current branch to its upstream branch.
  • current: push the current branch to a branch of the same name.

The most suitable option in most of situations, in my opinion, is the tracking option.

Happy versionning and be careful!