Showing posts with label code/coding. Show all posts
Showing posts with label code/coding. Show all posts

8 May 2015

Finding blog posts with broken links

How frequently do you end up with erratic HTML in your blog posts?  Not very frequently.  But if you do find your blog in such a state, how do you fix it?  I was playing around with my Picasa settings and in the process I managed to break all my album URLs.  All my albums now returned a 404.

I wanted to find all my blog posts that link to one of my Picasa Web albums and fix the broken links.  Unfortunately Blogger's search will only search the text of the posts, not the HTML.  What this means is that a post containing HTML like "<a href="http://picasaweb.google.com/mankis.pics/Pilgrimage2010>photos</a>" can be found by searching for "photos", but not by searching for "picasaweb" or "mankis.pics".  Like any self-respecting programmer, I decided I'd whip up a script that would do the searching for me.

To access my posts from a script I have two choices: use Blogger's API or get a dump of my blog by exporting it to a file.  API would be a good choice if I have to edit a great number of posts, but I only have to edit a few posts so I went ahead with the latter option.

If I pass the export XML file and the search string, my script would print URLs to edit posts that contain the string.  This is how I found all posts with links to a Picasa album:
% ./find_blog_posts.py \
     -b /tmp/blog-04-30-2011.xml \
     -s 'mankis.pics'
http://draft.blogger.com/post-edit.g?blogID=28645193&postID=5479412993915553873
http://draft.blogger.com/post-edit.g?blogID=28645193&postID=6291962710796224390
...
The script is available online if you want to use.

16 May 2014

JavaDoc for methods

If you find it hard to write JavaDoc for your method, it’s a sign that you should rethink what your method does. Most likely your method is doing way too many things and you should break it into multiple methods.

18 Sept 2012

Error-handling: Java vs Go

FotoBlogr is the first toy I wrote using Go.  As a part of FotoBlogr, I also wrote a Flickr client library, an App Engine helper library, (unpublished) Blogger client, and Picasa client, so I got to see some idiomatic Go.  One thing I really missed when writing Go was exceptions.  Many things that are one-liners in languages with exception support (Java, Python, etc.) become 3 or 4 lines in Go.  Let’s take parsing a string as an integer for example.  In Java, you’d write:
int n = Integer.parseInt(str);
and you’re done.  If you expect this conversion to fail, you’d catch NumberFormatException, but it’s not mandatory.  Compare this to equivalent Go code:
n, err := strconv.Atoi(str)
Of course, you can choose to ignore the error by using an underscore in the place of err, but it still won’t be as expressive like in Java.  For instance, you cannot write return math.Sqrt(strconv.Atoi(str)).  You must write that in two different statements:
n, _ := strconv.Atoi(str)
return math.Sqrt(n)
Of course, this is wrong, and it should actually be something like:
n, err := strconv.Atoi(str)
if err != nil {
  // Handle this error.
}
return math.Sqrt(n)
It was very annoying to get used to writing code this way... almost as if writing dumb code.

Fast forward a few months.  I had moved to a C++ project where the style guide prohibits using exceptions.  Existing code in this project ignored errors in several places, but when I was writing new code I always made sure I did something about errors... at the minimum log it and proceed.  I didn’t have to make a conscious effort to do that; writing Go code had trained me to naturally think about error handling.  It felt awkward to not check for errors, in fact.

Now, I am fixing a bug in a Java project.  This is an old project with design decisions independently made by hundreds of engineer over several years.  The change itself is fairly simple: instead of simply sending a request to an RPC server, now we have to first check whether it’s okay to send that request.  If this query fails, we’d show an error message to the user.  But the complication is this: I’m changing a void method that does not throw any exceptions.  (This method in effect promises all its callers that it can never fail!)  This method is being called by half a dozen classes, which are being called a few others, and so on.  Unless I touch a large number of files to handle the new error, I can’t get the code to compile.

I was discussing this issue with a teammate and what he said was remarkable.  He said, “Every method in every class should throw a checked exception irrespective of whether that method can fail or not.  If it cannot fail today, maybe it can tomorrow.”  He didn’t literally mean that, of course.  What he meant was we weren’t using checked exceptions as extensively as we should have.  If this method I am changing now threw some checked exception, I could simply use that in my client code without scratching my head too much.  This is precisely what Go does.  Almost all functions return an error status.  You can choose to ignore it, but when someone new to the codebase reads it, it’s obvious you’re ignoring an error.  I’m starting to think that Go’s way of error-handling is a much superior way than Java’s and C++’s.

SIDENOTE: The easy and obvious fix is to throw a RuntimeException and catch it in only the places I like to change now.  But that’s a really wrong way to fix a problem like this.  First of all, RuntimeExceptions are not meant for cases like this.  They are for things like division by zero, dereferencing a null pointer, etc.  Things that can happen in any code and thus are impractical to handle specifically.  Since they are rare and usually very serious, they are allowed to propagate through deep call stacks.  Defining application errors, input errors, etc. as RuntimeException can lead to severe debugging issues over time.  You really don’t want that.

9 Sept 2012

Understanding code

You don’t understand a piece of code until you can confidently add features to it.

2 Sept 2012

Inspecting 302 HTTP headers

Let’s say you want to inspect the response header for an HTTP request.  But the response is a 302, so your browser immediately navigates to the new location and you never get to see the 302 response (and the headers).

One way to solve this problem would be to install a browser extension that would keep the headers for you even after the redirect has happened.  But I’m not a big fan of installing browser extensions for functionality that I very rarely need.  So I use the wget command instead:
wget -S -O/dev/null --max-redirect=0 'http://www.google.com/'
-S flag tells wget to print the headers to stderr
-O/dev/null discards the response body (by writing it to the null device)
--max-redirect=0 tells wget to not follow any redirects.

This is the 302 redirect google.com sends for redirecting users to country-specific Google domain:
--2012-09-02 09:54:33--  http://www.google.com/
Resolving www.google.com (www.google.com)... 74.125.237.50, 74.125.237.48, 74.125.237.52, ...
Connecting to www.google.com (www.google.com)|74.125.237.50|:80... connected.
HTTP request sent, awaiting response... 
  HTTP/1.1 302 Found
  Location: http://www.google.com.au/
  Cache-Control: private
  Content-Type: text/html; charset=UTF-8
  [...snip...]
  Date: Sat, 01 Sep 2012 23:54:33 GMT
Location: http://www.google.com.au/ [following]
0 redirections exceeded.

14 Apr 2012

How to add infinite scrolling to Blogger blogs

One nice thing I like about Blogger’s Dynamic Views is that they remove older posts/newer posts links from your blog and load more posts as you scroll to the end of a page.  (This is commonly referred to as infinite scrolling.)  Adding infinite scrolling to your Blogger blog with a traditional template is not that hard.

If you don’t care about the details and you only want to enable the feature on your blog, click on the button below and add the code to your blog.  Infinite scrolling should just work on your blog, in most cases.  If you have a custom template, though, you may need to tweak the code a little.  (Scroll down to “Frequently asked question” section for details.)

If clicking on this button does nothing, or it doesn’t work for some reason, you can add this code manually:
  • Add a HTML/JavaScript gadget to your blog.
  • Leave the gadget’s title empty.
  • Paste the following code as the gadget’s content:
    <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
    <script type='text/javascript' src='//m-misc.appspot.com/js/blogger-infinite-scrolling.js'></script>
  • Save the gadget, and you’re done.
The code for the widget is available on GitHub.  Feel free to copy or adapt the code.  A few points worth mentioning:
  • This code uses jQuery library, so don’t forget to include it.
  • Custom template blogs may have to change the value of postContainerSelector variable in the code.
  • I have manually added +1 buttons to my blog.  Dynamically loaded posts won’t have the +1 buttons initialised; to fix that issue, I had to call gapi.plusone.go() every time new posts are added to the page.
  • _WidgetManager is a JavaScript object present in Blogger blogs.  You can query this object to find some page metadata.  This code uses _WidgetManager to determine if the current page is showing a single post.  Infinite scrolling is not meaningful when only a single post needs to be displayed.

