rohan singh

software engineer. bicyclist & rock climber. craft beer addict.

A Little Trick

Here’s a little trick I use. I figured I’d share it just in case anyone else finds it useful.

Whenever I need to decide whether something is good, whether I support it or I don’t, it all comes together in one simple question. In the ideal world that I want to live in — the ideal, peaceful, happy, loving, accepting world — would this thing be or would it not be?

Once you start putting things into that perspective, everything becomes quite straightforward. Whatever the issue or thing is, all you have to do is ask that one simple question, and then the correct path of action often becomes quite clear.

Whether the issue you are considering is one of those big values-based divides of our day — war, abortion, gay marriage, religion — or whether it is just a simple matter of your daily dealings with other people, all you have to do is ask yourself: is this the world I want to live in?

4 Simple Rules for Catching .NET Exceptions

What follows has probably been expounded a thousand times in different places. In fact, MSDN even has a long article entitled Best Practices for Handling Exceptions.

That said, I believe the best practices when it comes to catching .NET exceptions can be boiled down into four basic rules:

  1. Do not catch an exception unless you have something specific you need to do with that exception in the place you are catching it. Generally, there’s two scenarios where it’s alright to catch an exception:

    1. When you can do something specific to respond to and recover from a specific exception.
    2. When you have specific logging or, in the UI, want to display a specific error message due to a specific exception.

    Every exception and every catch block incurs a major performance overhead. If you can’t do something that fits into one of these two categories, you generally should not catch the exception. Note that this means that catching Exception instead of a specific type of exception is almost never correct.

  2. When you want to convert an exception to a string for logging, just use ex.ToString(). Do not try to ToString() or do any complex operations on any of the exception’s other properties in a way that could fail if those properties are null. For example, ex.SomeProperty.ToString() is almost never correct since SomeProperty might be null. Even if it seems to not be null when you are testing, since this is by definition an exceptional case you can’t be sure what properties of the exception may or may not be filled.

    More generally, avoid doing things in a catch block that may cause another exception to be thrown. Don’t nest try-catch blocks.

  3. Never do anything that would hide an exception from bubbling up unless you have specific code that can recover from the exception. For example, even if you are logging an exception in your catch block, rethrow it so any logging code higher up will be able to process it as well.

    The only time you should not rethrow an exception is when you can recover from it and the code can keep running fine.

    That said, if you can recover from an exception and the code can keep running, see if it would be possible to predict the exception beforehand and avoid it. As an example, say you are going to try to call ToUpper() on a string. If the string is null beforehand, you already know that a null reference exception will be thrown, so don’t call ToUpper().

  4. When you rethrow an exception, always just use throw;. Do not use throw ex;. The latter restarts the call stack and makes debugging much more difficult. The only time you would do the latter is if you want to hide internals for some reason like security, which is almost never needed.

Comments? Concerns? Death threats?

HTML5 Database API Support in an Android WebView

Here are some facts:

  1. HTML5 has a Database API that lets you store things locally and retrieve them with SQL queries.
  2. Android lets you embed a WebView in your application to display web content.
  3. How to combine #1 and #2 is extremely poorly documented.

One thing that kills me about the Android documentation is how it’s so hit-or-miss. Some things are so well documented that I have literally been able to copy code out of the docs into my code and just change it a little. Actually, my roommate saw me do this at one point and accused me of plagiarism. But that is the subject of another post entitled “Why You Shouldn’t Take Coding Advice From Psychology Majors”.

But really, I think the #1 best thing you can do when releasing a platform or public API of any sort is include tons of samples, inline with the documentation. The real winners when it comes to doing this are the PHP documentation and the MSDN .NET Framework documentation. Almost every single class and function in the docs for these platforms includes a sample of how to use the thing.

Maybe it’s not a coincidence that PHP and .NET are so popular?

It took me way too long to find out how to enable HTML5 Database API support for content displayed inside a WebView on an Android. The pieces were scattered all over the Intertubes, though I finally found the last piece of the puzzle on Joe Bowser’s blog. Here’s the entire thing put together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
WebSettings settings = myWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);

String databasePath = this.getApplicationContext().getDir("database",
    Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);

myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
        long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
        quotaUpdater.updateQuota(estimatedSize * 2);
    }
});