Frequently asked question

  • Q: My blog uses a script/widget that adds post thumbnails or related posts.  When I add infinite scrolling, only the first few posts have thumbnails/related posts.  How to fix that?
    A: Simple answer is that this script doesn’t work well with other scripts that add content to posts.  But if you are willing to change the code, you can get both scripts to work together.  Right after new posts have been added — which is the line after $(postContainerSelector).append(newPosts); in the script — add the JavaScript that will make your other widget update itself.
  • Q: The script doesn’t work on my blog.  Can you help me debug it?
    A: While I really wish I could help everyone use this script, it’s practically not possible for me to look at everyone’s blog and see what’s wrong.  If I don’t respond to your comment quickly (or at all), it’s because I am just too busy with things like my day job.  I’m sorry I couldn’t help you with your blog.
  • Q: Why can’t I post a comment?
    A: Contact me through Google+ if you need to ask me anything. I believe you can send me a message even if you don’t have a Google+ profile yourself.

Change log

  • Mar 9, 2013: Moved the script to m-misc.appspot.com because Google Code is not setting the right content type.  This disabled the script completely in Google Chrome.
  • Nov 19, 2012: Version 1.6 was released with support for Automatic Thumbnail and Read More.
  • Oct 17, 2012: Version 1.5 was released with support for Facebook buttons and a fix for Disqus integration bug.  Thanks to Alex for sharing Facebook support code in a comment.
  • Oct 11, 2012: Version 1.4 was released with support for Disqus comments.  Do not use this version; Disqus integration is broken in this version.
  • Sep 20, 2012: Version 1.3 was released with support for Google Analytics.  If a blog uses Google Analytics, the script will register all automatic post loading as pageviews.  To Google Analytics, it will look like the reader clicked on the Older Posts link every time the script autoloads posts.
  • May 30, 2012: Version 1.2 was released with fixes for all known bugs.
  • Versions up to (and including) 1.1 have known bugs.

1 Apr 2012

Rolling back git commits without losing history

I sometimes introduce a buggy feature to a program and I want to roll it back.  If I had already committed the buggy feature into my git repository, I prefer to keep the buggy commit in revision history... just for posterity ;-)

Finding how to do this was a bit hard, so I’ll document it here.  I know I’ll need to look this up another time; it’s easier if it’s on my own blog :)  The command to roll back to a previous commit is:
git checkout <commit> <repository root>
For example, running git checkout ea2ff0a50 ~/d/prog would restore all files under ~/d/prog directory to the state they were at ea2ff0a50 commit.  Now I can commit the “new” rolled back state with a different commit message, for example “Roll back free penguins feature.  Penguins are too cute to be given away.”

The other approach for rolling back, where you lose the buggy commit for good is to use git reset.

29 Mar 2012

Generic solutions and specific solutions

From certain points of view, programming is fairly easy.  Most of the common problems have known solutions.  Often, programming is simply applying common solutions to specific problems.

I have a web app whose sole purpose is to create thumbnails of images whose URLs are given.  It took a few seconds for serving each request, so I applied a common solution to the “my program is too slow” problem: caching.  With two levels of caching, I brought down the average response time to around 150ms.  (Caching code is in boldface.)
if PICASA_URL_REGEX.matches(original_url):
  # Resizing Picasa URLs is child's play.
  # All we need is some URL tweaking.
  response.Redirect(resize_picasa(original_url))
  return

if FLICKR_URL_REGEX.matches(original_url):
  original_url = mid_size_flickr_url(original_url)
# local_cache is a simple hash map.
if original_url in local_cache:
  response.Redirect(local_cache[original_url])
  return

thumb_url = memcache.Get(original_url)
if not thumb_url:
  thumb_url = data_store.Get(original_url)
  if not thumb_url:
    image_bytes = http_client.Fetch(original_url)
    thumbnail_bytes = image_resizer.Resize(image_bytes)
    thumb_url = data_store.Store(original_url, thumbnail_bytes)
  memcache.Set(original_url, thumb_url)
local_cache[original_url] = thumb_url
response.Redirect(thumb_url)
Though 150ms isn’t too bad, I had been wanting to optimise this further for several months.  Only I couldn’t figure out how.  Yesterday, something dawned on me: I was using the caches all wrongly!  I was unnecessarily repeating a bunch of string operations and regular expression searches for every request before even touching the caches.  A better approach would be to hit the cache as early as possible.  I changed the algorithm to be like:
# response_cache is a a simple hash map.
if request.query_string in response_cache:
  response.Redirect(response_cache[request.query_string])
  return

if PICASA_URL_REGEX.matches(original_url):
  # Resizing Picasa URLs is child's play.
  # All we need is some URL tweaking.
  thumb_url = resize_picasa(original_url)
  response_cache[request.query_string] = thumb_url
  response.Redirect(thumb_url)
  return

if FLICKR_URL_REGEX.matches(original_url):
  original_url = mid_size_flickr_url(original_url)
thumb_url = memcache.Get(original_url)
if not thumb_url:
  thumb_url = data_store.Get(original_url)
  if not thumb_url:
    image_bytes = http_client.Fetch(original_url)
    thumbnail_bytes = image_resizer.Resize(image_bytes)
    thumb_url = data_store.Store(original_url, thumbnail_bytes)
  memcache.Set(original_url, thumb_url)
response_cache[request.query_string] = thumb_url
response.Redirect(thumb_url)
Immediately the average response time came down to around 40ms.  Plus, it’s not unusual now to find requests that get served in less than 5ms!

Algorithmic difference between the two code snippets is subtle, yet the performance difference is substantial.  What makes programming interesting is the fact that knowing the solution is not always sufficient.  Ability to adapt a generic solution to specific problems is one of the things that makes one a good programmer.

Appendix
Sample logs before code change:
Sample HTTP request log before code change
After code change:
Sample HTTP request log after code change

16 Mar 2012

Generating data URIs in Go language

I wrote FotoBlogr to make blogging easier for a friend.  The main goal was to make it easy to add Flickr photos to Blogger blogs.  As time went by, I added support for adding recipe microformats to blog posts, since that’s what she primarily posts.

The app is fairly simple, it’s just one HTML file; but most of the UI is constructed at client side using JavaScript.  As soon as the page loads, it’d send out a number of AJAX requests to fetch the list of blogs, list of Flickr photos, any saved draft post, etc.  Adding features always implied adding more images (i.e. icons) to the interface.

At one point, rendering the UI needed more than 40 HTTP requests, all to the same domain.  The app that used to load instantly started taking a second or two to fully load.  I wanted to bring back the old speed while retaining all existing features.

I have seen data URIs generated by frameworks like Google Web Toolkit.  When you replace an <img src='/img/my-icon.png'> with something <img src='data:image/png;base64;image-data-inline'>, it cuts off one HTTP request from the load time[1].  I decided this is what I’d do, and this post is to document how I did it.

FotoBlogr is written using Go language and runs on Google App Engine.  One possible implementation is I can run my HTML files through some tool that will replace all (or selected) images with inline image data.  It could work, but I wanted something easier.  This is when I found out how powerful the Go language is.

Generating data URIs for images is literally one line of code:
func dataUrl(data []byte, contentType string) string {
  return fmt.Sprintf("data:%s;base64,%s",
      contentType, base64.StdEncoding.EncodeToString(data))
}
Now I have to connect this code with my HTML.  Enter Go’s template package.  Go’s templates can call functions[2].  If I can make this function callable from my templates, it’s job done.  I’ll first show you how this is used and then the implementation.

Instead of instantiating the template by parsing the file directly, now I need to call a helper function.  I.e., I had to replace calls like
  tmpl := template.Must(template.ParseFile("tmpl/home.html"))
with
  tmpl := gaesupport.NewTemplate("tmpl/home.html")
(gaesupport is the name of the package where I have some App Engine support code.)

To request inlining of images, I replaced HTML like
  <img src='/img/plus.png' width='16' height='16'>
with
  <img src='{{inline "img/plus.png" "image/png"}}' width='16' height='16'>
That’s all a caller has to.  It’s hardly any extra work, so I am happy with this solution.  Implementation of gaesupport.NewTemplate function is straightforward too.  It instantiates a new template.Template object, adds the inline function to its context so templates can call it, and then parses the template file as usual.  Here’s the full code:
package mgae

import (
  "encoding/base64"
  "fmt"
  "io/ioutil"
  "os"
  "template"
)

// Encodes data into a 'data:' URI specified at
// https://developer.mozilla.org/en/data_URIs.
func dataUrl(data []byte, contentType string) string {
  return fmt.Sprintf("data:%s;base64,%s",
      contentType, base64.StdEncoding.EncodeToString(data))
}

func inline(fileName, contentType string) (uri string, err os.Error) {
  data, err := ioutil.ReadFile(fileName)
  if err != nil {
    return "", err
  }
  return dataUrl(data, contentType), nil
}

func NewTemplate(fileName string) *template.Template {
  funcs := template.FuncMap(map[string]interface{} {
    "inline": inline,
  })

  tmpl := template.New(fileName)
  tmpl.Funcs(funcs)
  template.Must(tmpl.ParseFile(fileName))
  return tmpl
}
[1] On the other hand, it bloats up your bootstrap HTML and makes it impossible for clients to cache your image.  FotoBlogr is tiny; even with all image inline, the bootstrap is only about 70kB, so this would work for me.
[2] I’ll be honest and admit that I first thought “wow, that’s like PHP!” when I first heard it.  But it’s actually cleaner than that.  Templates can only call functions that you explicitly export.

4 Feb 2012

Moving Eclipse installation to a different location

I recently changed my username on my laptop from manki to m.  I just had to rename /home/manki directory to /home/m and everything worked just fine, except one program: Eclipse.  For whatever reason, Eclipse writes absolute pathnames like /home/manki/whatever in its configuration files and when /home/manki disappeared, Eclipse could’t figure out what to do about it.

One nice thing about Eclipse is that, like all Unix programs, it keeps all its data in plain text files.  I just had to look for files that contained the string /home/manki and replace those strings with /home/m instead.  The directories I had to scan were:
  • workspace-root/.metadata
  • ~/.eclipse
I used this command to get a list of files that matched:
find ~/.eclipse ~/prog/eclipse-workspace-android \
    -type f \
    -exec grep -l '/home/manki/' {} \;
Once I had the list of files, an easy search-and-replace across all those files did the job.  Eclipse opened with no issues, and it was able to find all the plugins and such.  I think doing the same would be sufficient to move an Eclipse installation from one location to another.

21 Dec 2011

Your thoughts betray you

I have been hating Java since morning.  Because I have been reading Java code since morning, and the code is all dumb.  Dumb because it’s reams of code for doing trivial things.  (This being Google Nonsense Toolkit code doesn’t help either; I keep thinking that GWT manifests everything wrong with the Java culture.)

I know all this negative feeling is because I am just tired and sleepy.  Nevertheless it makes me hate Java uncontrollably!

12 Dec 2011

Reading code

Good code is so simple, reading it often makes you think “I could’ve written this”.

16 Oct 2011

Very high level programming

James Iry has written an excellent post on why calling C “portable assembly” is wrong.  The part that inspired me to think is the one about undefined behaviour.  He says:
The C standard says a bunch of stuff leads to undefined behavior. Real compilers take advantage of that to optimize away code, sometimes with surprising results.

What assembly has undefined behavior on that scale? mov al, [3483h] ;(Intel syntax) is going to try to copy the byte at 3483h into the al register, period.
Essentially compilers understand the intent of our statements and can rewrite the program for us if they can prove that the rewrite does not change the program’s behaviour.  Compilers understand a lot of “low level” operations so they are smart enough to rewrite them for us.

One thing you would have noticed if you’re a programmer is that formidable amount of coding time is spent on handling corner cases.  Most of this corner case complexity is caused by the lack of understanding our tools (compilers, runtimes, etc.) have of the program’s intent.  Let’s take an example code snippet:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; ++i) {
  list.add(300 * 2);
}
Compilers of today can rewrite this code as:
List<Integer> list = new ArrayList<Integer>();
int __tmp = 300 * 2;
for (int i = 0; i < 10; ++i) {
  list.add(__tmp);
}
This is a very simple optimization that saves CPU time.  This is possible only because our compilers know that a loop repeats the execution of its body over and over again, and that the value of 300 * 2 cannot change over time.

All the languages and other tools we have today are only aware of low level constructs, or code blocks.  They don’t understand, for instance, connection between two functions in a program.  What I think future holds for us are tools that understand very high level semantics.  Tools that can detect if you have two conflicting features in your product.

Another example.  If a Blogger blog uses a classic template, that blog should not have Layouts tab in the UI.  Because Layouts tab is only for manipulating a Layouts template.  Currently this idea is beyond the scope of tools, so we implement this manually: there’s a block of code that determines if the Layouts tab can be shown for a specific blog or not.

If a code change accidentally makes the Layout tab available to classic template blogs, no tool can find it today.  The only way we can detect such an error is by having tests.  Awesome as they are, tests are just band-aids.  Some day there will be tools that would know that classic templates and Layout tab are in conflict.  Those tools will flag an error if we link to the Layout tab of a classic template blog.  (In other words, a few more levels of indirection is due.)

26 Aug 2011

Remote debugging client side code

When I was learning to program, I was taught to use interactive debuggers.  Turbo C++ version 3 – the de facto DOS C++ IDE everyone used back then – had an interactive debugger.  That was the first debugger I ever used.  Then I used Visual Basic and Visual C++ debuggers as well, and loved them both.

When I learned Java, I tried to use jdb for some debugging but couldn't get my head around debugging from the "command line".  I never managed to learn that.  8+ years later, even today, I cannot connect the context from a jdb- or gdb-style debugger with code in an editor.

But I learned another way of debugging: System.err.println.  Just add a few print statements in the places you think are interesting and rerun your code.  (Some people are surprised when I say I find using print statements faster than using an interactive debugger.)  One thing I like about print statements is that it's so universal: I never have to learn how to use a new debugger.  It works the same way in all kinds of enviroments including Python, C++, and JavaScript.

The latest toy I've built, FotoBloger, has a mysterious bug that kicks in only when a friend of mine uses the app.  I have been trying to reproduce the bug from my account for a few weeks, but with no success.  Yesterday, I decided I had no way but to do some "remote debugging" when my friend is using the app.  My universal "print what's interesting" approach works really well in this bizarre remote debugging scenario as well :)

I added a /debug URI to the app which won't do anything apart from sending a 204 (no content) response back.  Next time the app is being used, it will make a bunch of /debug requests with the data I want to inspect in its query string.  The server logs all incoming requests, so I can look at the logs to see what those values were and maybe I can discover the bug.  (Can your interactive debugger do this? ;-)

7 Aug 2011

AJAX fie upload

Uploading a file from the browser can only be done by using forms.  Even then, you should remember to set enctype='multipart/form-data' attribute on your form.  Form submissions require a page refresh.  If your app is AJAX-heavy you probably wouldn't want to refresh the page just for uploading files.

Here's what you need to do to submit a form with file inputs without refreshing the page:
  1. Add an invisible iframe to your page.  Give the iframe a name.  For example, your iframe might look like: <iframe name='submit-iframe' style='display: none;'></iframe>.
  2. Set the target of your form so that the form submission goes to the hidden iframe: <form method='POST' action='/upload' enctype='multipart/form-data' target='submit-iframe'>.
  3. Add an onload event handler for your iframe.  This event handler will be called every time the form is submitted.  You can then read the response from the iframe's body.  A JQuery app might do it like:
    $(myIFrame).load(function() {
      var responseText = this.contentDocument.body.innerText;
      // Do something with response text.
    });
Update: This can lead to some weird behaviour when a user navigates away from the app and then navigates back using the browser's Back button.  (Or if the page is refreshed.)  The iframe's onload event will be fired and your event handler will be called when you don't expect it to be called.  To work around this problem, I am clearing the iframe's content immediately after copying the text into a variable.  The event handler now looks like:
$(myIFrame).load(function() {
  var responseText = this.contentDocument.body.innerText;
  if (!responseText) {
    return;
  }
  // Clear the content of the iframe.
  this.contentDocument.location.href = '/img/logo.png';

  // Do something with response text.
});

15 Jul 2011

Conditionals and code complexity

Let's say we have a function that takes the name of a city and returns the city's current weather.  More details about the implementation:
  • The user might misspell the city name.  The function will use a spell checker to correct any spelling errors we may find.
  • Even with spell correction, we may not find the city.  We will throw an exception if we can't find any city.
  • There can be multiple cities with the same name.  For example there is a Hyderabad in India, and one in Pakistan.  In such cases, we will arbitrarily pick one.  If we get the wrong city, user has to refine the query.
  • We may not be able to get weather data.  If the weather service we are relying on fails, we return null.  (You would probably throw an exception here as well, but this is just a fabricated example.)
  • You don't always want real weather data.  Most of the time, you are working on different parts of the app; you don't care if the weather you get is accurate or not.  You want to use fake weather data if you are running the app for development/testing.
I am going to use Java in this post because that's what I have been writing these days.  First, I present the dreaded conditionals version:
Weather getWeatherFor(String cityName, boolean mayCorrect) throws CityNotFoundException {
  if (AppConfig.useFakeWeather()) {
    return AppConfig.getFakeWeather();
  } else {
    try {
      List<Location> locations = locationService.findCity(cityName);
      if (locations.size() > 0) {
        Location locn = locations.get(0);
        return weatherService.getCurrentWeather(locn);
      } else {
        if (mayCorrect) {
          for (String name : spellCheckService.getCorrectionsFor(cityName)) {
            Weather weather = getWeatherFor(name, false);
            if (weather != null) {
              return weather;
            }
          }
          throw new CityNotFoundException(cityName);
        } else {
          throw new CityNotFoundException(cityName);
        }
      }
    } catch (WeatherException e) {
      return null;
    }
  }
}
Sure, you can read this code and understand what's going on.  But how easy is it to find a bug in this?  And how easy it would be to fix that bug?

The problem with this code is that it uses way too much branching.  An if-else is essentially one statement.  What I mean by that is, when you change something in the middle of an if-else, you should keep the entire if-else in mind.  The condition (weather != null), for example, is 3 levels down a decision tree.  Before you can touch that part of this function, you should have worked out all 3 paths of the decision tree in your mind; otherwise your change might introduce a bug.

Now, the same code written in a way I like:
Weather getWeatherFor(String cityName, boolean mayCorrect) throws CityNotFoundException {
  if (appConfig.useFakeWeather()) {
    return appConfig.getFakeWeather();
  }

  List<String> candidates = new ArrayList<String>();
  if (mayCorrect) {
    candidates = spellCheckService.getCorrectionsFor(cityName);
  }
  // Actual input must be the first search we do; insert it
  // as the first item in the list.
  candidates.add(0, cityName);

  Location locn = findCity(candidates);
  try {
    return weatherService.getCurrentWeather(locn);
  } catch (WeatherException e) {
    return null;
  }
}

Location findCity(List<String> nameCandidates) throws CityNotFoundException {
  for (String candidate : nameCandidates) {
    List<Location> locations = locationService.findCity(cityName);
    if (locations.size() > 0) {
      return locations.get(0);
    }
  }
  return new CityNotFoundException(nameCandidates.get(0));
}
In this version, the decision tree is only one level deep at any given point.  (for and try are not necessarily "conditionals", but even if you include them, nesting is only two levels deep.  Which of these two versions would you change confidently?

If you have been writing code for a while, you will know that what starts like the second version would eventually end up like the first version over time: by changes that happen one line at a time.  As you make code changes, check how deep your decision trees get; if it's anything more than two, it's time to restructure the code to simplify it.

10 Jul 2011

Web layout: how not to do it

We didn't have stupid issues like this when we used tables for layout.

19 Jun 2011

Go: first impressions

After having written about 300 lines of Go code for something meant to be used in the real world, I have mixed feelings about Go.

Things I like
  • Static typing done really well.  Lightweight interfaces (see Rotting Cats section of Go tutorial), type inference, closures, etc. make the language fun like a dynamic language.
  • Clean standard library.  The interfaces are well thought out, and names are picked well.  Effective Go, the document that describes the design/style ideas used by the Go project says "long names don't automatically make things more readable" and I can't agree more.
  • Google App Engine support for Go.  This is the deciding factor for writing my current app in Go.
  • Object oriented programming without fetters.  There are no classes.  There is no type hierarchy.  You can define methods for any type, even those defined by a third party library you don't have source code for.
Things I have to get used to
There are certain things that are not entirely new to me, but I have almost forgotten because I have been coding mostly in Python and Java.
  • Values are different from pointers.  I can define a method on a type like this:
    func (o MyObject) Increment() {
        o.count++
    }
    But this will silently fail because o's type is not *MyObject.  So when I call myo.Increment(), myo is passed by value, i.e., a copy of myo is passed to Increment, not a reference.
  • Crashes and core dumps.  Because the code compiles to native code, you can easily crash your program by dereferencing a null pointer or accessing a nonexistent index in an array.
Things I don't like
  • Errors are returned, not thrown.  In most modern languages your code is mostly free of error-handling because either you want to propagate it to the caller or you can handle them all in one place (with a try-catch).  Go doesn't have exceptions.  So you have to check for errors after calling every function that may return an error.  If you forget to do that, too bad, the error is silently ignored.

18 Jan 2011

Running a filter on text in clipboard

The power (or beauty, if you want to call it that way) of Unix command-line interface is not only because of the available commands, but also because of the way we can combine simple commands to do complex things.  Filters are a great example.  In the Unix world we can find many powerful commands that expose functionality that is available only to programs via APIs.  xsel is a great example.  With xsel command, we can inspect and manipulate the contents of clipboard from the command line.

I often have some text -- maybe in a simple text editor (like Kate or GEdit) or in the browser.  I want to use that text in a different program, but with some modifications applied to it.  For example I might want to convert all tab characters in that text to 2 spaces.  Today I wrote a one-line shell script (called run-on-clipboard) that would let me run any filter on the text in clipboard.  Here's the script:
#!/bin/sh
#
# Runs a "filter" on clipboard contents.  Can be used to make arbitrary changes
# to the text in clipboard.  For example, to convert all tabs in the clipboard
# text to two spaces, you can run:
#    run-on-clipboard sed 's/\t/  /g'

xsel -b | "$@" | xsel -bi
To convert tabs to spaces, I would copy the original text into clipboard and run the following command from a terminal:
  run-on-clipboard sed 's/\t/  /g'
This would change the clipboard contents, so pressing Ctrl+V in any program now will paste the text with tabs replaced with spaces.

8 Nov 2010

How I use Synergy

Have you heard of Synergy?  This is a cool application that allows you to share one physical keyboard and mouse across multiple computers you use.  I have been using Synergy for years, and I'm going to share my Synergy setup in this post.

Basic setup is done by writing a configuration file on the server machine as shown in Synergy manual.  In addition to letting you share keyboard and mouse, Synergy does another sweet thing: it synchronizes clipboards on all the connected machines.  What this means is that you can copy some text on one computer and paste it on another!  I love this feature.  But one thing I was not comfortable with: all Synergy communication over the network is done in plaintext.  Every day I would be sending a lot of information over the wire without even being aware of it!  URLs, email addresses, code snippets, and so on.  I don't like it.

Any TCP/IP connection can be encrypted (without the app having to support encryption) using SSH tunnels.  Synergy site has some information about using tunnels to secure Synergy traffic.  Using that setup requires typing a password to establish the tunnel every time I start synergyc, the Synergy client program.  I don't like that either.

First thing I did was to set up public key/private key authentication to the server computer -- one on which I run synergys, and run ssh-agent on the client computer -- one on which I run synergyc.  (Mark A. Hershberger has written a detailed guide for doing this.)  This would let me log into the server from the client without having to  type a password.  Then, I wrote a Python script that would set up an SSH tunnel and start Synergy client.  Now, instead of running synergyc command I run my synergyc.py script, and everything works as expected.

The script sets up a tunnel and starts the client.  My first version, which I wrote a few years ago, was very naive.  For example, it would freak out when the client loses connection to the server, and I will have to manually restart the client.  Now the script is much improved and works pretty well for my usage.  The script is available on GitHub.  Feel free to use it, review the code, send patches, send feedback/bug report, etc.  (Remember to change SERVER_HOST_NAME in the script to your server's host name before using the script though :)