Note that the onExceededDatabaseQuota is mandatory. I am pretty sure the default quota is zero, so you need to override this method and provide a quota to allow storage. I’m using estimatedSize * 2 as the new quota since my app is browsing to a known page that only stores a small amount of data. Your scenario may be different.

One Song on Repeat

So I’ve been listening to this one song on repeat for pretty much the entire day:

Let me explain a bit further. I barely know anyone today who doesn’t listen to music while working. But I’ve been reading the classic Peopleware book, and apparently back in the ’60s this was something that researchers at Cornell thought was worth looking into. They took a group of computer science students and split them into two groups.

The first group went into a silent room, and the second group went into a room where they could listen to music using headphones. There was an equal distribution of students who said they liked to listen to music while working and those who didn’t.

Everyone was then given the same coding problem. The challenge was to implement a program from a pretty complicated spec, using Fortran (hey, it was the ’60s after all). Not surprisingly, there wasn’t much difference between what went on in the two rooms. Both groups of students were able to do the challenge at about the same speed and with the same skill. No big surprise, right?

Except for this, from Peopleware (emphasis mine):

The Cornell experiment, however, contained a hidden wild card. The specification required that an output data stream be formed through a series of manipulations on numbers in the input data stream … Although the specification never said it, the net effect of all the operations was that each output number was necessarily equal to its input number. Some people realized this and others did not. Of those who figured it out, the overwhelming majority came from the quiet room.

Think about that for a second. Here are these two groups of students who are given what they think is a fairly mechanical task: look at this spec that tells you how these numbers should be manipulated, write some code that does the manipulations. And all of them were able to complete the mechanical, mathematical portion of this task at about the same speed.

But inside the mechanical task was something that required a creative leap: figuring out that the output numbers of the program would be exactly the same as its input. Something like that might be obvious today with our fancy interactive debuggers, but you have to imagine it must have taken quite the leap to figure it out while stamping Fortran code into punch cards. This is the kind of leap that could save hours upon hours of work and tens of thousands of dollars.

To make this creative leap, you almost invariably had to be in the quiet room.

To the crack neurologist in me, it makes sense. Music is a creative activity, and listening to it probably engages the creative part of your brain. Everything seems fine when you are working, since most of what you are doing is mathematical, analytical, or mechanical. What you don’t realize is that your creative areas are too engaged with the music to be engaged with the problem at hand.

Maybe that’s alright sometimes when you’re just powering through something you’ve done a million times, but how sustainable is that approach? Unless our basic neurology has changed since the 1960’s, it seems clear that to make the creative leaps in software design – and probably anything else – you have to turn the music off at some point.

The thing that kills me about this is that I like music. It’s awesome. I love listening to music, and I do it almost exclusively when I work and no time else. I think I’ve developed the habit of sometimes listening to just one song on repeat as a type of defense strategy. The music gives you a rhythm and a beat to work to, but when it’s just the same song a million times over, you can start to tune it out. Maybe that lets the creative part of your brain re-engage with your work?

Then again, maybe I have no idea what I’m talking about.

Laying on the Boat…

Laying on the boat, reading a book drinking a beer. This is what it’s about.

ConfigurationProperty Code Snippet (C#)

If you’ve ever wanted to create a custom configuration section for a .NET app, you know how tedious it is to type this out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace Samples.AspNet
{
    public class PageAppearanceSection : ConfigurationSection
    {
        // Create a "remoteOnly" attribute.
        [ConfigurationProperty("remoteOnly", DefaultValue = "false", IsRequired = false)]
        public Boolean RemoteOnly
        {
            get
            {
                return (Boolean)this["remoteOnly"];
            }
            set
            {
                this["remoteOnly"] = value;
            }
        }

        // Create a "font" element.
        [ConfigurationProperty("font")]
        public FontElement Font
        {
            get
            {
                return (FontElement)this["font"]; }
            set
            { this["font"] = value; }
        }

...

There’s a much faster way to create normal properties. If you’ve ever used the prop code snippet to create a property, you already know this. You can just type “prop” and hit tab to have an entir property filled out for you:

Faced with the daunting task of creating some custom configuration elements, I threw together a code snippet that lets you do the same for a configuration-backed property. I can now just type “propc” and hit tab to get this:

Then I just fill out the name and type and call it good. If you’d like to join in on the propc goodness here’s the source of the snippet file. Just download and save it as a .snippet file and import it through Tools | Code Snippets Manager in Visual Studio: