Ashod Nakashian

Apr 292011
 
Cover of "I Am America (And So Can You!)&...

Cover of I Am America (And So Can You!)

Satire and sarcasm are two tools Stephen Colbert can’t stop using to give his otherwise very funny and sometimes hysterical skits some serious meat and subject. And I can’t seem to get enough of it.

I Am America is a brilliant exercise in looking at the world upside down. The topics are contemporary and hotly debated in the public arena. Cobert’s take is narcissistic, self-centered, indifferent, proud and downright obnoxious. At least, that’s the character he pretends to be. A very ignorant yet opinionated pundit of the most annoying type. Indeed, if it weren’t for his humor and sarcasm, non of it would fly.

Colbert sometimes downplays his words so much so that you may miss them if you’re not too careful. Like the homosexuals who want to have their rainbow colors everywhere, even on white flags. Very subtle, if you caught the drift. (Hint: white-light through a prism.)

I’ve had quite a few laughs listening to the audio book version of I Am America. On a few occasions I even caught the attention of others seeing me seemingly bursting into laughter for no apparent reason, except for a pair of ear-buds, that is.

Perhaps of the more memorable pieces are those on old people, family, religion and homosexuals. The part about pets didn’t resonate with me, but then again, I don’t have a pet. However, his wise words about his one issue with children, that he doesn’t like them, and his “rationale” were really sidesplitting. There was a cast who performed small skits at the end of each chapter which I was afraid would turn out to be dull, but on the contrary it wasn’t. They did a good job picking the right voices and actors. Apparently, Martin Luther King was worried that after he wins his cause, he’d find the pastorate leaving him wanting. To make up for it, he was available for hire to lead marches and protests. This was presented by a voice almost identical to King’s own, yet, the actor mentioned that he walked next to King (among others.) So while you shouldn’t think it’s King speaking, your brain can’t help but take the voice to be his. Amusing trickery.

My only issue with this book is that the last one-third seemed more dry and somewhat serious than the rest. I found that a bit confusing, as the whole point of the character he’s playing is the satire and sarcasm. Once that waned, I found myself taking his words seriously and that’s dangerous when you know you’re listening to satire. I had to snap myself out of it a few times, to make sure I don’t take anything as fact when he’s clearly making stuff up as he goes. Like the “fact” that bathroom tiles are the cause of 80% of domestic fatalities. It may very well be true, but, it probably isn’t.

I enjoyed this book quite a bit and found it very up-lifting. I’m just dumbfound for not recognizing Jon Stewart‘s voice in the audiobook.

Apr 172011
 

With the introduction of .Net and a new, modern framework library, developers understandably were very cheerful. A shiny new ecosystem with mint library designed without any backwards compatibility curses or legacy support. Finally, a library to take us into the future without second guessing. Well, those were the hopes and dreams of the often too-optimistic and naive.

However, if you’d grant me those simplistic titles, you’d understand my extreme disappointment when the compiler barfed on my AddRange call on HttpWebRequest with a long parameter. Apparently HttpWebRequest lacks 64-bit AddRange member.

Surely this was a small mistake, a relic from the .Net 1.0 era. Nope, it’s in 2.0 as well. Right then, I should be used 3.5. What’s wrong with me using 2.0, such an outdated version. Wrong again, I am using 3.5. But I need to resume downloads on 7GB+ files!

To me, this is truly a shocking goof. After all, .Net is supposed to be all about the agility and modernity that is the web. Three major releases of the framework and no one put a high-priority tag on this missing member? Surely my panic was exaggerated. It must be. There is certainly some simple workaround that everyone is using that makes this issue really a low-priority one.

Right then, the HttpWebRequest is a WebRequest, and I really don’t need a specialized function to set an HTTP header. Let’s set the header directly:

            HttpWebRequest request = WebRequest.Create(Uri) as HttpWebRequest;

            request.Headers["Range"] = "bytes=0-100";

To which, .Net responded with the following System.ArgumentException:

This header must be modified using the appropriate property.

Frustration! Luckily, somebody ultimately took notice of this glaring omission and added the AddRange(long, long); function to .Net 4.0.

So where does this leave us? Seems that I either have to move to .Net 4.0, write my own HttpWebRequest replacement or avoid large files altogether. Unless, that is, I find a hack.

Different solutions do exist to this problem on the web, but the most elegant one was this:

        /// <summary>
        /// Sets an inclusive range of bytes to download.
        /// </summary>
        /// <param name="request">The request to set the range to.</param>
        /// <param name="from">The first byte offset, -ve to omit.</param>
        /// <param name="to">The last byte offset, less-than from to omit.</param>
        private static void SetWebRequestRange(HttpWebRequest request, long from, long to)
        {
            string first = from >= 0 ? from.ToString() : string.Empty;
            string last = to >= from ? to.ToString() : string.Empty;

            string val = string.Format("bytes={0}-{1}", first, last);

            Type type = typeof(WebHeaderCollection);
            MethodInfo method = type.GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
            method.Invoke(request.Headers, new object[] { "Range", val });
        }

Since there were apparently copied pages with similar solutions, I’m a bit hesitant to give credit to any particular page or author in fear of giving credit to a plagiarizer. In return, I’ve improved the technique and put it into a flexible function. In addition, I’ve wrapped WebResponse into a reusable Stream class that plays better with non-network streams. In particular, my WebStream supports reading the Length and Position members and returns the correct results. Here is the full source code:

// --------------------------------------------------------------------------------------
// <copyright file="WebStream.cs" company="Ashod Nakashian">
// Copyright (c) 2011, Ashod Nakashian
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 
// o Redistributions of source code must retain the above copyright notice, 
// this list of conditions and the following disclaimer.
// o Redistributions in binary form must reproduce the above copyright notice, 
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// o Neither the name of the author nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <summary>
//   Wraps HttpWebRequest and WebResponse instances as Streams.
// </summary>
// --------------------------------------------------------------------------------------

namespace Web
{
    using System;
    using System.IO;
    using System.Net;
    using System.Reflection;

    /// <summary>
    /// HTTP Stream, wraps around HttpWebRequest.
    /// </summary>
    public class WebStream : Stream
	{
		public WebStream(string uri)
            : this(uri, 0)
		{
		}

        public WebStream(string uri, long position)
		{
			Uri = uri;
			position_ = position;
		}

        #region properties

        public string Uri { get; protected set; }
        public string UserAgent { get; set; }
        public string Referer { get; set; }

        #endregion // properties

        #region Overrides of Stream

        /// <summary>
        /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public override void Flush()
        {
        }

        /// <summary>
        /// When overridden in a derived class, sets the position within the current stream.
        /// </summary>
        /// <returns>
        /// The new position within the current stream.
        /// </returns>
        /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
        /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
        /// <filterpriority>1</filterpriority>
        /// <exception cref="NotImplementedException"><c>NotImplementedException</c>.</exception>
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// When overridden in a derived class, sets the length of the current stream.
        /// </summary>
        /// <param name="value">The desired length of the current stream in bytes.</param>
        /// <filterpriority>2</filterpriority>
        /// <exception cref="NotImplementedException"><c>NotImplementedException</c>.</exception>
        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <filterpriority>1</filterpriority>
        /// <exception cref="System.ArgumentException">The sum of offset and count is larger than the buffer length.</exception>
        /// <exception cref="System.ArgumentNullException">buffer is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">offset or count is negative.</exception>
        /// <exception cref="System.NotSupportedException">The stream does not support reading.</exception>
        /// <exception cref="System.ObjectDisposedException">Methods were called after the stream was closed.</exception>
		public override int Read(byte[] buffer, int offset, int count)
		{
            if (stream_ == null)
            {
                Connect();
            }

            try
            {
                if (stream_ != null)
                {
                    int read = stream_.Read(buffer, offset, count);
                    position_ += read;
                    return read;
                }
            }
            catch (WebException)
            {
                Close();
            }
            catch (IOException)
            {
                Close();
            }

            return -1;
		}

        /// <summary>
        /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        /// <filterpriority>1</filterpriority>
        /// <exception cref="NotImplementedException"><c>NotImplementedException</c>.</exception>
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
        /// Always returns true.
        /// </summary>
        /// <returns>
        /// true if the stream supports reading; otherwise, false.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public override bool CanRead
        {
            get { return true; }
        }

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
        /// Always returns false.
        /// </summary>
        /// <returns>
        /// true if the stream supports seeking; otherwise, false.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public override bool CanSeek
        {
			get { return false; }
        }

        /// <summary>
        /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
        /// Always returns false.
        /// </summary>
        /// <returns>
        /// true if the stream supports writing; otherwise, false.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public override bool CanWrite
        {
			get { return false; }
        }

        /// <summary>
        /// When overridden in a derived class, gets the length in bytes of the stream.
        /// </summary>
        /// <returns>
        /// A long value representing the length of the stream in bytes.
        /// </returns>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.</exception>
        /// <filterpriority>1</filterpriority>
        public override long Length
        {
            get { return webResponse_.ContentLength; }
        }

        /// <summary>
        /// When overridden in a derived class, gets or sets the position within the current stream.
        /// </summary>
        /// <returns>
        /// The current position within the stream.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        /// <exception cref="NotSupportedException"><c>NotSupportedException</c>.</exception>
        public override long Position
        {
			get { return position_; }
			set { throw new NotSupportedException(); }
        }

        #endregion // Overrides of Stream

        #region operations

        /// <summary>
        /// Reads the full string data at the given URI.
        /// </summary>
        /// <returns>The full contents of the given URI.</returns>
        public static string ReadToEnd(string uri, string userAgent, string referer)
        {
            using (WebStream ws = new WebStream(uri, 0))
            {
                ws.UserAgent = userAgent;
                ws.Referer = referer;
                ws.Connect();

                using (StreamReader reader = new StreamReader(ws.stream_))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// Writes the full data at the given URI to the given stream.
        /// </summary>
        /// <returns>The number of bytes written.</returns>
        public static long WriteToStream(string uri, string userAgent, string referer, Stream stream)
        {
            using (WebStream ws = new WebStream(uri, 0))
            {
                ws.UserAgent = userAgent;
                ws.Referer = referer;
                ws.Connect();

                long total = 0;
                byte[] buffer = new byte[64 * 1024];
                int read;
                while ((read = ws.stream_.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, read);
                    total += read;
                }

                return total;
            }
        }

        #endregion // operations

        #region implementation

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (stream_ != null)
            {
                stream_.Dispose();
                stream_ = null;
            }
        }

        private void Connect()
        {
            Close();

            HttpWebRequest request = WebRequest.Create(Uri) as HttpWebRequest;
            if (request == null)
            {
                return;
            }

            request.UserAgent = UserAgent;
            request.Referer = Referer;
            if (position_ > 0)
            {
                SetWebRequestRange(request, position_, 0);
            }

            webResponse_ = request.GetResponse();
            stream_ = webResponse_.GetResponseStream();
        }

        /// <summary>
        /// Sets an inclusive range of bytes to download.
        /// </summary>
        /// <param name="request">The request to set the range to.</param>
        /// <param name="from">The first byte offset, -ve to omit.</param>
        /// <param name="to">The last byte offset, less-than from to omit.</param>
        private static void SetWebRequestRange(HttpWebRequest request, long from, long to)
        {
            string first = from >= 0 ? from.ToString() : string.Empty;
            string last = to >= from ? to.ToString() : string.Empty;

            string val = string.Format("bytes={0}-{1}", first, last);

            Type type = typeof(WebHeaderCollection);
            MethodInfo method = type.GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
            method.Invoke(request.Headers, new object[] { "Range", val });
        }

        #endregion // implementation

        #region representation

        private long position_;
        private WebResponse webResponse_;
        private Stream stream_;

        #endregion // representation
	}
}

I hope this saves someone some frustration and perhaps even time writing this handy class. Enjoy.

Apr 172011
 

The topic covered by Malise Ruthven is not free from controversy, to put it mildly. When I approach any work on a religious topic, I automatically become self-conscious and on the lookout. This is of course an understatement when it comes to Islam.

The pressure, whether real or perceived, on any author approaching this topic should already cast doubts as to whether or not the product is biased. I do not mean to imply that there is pressure one way or the other. It works both ways. On the one side there are those who think there is every reason to be aware of the threat caused by the rise of Islam and the progressing Islamization, and on the other those who call the first party Islamophobes and racist. It is therefore no surprise that the book had some very negative reviews. Perhaps another reason is that the topic is one that no two seem to completely agree on. In hindsight, this is reasonable. Scarcely can one find a topic as polarizing as religion.

Islam: A Very Short Introduction is unsurprisingly a short text on a complex and loaded topic. The author seems to be very capable and well-versed. Ruthven covers a large number of topics in a dense space. However, he also wastes some very valuable pages reflecting on the topic rather than presenting it. This would have been very welcome, if you asked me, if it wasn’t at the cost of core material.

This isn’t to say the book isn’t worth reading, far from it. The author does a good job of taking the reader on a tour of the religion from historic, cultural and traditional points to popular-opinion, controversies and even contemporary topics. However, it must be said that as prominent as the author is on the subject matter, he often fails to give the reader background on what he discusses. This might be the unintentional side-effect of trying to make the text interesting and non-linear. As an example, if any book should give a good introduction on Sunni and Shia and their differences, it should’ve been this book. Unfortunately, I found myself reading about them without prior introduction. While later in the book historic background shed some light on how these two groups came to be, it was only mentioned in passing and, without careful reading, the reader may feel a bit at loss as to how these two groups ended on opposite sides of an ongoing battle to this day. It may be the case that the author tried to avoid coming out as painting Islam as a polarized and battled religion.

Having been familiar with both the topic and many details of the subject matter, I can also add that the text was even-handed on most controversial topics. The author didn’t indulge in scenarios involving a complete takeover from extremists, rather, after pointing obvious concerns that most people within and without the Islamic hold. He discussed some recent movements towards reform and potential future trends. Of the cases mentioned were the women’s movement in Saudi Arabia for their right to acquire driver’s license (however that ended.)

Overall, the book is what it claims to be, with emphasis on the word very. The reader should be able to dive deeper into any of the many facets of this significant religion, thanks to the wide, albeit paper-thin, coverage done by Ruthven.

Apr 102011
 

The WordPress plugin I use to manage my reading list is an updated version of the popular Now Reading plugin, called Now Reading Reloaded.

Original NRR book management page.

The original Now Reading plug was developed by Rob Miller who stopped maintaining it at around WP2.5. Luckily, Ben Gunnink at heliologue.com picked up where Rob left off and gave us Now Reading Reloaded (NRR). Unfortunately, it seems that the maintainer has no time to donate to the project and ceased maintaining it.

As one can see, the plugin is a great way to organize and share reading lists. This is exactly what I was looking for when I searched the WP plugin database. Up until then I was tracking my reading lists using simple lists in WP posts and pages. The database back-end of NRR gives it much more potential than one can hope to achieve with simple lists. This is not to say anything of the Amazon search-n-add feature with link and thumbnail of the book cover. All very welcome features.

Limitations

Unfortunately, NRR is far from perfect. One can run into it’s quirks multiple times during a single book update. But, for the price, I can’t complain. None of the issues were too big to annoy me enough to get my hands dirty debugging and patching the code. None, that is, except for a little obvious feature conspicuously missing. By the time I added most of the books I had in my lists and started updating what I read and adding current-reading items, I wished I didn’t have to jump from page to page until I found the book I had just finished to update its status. That is, I wished I could simply sort my library by status, started-reading or finished-reading dates. Even better, I wished by default the library showed me the latest books I started reading, which I was most probably interested in updating.

While open-source programs are great for too many reasons to list here, they all suffer from the same problem. Namely, the freedom to update the code also, by definition, forks and diverges it from the source. This immediately adds the overhead of merging any updates or bug-fixes added to the source to your hand-modified version. However, since it seems that NRR is no longer maintained, I had no reason to fear such a hustle and I still had all the reasons to get sorting functionality in the admin library page, also known as the Manage Books page.

Figuring out the code

First test with new sorting code.

First I had to figure out the wheres and the hows of the code. I wasn’t familiar with NRR, so I had some detective work ahead of me. First, I browsed the page in question: wp-admin/admin.php?page=manage_books. I browsed the pages and noticed how the URL was formed. Apparently, selecting the page to display is chosen by specifying a ‘p’ argument and the index of the page. For example, the second page would be /wp-admin/admin.php?page=manage_books&p=3. Next I had to find the PHP file responsible for generating this page. Since each plugin is stored in its own separate folder, first place to look in was the NRR plugin folder within my WP installation. On my WP3.1 installation, this folder is at /wp-content/plugins/now-reading-reloaded/admin. Within this folder a few PHP files exist with the “admin” prefix. The file “admin-manage.php” seems a reasonable start. I looked for any table construction code that resembles the Manage Books page, and sure enough it’s right there.

Patching

Page sorting works.

(Note: Breaking the PHP files may leave your WP in limbo. Make sure you have backup of your site before you make manual changes, and that you can replace broken files via ssh or ftp.)

The key to adding sorting is to figure out how the database query is generated. This, as it turns out, wasn’t very difficult to find. Within the admin-manage.php file the get_books function contains the complete query

$books = get_books("num=-1&status=all&orderby=status&order=desc{$search}{$pageq}{$reader}");

From this, it’s quite obvious which filter is responsible for what. The ‘orderby’ filter selects the sorting column, ‘order’ decides the direction of sorting and the rest are for searching, pagination etc. Instead of using hard-coded values, we need to get these values from the browser. Let’s add a couple of optional parameters to the page:

            if ( empty($_GET['o']) )
                $order = 'desc';
            else
                $order = urlencode($_GET['o']);

            if ( empty($_GET['s']) )
                $orderby = 'started';
            else
                $orderby = urlencode($_GET['s']);

So ‘o’ will decide the ‘order’ and ‘s’ the ‘orderby’ value. Before I move on, I have to test that this is working in practice and not just in theory. Manually loading the page with the newly added parameters give the expected results. /wp-admin/admin.php?page=manage_books&s=author&o=asc loads as expected the table of books, sorted by the author name in ascending order. Now, all we have to do is add links to the column headers and we can get a working page.

			if ( $order == 'asc' )
				$new_order = 'desc';
			else
				$new_order = 'asc';

			$book_link = "{$nr_url->urls['manage']}&p=$page&s=book&o=$new_order";
			$author_link = "{$nr_url->urls['manage']}&p=$page&s=author&o=$new_order";
			$added_link = "{$nr_url->urls['manage']}&p=$page&s=added&o=$new_order";
			$started_link = "{$nr_url->urls['manage']}&p=$page&s=started&o=$new_order";
			$finished_link = "{$nr_url->urls['manage']}&p=$page&s=finished&o=$new_order";
			$status_link = "{$nr_url->urls['manage']}&p=$page&s=status&o=$new_order";

            echo '
				<table class="widefat post fixed" cellspacing="0">
					<thead>
						<tr>
							<th></th>
							<th class="manage-column column-title"><a class="manage_books" href="'. $book_link .'">Book</a></th>
							<th class="manage-column column-author"><a class="manage_books" href="'. $author_link .'">Author</a></th>
							<th><a class="manage_books" href="'. $added_link .'">Added</a></th>
							<th><a class="manage_books" href="'. $started_link .'">Started</a></th>
							<th><a class="manage_books" href="'. $finished_link .'">Finished</a></th>
							<th><a class="manage_books" href="'. $status_link .'">Status</a></th>
						</tr>
					</thead>
					<tbody>
			';

Notice that I didn’t forget to invert the current sorting order in the link. This is pretty straight forward. Reloaded the page, tested the header links and sure enough all was well. One thing missing is the page selection links – they don’t obey the current sorting. The page selection links had to be patched as well:

                $pages .= " <a class='page-numbers prev' href='{$nr_url->urls['manage']}&p=$previous&s=$orderby&o=$order'>«</a>";
                $pages .= " <a class='page-numbers' href='{$nr_url->urls['manage']}&p=$i&s=$orderby&o=$order'>$i</a>";
                $pages .= " <a class='page-numbers next' href='{$nr_url->urls['manage']}&p=$next&s=$orderby&o=$order'>»</a>";

New default book management page view.

Download

Perfecto! Works great.

One last thing I thought would be useful was to reorder the columns, such that it’s “Book, Author, Status, Started, Finished, Added” instead of the default “Book, Author, Added, Started, Finished, Status”. Because frankly, I don’t care much when I added a book, I care most about its current status and when I started reading it. Once I’m done, I want to set the Finished date and move on to the next. After reordering the columns, I set the default sorting on the Started date and in descending order, as you can see in the screenshot.

Download NRR v5.1.3.2 with the sorting patch.

Mar 112011
 

A product of ours had a serious problem. We could reproduce it by running the main application for several hours, the result of which was that a back-end service was crashing. Initial investigation showed that there was excessive memory usage. Leaks were hunted and we tried to patch and improve all possible situations that may result in leaks.

This isn’t as simple as I make it sounds. There are many cases with exceptions being throws from the network layer and these exceptions bring the whole stack undone. Sure we’re using smart pointers all over, but still, there are some tricky situations with cached objects, COM, network buffers and whatnot.

Memory leaks aside, I noticed something more disturbing: Handle leaks. Memory leaks would affect the ill application, but the system is more or less immune until the culprit crashes in heaps of smoke. But if you have kernel handles leaking, then you are bound to have an unstable system. This is the type of leak that one must resolve ASAP. Apparently, we were leaking kernel handles at an alarming rate.

Windbg screenshot

Third Party?

An immediate suspect is a 3rd party library we were using to handle some MAPI chores. Could that be the source of the leaks? Sure it’s an easy call, but without the right research it’s no use. Plus, replacing that library is not trivial. And who’s to say we’d do a better job rewriting it ourselves? If leaks are such a hard issue to notice and fix, who’s to say we won’t have a bunch more ourselves? After all, rewriting the library functions means we have to rewrite both the good and the bad ones. There is no marker to hint us where the leak is either. So really, we aren’t better off rewriting anything ourselves.

In addition, it’s not very difficult to proof whether or not the said library is to blame. Some investigation was warranted. First thing was to get some stack traces on the leaks. With the stack trace we can tell where the leaked object construction was coming from. This can be done using windbg, the great debugger. Windbg has a handle tracing extension called htrace. After loading our service, run as a console for simplicity, I hit “!htrace -enable” in windbg. “g” to run the application. I run it through a cycle of data processing to let it do it’s necessary allocations and settle. Back in windbg, Break. Now we can set a marker to track the handles “!htrace -snapshot” then “g” again to run it back. Another cycle of data processing and we break it again in windbg. Time to collect the data with “!htrace -diff”.

Sure enough I got a rather long list of leaked objects. Copied the list into my favorite text editor for eyeballing. Looks like a bunch of them were duplicates. I looked very carefully to where the handles were allocated, I was looking for evidence that the 3rd party library was allocating, and hence leaking, them. Well, turns out that there was very little reason to think that the leaks were from the unnamed 3rd party library, and every reason to suspect MAPI was the culprit. These lines sort of gave it away:

0x7c80ea2b: kernel32!CreateMutexA+0x00000065
0x35f7452f: MSMAPI32!SzGPrev+0x00000293

 

The Leak

Ok, so we suspect MAPI32 to be the source, now what? We need to prove it. But before that, let’s examine the leaks. Procexp, the great task manager replacement by Russinovich, would be all we need. I fired it up and run the application again. In procexp I noticed the number of handles before and after each cycle. Sure enough the number was growing. In procexp one can see new items and deleted items in (the default) green and red colors. This is called highlight. The duration for highlight difference is set to 2 seconds by default. I maxed the duration to 9 seconds to give me enough time to pause procexp and prevent it from updating the data. The space bar is the shortcut to pause/resume refreshing.

Ready. Now we need to select the application from the processes list and bring up the handle view. Here we see all the handles allocated by the application. Anything new will show in green anything deleted in red. Right now we’re interested in the green stuff that never go away (even though the color will revert to the default after 9 seconds).

I run another data cycle and sure enough a bunch of reds and greens showed up. Sure enough a few of them remained. 3 to be exact. Looking at the type, they were “Mutant”, “Mutant” and “Section”. Obscure? Not really. Mutant is the internal name for Mutex and a Section is a memory block backed with a file, most probably a mapped file view.

These aren’t exactly light-weight objects to leak.

But our work isn’t over yet. We need to figure out a workaround. Let’s fire up visual studio to type some code. What we need to do is to simulate the execution of the key MAPI functions that we know the intermediate library must execute to carry out the operations we ask it to perform. To make things easy for me, I assigned a number to each operation, such that on the console I could hit a number and get an operation executed. I added both the operation and cleanup as separate commands. Here is some code.

int _tmain(int argc, _TCHAR* argv[])
{
	HRESULT hr;

	int count = 1;
	while (true)
	{
		char c = getch();

		switch (c)
		{
			case '0':
			{
				std::cout << "Calling MAPIUninitialize." << std::endl;
				::MAPIUninitialize();
			}
			break;

			case '1':
			{
				std::cout << "Calling MAPIInitialize." << std::endl;
				MAPIINIT_0 mapiinit= { MAPI_INIT_VERSION, MAPI_NT_SERVICE | MAPI_MULTITHREAD_NOTIFICATIONS };
				hr = ::MAPIInitialize(mapiinit);
			}
			break;

			case '2':
			{
				std::cout << "Calling MAPILogonEx." << std::endl;
				LPMAPISESSION lpMAPISession = NULL;

				ULONG ulFlags = MAPI_NO_MAIL |
								MAPI_NEW_SESSION |
								MAPI_EXPLICIT_PROFILE |
								MAPI_EXTENDED |
								//MAPI_NT_SERVICE |
								MAPI_LOGON_UI;

				hr = ::MAPILogonEx(0,
					  NULL,//profile name
					  NULL,//password - This parameter should ALWAYS be NULL
					  ulFlags,
					  &lpMAPISession);//handle of session
				if (FAILED(hr))
				{
					std::cout << "Failed to logon " << hr << std::endl;
				}

				UlRelease(lpMAPISession);
			}
			break;
		}
	}

	::CoUninitialize();
	return 0;
}

I omitted the other cases, since it’s redundant. You get the idea. Basically, after adding about 10 cases, I started playing around with the different commands to simulate a run of our application. Procexp was monitoring the number of handles and I was hitting on the num-pad to simulate the application. Soon I noticed a trend, and a trend I was looking for. Turns out MAPIInitialize was allocating a lot of handles and MAPIUninitialize wasn’t releasing all of them.

Lo and behold, turns out they are 3 handles and of the same type as I traced in the application!

Now that we strongly suspect MAPIInitialize to be the source of the leak, let’s put the final nail in the proof’s proverbial coffin. Of course, using windbg. Back to windbg, this time let’s load the test application which helped us suspect MAPIInitialize in the first place. Same drill. Enable htrace, run the application, call MAPIInitialize by hitting ‘1’, call MAPIUninitialize by hitting ‘0’, break in windbg, take a snapshot, run the application, hit ‘1’ then ‘0’ again, break in windbg and finally get a diff from the snapshot. Here is the full run:

Microsoft (R) Windows Debugger Version 6.11.0001.404 X86
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: C:\Test\MapiTest\Debug\MapiTest.exe
Symbol search path is: SRV*C:\WINDOWS\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
ModLoad: 00400000 0041f000   MapiTest.exe
ModLoad: 7c900000 7c9b2000   ntdll.dll
ModLoad: 7c800000 7c8f6000   C:\WINDOWS\system32\kernel32.dll
ModLoad: 61e00000 61e1f000   C:\WINDOWS\system32\MAPI32.dll
ModLoad: 77dd0000 77e6b000   C:\WINDOWS\system32\ADVAPI32.dll
ModLoad: 77e70000 77f02000   C:\WINDOWS\system32\RPCRT4.dll
ModLoad: 77fe0000 77ff1000   C:\WINDOWS\system32\Secur32.dll
ModLoad: 7e410000 7e4a1000   C:\WINDOWS\system32\USER32.dll
ModLoad: 77f10000 77f59000   C:\WINDOWS\system32\GDI32.dll
ModLoad: 774e0000 7761d000   C:\WINDOWS\system32\ole32.dll
ModLoad: 77c10000 77c68000   C:\WINDOWS\system32\msvcrt.dll
ModLoad: 77120000 771ab000   C:\WINDOWS\system32\OLEAUT32.dll
ModLoad: 10480000 10537000   C:\WINDOWS\system32\MSVCP100D.dll
ModLoad: 10200000 10372000   C:\WINDOWS\system32\MSVCR100D.dll
(a98.864): Break instruction exception - code 80000003 (first chance)
eax=00251eb4 ebx=7ffdf000 ecx=00000003 edx=00000008 esi=00251f48 edi=00251eb4
eip=7c90120e esp=0012fb20 ebp=0012fc94 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000202
ntdll!DbgBreakPoint:
7c90120e cc              int     3
0:000> !htrace -enable
Handle tracing enabled.
Handle tracing information snapshot successfully taken.
0:000> g
ModLoad: 76390000 763ad000   C:\WINDOWS\system32\IMM32.DLL
ModLoad: 3fde0000 40221000   C:\WINDOWS\system32\MSI.DLL
ModLoad: 35f70000 360bd000   C:\Program Files\Common Files\SYSTEM\MSMAPI\1033\MSMAPI32.DLL
ModLoad: 74720000 7476c000   C:\WINDOWS\system32\MSCTF.dll
ModLoad: 3fde0000 40221000   C:\WINDOWS\system32\msi.dll
ModLoad: 35e80000 35f40000   C:\Program Files\Common Files\SYSTEM\MSMAPI\1033\MAPIR.DLL
ModLoad: 773d0000 774d3000   C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83\Comctl32.dll
ModLoad: 77f60000 77fd6000   C:\WINDOWS\system32\SHLWAPI.dll
ModLoad: 77c00000 77c08000   C:\WINDOWS\system32\version.dll
ModLoad: 755c0000 755ee000   C:\WINDOWS\system32\msctfime.ime
(a98.ac): Break instruction exception - code 80000003 (first chance)
eax=7ffdf000 ebx=00000001 ecx=00000002 edx=00000003 esi=00000004 edi=00000005
eip=7c90120e esp=00a4ffcc ebp=00a4fff4 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=0038  gs=0000             efl=00000246
ntdll!DbgBreakPoint:
7c90120e cc              int     3
Missing image name, possible paged-out or corrupt data.
0:001> !htrace -snapshot
Handle tracing information snapshot successfully taken.
0:001> g
ModLoad: 3fde0000 40221000   C:\WINDOWS\system32\msi.dll
ModLoad: 35e80000 35f40000   C:\Program Files\Common Files\SYSTEM\MSMAPI\1033\MAPIR.DLL
(a98.c08): Break instruction exception - code 80000003 (first chance)
eax=7ffdf000 ebx=00000001 ecx=00000002 edx=00000003 esi=00000004 edi=00000005
eip=7c90120e esp=00a4ffcc ebp=00a4fff4 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=0038  gs=0000             efl=00000246
ntdll!DbgBreakPoint:
7c90120e cc              int     3
Missing image name, possible paged-out or corrupt data.
Missing image name, possible paged-out or corrupt data.
0:001> !htrace -diff
Handle tracing information snapshot successfully taken.
0xdd new stack traces since the previous snapshot.
Ignoring handles that were already closed...
Outstanding handles opened since the previous snapshot:
--------------------------------------
Handle = 0x000001bc - OPEN
Thread ID = 0x00000d9c, Process ID = 0x00000a98

0x7c80ea2b: kernel32!CreateMutexA+0x00000065
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Program Files\Common Files\SYSTEM\MSMAPI\1033\MSMAPI32.DLL -
0x35f74552: MSMAPI32!SzGPrev+0x000002b6
0x35f74476: MSMAPI32!SzGPrev+0x000001da
0x35f76c46: MSMAPI32!FOpenThreadImpersonationToken+0x00000fb9
0x35f76bc9: MSMAPI32!FOpenThreadImpersonationToken+0x00000f3c
0x35f76ba3: MSMAPI32!FOpenThreadImpersonationToken+0x00000f16
0x35f7662e: MSMAPI32!FOpenThreadImpersonationToken+0x000009a1
--------------------------------------
Handle = 0x000001c4 - OPEN
Thread ID = 0x00000d9c, Process ID = 0x00000a98

0x7c80ea2b: kernel32!CreateMutexA+0x00000065
0x35f7452f: MSMAPI32!SzGPrev+0x00000293
0x35f74476: MSMAPI32!SzGPrev+0x000001da
0x35f76c46: MSMAPI32!FOpenThreadImpersonationToken+0x00000fb9
0x35f76bc9: MSMAPI32!FOpenThreadImpersonationToken+0x00000f3c
0x35f76ba3: MSMAPI32!FOpenThreadImpersonationToken+0x00000f16
0x35f7662e: MSMAPI32!FOpenThreadImpersonationToken+0x000009a1
--------------------------------------
Handle = 0x000001cc - OPEN
Thread ID = 0x00000d9c, Process ID = 0x00000a98

0x7c80955f: kernel32!CreateFileMappingA+0x0000006e
0x35f744d4: MSMAPI32!SzGPrev+0x00000238
0x35f74476: MSMAPI32!SzGPrev+0x000001da
0x35f76c46: MSMAPI32!FOpenThreadImpersonationToken+0x00000fb9
0x35f76bc9: MSMAPI32!FOpenThreadImpersonationToken+0x00000f3c
0x35f76ba3: MSMAPI32!FOpenThreadImpersonationToken+0x00000f16
0x35f7662e: MSMAPI32!FOpenThreadImpersonationToken+0x000009a1
--------------------------------------
Displayed 0x3 stack traces for outstanding handles opened since the previous snapshot.

Well, there they are “0x3 stack traces for outstanding handles” all coming solidly from within MSMAPI32.dll. Now that we know who’s responsible for the allocations, let’s see if it’s any of our settings that is causing this. In other words, is there some flag that we can use or remove that might fix this issue?

Fortunately, there are only 3 flags that can be set in MAPIINIT_0. Since MAPI_NT_SERVICE is absolutely necessary, we are left with only two others: MAPI_NO_COINIT and MAPI_MULTITHREAD_NOTIFICATIONS. Trying the combinations of these flags, in addition to the default when MAPIINIT_0 is not set, unfortunately, doesn’t do away with the leak.

Another important fact is that I was using an old MAPI provider. Since we support Outlook 2003 as the minimum version for a MAPI provider, that’s what I was using. I had no service packs installed. The relevant DLLs and their respective version numbers that resulted in the aforementioned behavior are the following:

  • MSMAPI32.dll – 11.0.5601.0
  • MSO.dll – 11.0.5606.0
  • MSPST32.dll – 11.0.5604.0

Conclusion

Tracking memory leaks can be painful, but with the help of the right tools it could be very organized and rewarding. With the help of windbg we easily tracked the memory leak to the source, which turned out to be the MAPI DLL. Unfortunately, the only thing we might be able to do is to avoid calling MAPIInitialize more than once per process. Another is to upgrade the MAPI DLL, with the hope that Microsoft has fixed these issues. But until then, our clients would appreciate if we had found workarounds. Understanding and pinpointing the problem gives the developers the edge necessary to devise a workaround for our customers. And a workaround we implemented.

Update (April 02, 2011):

While trying to figure out workarounds of this issue, I ran into The Intentional Memory Leak by Stephen Griffin, the author of MfcMapi. Apparently, they left the leak in because some ancient applications (going back to the early 1990’s) were accessing freed memory. To avoid penalizing bad code, it was decided to make everyone else pay the price in leaks. This solution isn’t new or specific to MAPI, many other cases exist on OS level as well as other platforms. Still, it doesn’t fail to frustrate.

Mar 012011
 

Lately my colleagues have been commenting on my relentless notes on code styling in our internal code-reviews. Evidently I’ve been paying more and more attention to what could rightly be called cosmetics. Sure there are bad conventions and, well, better ones. Admittedly, coding conventions are just that, conventions. No matter how much we debate tabs vs. spaces and how much we search for truth, they remain subjective and very much a personal preference. Yet, one can’t deny that there are some better conventions that do in fact improve the overall quality of the code.

But code quality is not what worries me. Not as much as worrying about eye strain and accidental misreadings. Both of which are also factors in the overall code quality, no doubt. It’s not rare that we find ourselves agonizing over a mistake that if it weren’t for haste and misunderstanding, could’ve been completely avoided.

C Sample Code: Function Parameter Duplication.

Image via Wikipedia

Developers don’t write code, not just. We spend the majority of our time adding, removing and editing small pieces of code. In fact, most of the time we do small changes in an otherwise large code-base. Rarely do we write new independent pieces of code, unless of course we are starting a project from scratch. Most projects are legacy projects in the sense that they are passed from generations of developers to the next. We add new functions to implement new features, rewrite some and edit some others to meet our needs. All of which means reading a great deal of code to understand which statement is doing what and decide the best change-set to get the output we plan. But even when we work on a completely independent module or class, once we have the smallest chunk of code written, we already need to go back and forth to interweave the remaining code.

Oddly, as I grew in experience I also spent increasingly more time reading code before making additions or changes. This seems reasonable in hindsight. It’s much easier to write new code, much more difficult to try to understand existing code and to find ways to adapt them. Experience tells us that the easiest route is not necessarily the best in the long run. Sure, we might get faster results if we write that case-insensitive string comparison function for the 30th time whenever we need one, or so we might think. But the fact is that chances are that we’ll get a few incorrect results as well, which we might not even notice until it’s too late. With a little effort, we should find a good implementation that we can reuse and learn how to use it. Indeed, that implementation might very well be in our code-base. My example of string comparison is not all that artificial, considering that some languages don’t come with standard string comparison functions, with Unicode, case and locale options. Some languages do have standardized (or at least canonical) functions, but you need to explicitly include the library reference in your projects and that might involve SCM and build server issues. Not fun when the deadline is looming, and when exactly was the last time we didn’t have an imminent deadline? (Notice that I do not mean to imply that DIY coding is a deadly sin. It probably is in most cases, but surely there are good reasons to write your own. Like early optimization, the first two rules are don’t do it. But that’s another topic for another day.)

Another great side-effect to reading code is that one will eventually find bugs and at least report them, if not fix them on the spot (and send for review). So instead of creating new sources of bugs, reuse reduces code duplication and possibly resolves old bugs.

When we anticipate and reasonably-accurately estimate the overhead of possible bugs in our home-grown functions, scattered around the code-base, in comparison to the overhead of learning and incorporating a higher quality library function, then and only then do we stand a chance of making reasonable decisions. Unfortunately, understanding the difficulty of such comparisons and especially grasping the perils of code duplication combined with the Dunning–Kruger effect when it comes to estimating expected bugs in one’s own code, requires, paradoxically, experience to become obvious.

The whole issue of maintaining legacy code vs. writing from scratch is a different battle altogether. However, I will only say that improving on legacy code in any pace is almost always superior to the demolition approach. It’s less risky, you still have working bits and pieces and you have a reference code right on your plate. And here is my point: to avoid rewriting, one must learn to read existing code, and read them well.

To make things more concrete, here are some of my top readability points:

  1. Consistency.
    I can read code with virtually any convention, no problem. I’ve grown to learn to adapt. If I think I need to read code, then I better accept that I may very well read code not written in my favorite style. One thing that is nearly impossible to adapt to, however, is when the code looks like it’s written by a 5 year old who just switched from Qwerty keyboard to Dvorak.
    Whatever convention you choose or get forced to use, just stick to it. Make sure it’s what you use everywhere in that project. 

  2. Consistency.
    There is no way to stress how important this is. People experiment with braces-on-next-line and braces-on-same-line and forget that their experiments end up in the source repository for the frustration of everyone else on the team. Seriously, experimentation is fine. Finding your preferred style is perfectly Ok. Just don’t commit them. Not in the Trunk at least. 

  3. Space out the code.
    Readable code is like readable text. As much as everyone hates reading text-walls, so do developers who have to read sandwiched code. Put empty lines between all scopes. An end-brace is a great place to add that extra line to make it easier to read and find the start of the next scope. Need to comment? Great. Just avoid newspaper-style coding, where the code is turned into a two-column format, code on the left, comments on the right. There are very few cases that one needs to do that. Comments go above the code block or statement, not next to it. Comments are also more readable if they are preceded by a blank line. There is no shortage of disk space. Break long functions, break mega classes and even break long files. Make your functions reasonable in size. Use cyclomatic complexity metrics to know when your code is too complex and hence hard to read and understand. Refactor. 

  4. Stop banner-commenting.
    If you need to add 5 lines of boxed comments within functions, then it’s a good indication you need to start a new function. The banner can go above the new function. As much as I’d rather not have it there either, it’s much better than having a 1000+ lines in a single function with half a dozen banners. After all, if you need to signal the start of a new logical block, functions do that better. Same goes to breaking long functions, classes and files. (Unlike what the image above may imply, that image is just an image of some code, I do not endorse the style it adopts.) 

  5. Don’t use magic numbers.
    Constants are a great tool to give names to what otherwise is a seemingly magic number that makes the code work. Default values, container limits, timeouts and user-messages are just some examples of good candidates for constants. Just avoid converting every integer into a constant. That’s not the purpose of constants and it reduces code readability. 

  6. Choose identifier names wisely.
    There has been no shortage of literature on naming conventions and the perils of choosing names that lack significant differences. Yet, some still insist on using very ambiguous names and reuse them across logical boundaries. The identifiers not only need to be meaningful and unambiguous, but they also need to be consistent across functions, classes, modules and even the complete project. At least an effort to make them consistent should be made. If you need to use acronyms, then make sure you use the same case convention. Have database or network connections, use the same identifier names everywhere. It’s much, much more readable to see an identifier and immediately know what the type is. Incidentally, this was the original purpose of Hungarian notation (original paper). Same goes to function names. ‘Get’ can be used for read-only functions that have no side-effects. Avoid using verbs and nouns in an identifier then implement logic that contradicts the natural meaning of those words. It’s downright inhumane. If a functions claims to get some value, then that function should never modify any other value (with the possible exception of updating caches, if any, which should only boost performance without affecting correctness.) Prefer using proper names in identifiers. Meaningful names, nouns and verbs can be a great help, use them to their limit. 

  7. Don’t chain declarations.
    Chaining variable declarations is a very common practice in C. This is partially due to the fact that Ansi C didn’t allow declaring variables after any executable statement. Developers had to declare everything up-front and at the top of their functions. This meant that all the variables of a given type were declared in a chain of commas. Declare variables in the innermost scope possible and as close to the usage statement as possible. Avoid recycling variables, unless it’s for the very same purpose. Never re-purpose variables, instead, declare new ones.
    A similar practice is sometimes used to chain calls where a single function call which takes one or more arguments is called by first calling other functions and passing their return values as arguments to the first call. These two types of chaining make readability a painful process. Some people chain 3 or 4 function calls within one another, thinking it’s more compact and therefore better, somehow. It’s not. Not when someone needs to scan the code for side-effects and to find a hard bug. A possible exception to this is chaining calls one after another. Some classes are designed to chain calls such that each call returns a reference to the original instance to call other members. This is often done on string and I/O classes. This type of chaining, if not excessively used and too long, can be helpful and improve readability. 

  8. Limit line and file lengths.
    Scrolling horizontally is a huge pain. No one can be reasonably expected to read anything while scrolling left and right for each line. But some people have larger screens than others. Yet some have weaker eye-sight, so use larger fonts. I’ve seen code apparently aligned to 120 characters per line, with occasional 150+ characters per line, back when 17″ screens were the norm. Some don’t even care or keep track of line length. This is very unfortunate as it makes other people’s lives very hard, especially those with smaller screens, lower resolutions and large fonts (read: bad eye-sight.) Code can’t be word-wrapped like article text (without the help of advanced editors.)
    A good starting point is the legacy standard of 80 characters-per-line (cpl). If we can stick to that, great. We should make an effort to minimize the line-length and 80 characters is not too narrow to make things garbled. For teams who can all work with 100 or 120 cpl, the extra line width can give quite a bit flexibility and improve readability. But again be careful because too long a line and readability suffers yet again. Think how newspapers and magazines have narrow columns and how readable they are. Our wide screens with large footprints are like newspapers and moving our heads to read across the line, as opposed to moving just our eyes, is an extra physical strain and certainly a speed bump that we can do without. 

  9. Make scopes explicit.
    Languages often have implicit scopes. The first statement after a conditional or a loop in C-style languages implicitly fall under the conditional or loop, but not consecutive statements. It’s much harder to parse the end of statements using one’s eyeballs to figure out which statement belongs to the implicit scope. Making these cases explicit makes it much easier to see them without much effort. Adding braces and an empty line after the closing brace, even around single-statement scopes does improve readability quite a bit. 

  10. Comment.
    Code is very well understood by machines, even when obsecure and mangled. Humans on the other hand need to understand purpose and reason, beyond seeing what a piece of code would do. Without understanding the reasons behind particular constructs, operations and values, no developer can maintain the code in any sensible way. Comments are a great tool to communicate the less obvious aspects of the code. Explain the business needs, implicit assumptions, workarounds, special-requests and the temporary solutions. Talk to your fellow developers through comments. But, as every rule comes with exceptions, avoid over-commenting at all costs. Resist the temptation to declare that an error is about to occure right before throwing an exception. The throw statement is self-commenting. Don’t repeat yourself. Rather, explain why the case is considered unrecoverable at that point, if it’s not obvious. Prefer to write code that speaks for itself. Self-descriptive code is the most readable code.

As a corollary, some code should be made hard to read. You read that right. Code that depends on hacks, bad practices or temporary solutions should be made harder to read. Perhaps my best example is casting. It’s not rare that we need to cast instances of objects to specific types, and while this is a standard practice, it isn’t exactly highly recommended either. Making the casting a little less readable is a good way to force the reader to squint and make sure it’s not a bogus cast. This isn’t unlike italic text which makes reading the text harder and therefore makes it stand out. In the same vein, temporary solutions and hacks should be made to stand out. Adding TODO and FIXME markers are a good start. BUGBUG is another marker for known issues or limitations. Actually, if there is any place for that banner-comment, this would be it. Make known issues stand out like a sore thumb.

As with most things, the above is mostly a guideline, rules of thumb if you will. They are not set in stone and they aren’t complete by any stretch of imagination. There are many obviously important cases left out. Languages, ecosystems, frameworks and libraries come with their own nuances. What’s clear in one language might be very ambiguous in another, and therefore frowned upon. The important thing is to write with the reader in mind, to avoid confusing styles and especially to be mindful of the context and when an explanatory comment is due, and when refactoring is a better choice.

Conclusion

Good developers write code fast and with low bug-rate. Great developers read existing code, reuse and improve them, generating higher quality code with no duplication and reduced bug-rate for both new and existing code. We should write readable code; written for humans and not just for machines. And we should read code and improve, rather than rewriting.

Feb 182011
 

Apparently there is a face that has been finally attached to the source that Colin Powell mentioned in his war-promoting speech to the UN on February 5th, 2003. Powell described Curveball, the source, as “an eye-witness, an Iraqi engineer who supervised one of these facilities.” The facilities in reference are of course the notorious Iraqi biological agent production trucks, or the labs-on-wheels as they were dubbed. Needless to say, they were fictional and now we know the man who’s imagination produced them. Meet Rafid Ahmed Alwan al-Janabi, or Curveball, the handle used by the German and US intelligence agencies.

At the UN, Colin Powell holds a model vial of ...

Image via Wikipedia

Guardian had an article Curveball’s confession: another dent in the Iraq conspiracy theory. A dent it certainly is. The confessions of al-Janabi certainly undermines the theory that evidence and reasons to invade Iraq were made up, that the war itself served to profit a few powerful elite.

A very interesting side-effect to all this is the heat CIA is getting. Apparently, the then-head of the European office of CIA, Tyler Drumheller, and the then-current CIA director, George J. Tenet, have contradictory memoirs. Drumheller insists that “we didn’t know if it was true. We knew there were real problems with it and there were inconsistencies.” According an article by the Guardian, Drumheller claims to have “warned the head of the US intelligence agency before the 2003 invasion of Iraq that Curveball might be a liar”.

Tenet, on the other hand, denies any warning or a hint of it whatsoever. On his website, Tenet reproduces a piece of his memoir where he wrote:

Drumheller had dozens of opportunities before and after the Powell speech to raise the alarm with me, yet he failed to do so. A search of my calendar between February 5, 2003, the date of the Powell speech, and July 11, 2004, the date of my stepping down as DCI, shows that Drumheller was in my office twenty-two times. And yet he seems never to have thought that it might be worth telling the boss that he had reason to believe a central pillar in the case against Saddam might have been a mirage.

It’s really hard to say who’s who in this mess. It seems that it’s fair to say that very important people dropped the ball. To me the most shocking piece of information in this story is not that they believed curveball or that they didn’t double-check his claims or the lack of any of the standard operating procedures you’d expect intelligent services to have in place. None of that is too shocking, as grave as they all are. The shocking fact is that they didn’t even have a second source or any other independent intelligence on an equal footing as what curveball provided them. For the largest economies of the world to go to war one would expect a bit more reason than the stories of a single, odd, defector-in-exile as primary evidence and reason.

The body-counts and estimates of casualties in Iraq seem to converge on a minimum of 100,000 deaths. This says nothing of the wounded which is almost certainly in the millions, although no good data exists. In addition, millions of citizens became refugees and homeless. 100s of Billions were spent by the coalition forces and the number is still in the rise as expenses for the war casualties are paid out, compensations given and law-suites settled. And all this doesn’t say a word about the destroyed and damaged infrastructure in Iraq and the lasting psychological consequences on the affected.

Perhaps it’s all worth it, considering the biggest gain: getting rid of a brutal dictator. That’s at least the Machiavellian interpretations of things. Perhaps. But if that’s all we care about, then I guess Curveball is irrelevant and Powell needn’t such intelligence to make a case for war. It should’ve been sufficient to make the purpose getting rid of Saddam Hussein. Since this wasn’t the case, I’m bound to believe that Machiavellian reasoning is not good enough to wage war and one needs to demonstrate that these horrendous costs do indeed justify the ends.

If Drumheller is to be believed, he hit the nail right on the head:

The week before the speech, I talked to the Deputy McLaughlin, and someone says to him, ‘Tyler’s worried that Curveball might be a fabricator.’ And McLaughlin said, ‘Oh, I hope not, because this is really all we have.’ And I said, and I’ve got to be honest with you, I said: ‘You’ve got to be kidding? This is all we have!’

But seriously, is curveball all they had?!

Nov 212010
 

Rarely do short introductory books make any justice to complex and large topics such as history. John Arnold made the exception in History: A Very Short Introduction. The book is a member of the highly renowned series of Very Short Introduction books by the Oxford University Press which has more than of its fair share of great introductory books.

John explores the history of historiography and the emergence of the discipline. He uses quite interesting and amusing tidbits from the past to both entertain the reader and to examine a use-case that demonstrates how historians work.

What I like most in this book is how the authors demonstrates that history and the past are not the same, nor are they equivalent. He stresses the point even further when he differentiates between history with a small h and History. The subjectivity and time-sensitive nature of history is well explained in this book. A point that many miss by a long shot. Some have even maintained that historic facts are equal to scientific facts, which couldn’t be further from the truth.

Finally, John writes that history doesn’t tell us how it would have been had we lived in the past, nor does it teaches us lessons for the present and future. Rather, history tells us something about ourselves. By examining others in similar situations and searching about meaning in what happened in the past, we get insight in what we might do in our future.


Meta;
Type: Nonfiction.
Category: History.
Edition(s) read: Audio.
Rating: 5/5.
Recommendation: Highly recommended for everyone.

Nov 072010
 

Jerry A. Coyne does a brilliant job in Why Evolution Is True. This is certainly one of the very best books on the evidence for evolution. Perhaps it’s only counterpart is Dawkins’ The Greatest Show on Earth.

Coyne takes the reader step by step from the hypothesis to testability to evidence in clear and concise progression. The book covers historic, geologic, molecular and fossil evidence, to name but a few. It’s full of interesting stories and factoids. Oddities that can hardly be explained without evolutionary theory is one of my favorite themes in the book.

For a topic this broad and complex, the author did a brilliant job in presenting the material in a half-digested form, ready for consumption by virtually anyone with little background. The book never gets boring. This is a page turner to recommend to anyone who wants to get familiarized with evolutionary biology being entertaining.


Meta;
Type: Nonfiction.
Categories: Evolutionary biology.
Edition(s): Audio.
Rating: 5/5.
Recommendation: Highly recommended for all.

Nov 072010
 

Dawkins takes the topic of evidence for evolution head on in The Greatest Show on Earth. The book starts off by explaining that fossils are not even necessary to demonstrate the validity of biological evolution. Dawkins likens this to a murderer to flees the sentence even when all the evidence mount to definitive incrimination because of new video evidence, that while supporting all previous evidences, contains a gap and is put in the shadows of doubt by the lawyer in defense of the accused. The gap in the evidence video is very similar to the gap in the fossil record.

The Greatest Show on Earth: The Evidence for E...
Image via Wikipedia

The book explores all the different hypotheses and expectation that follow from the hypothesis put forward by Darwin over 150 years ago. In deed, Darwin himself did state how his hypothesis could easily be discredit, if certain easily verifiable conditions turned out to be true. One such condition is the order of the fossils in the different strata or layer of earth. So while there is no expectation for the fossil record to be complete, a single misplaced bone would easily turn the whole biological evolution theory on its head.

Dawkins discusses the evidence from molecular biology and genetics as well as many other sciences. He explains how a seemingly complex organ or biological feature may have come to evolve while serving a functional purpose along its different stages.

There are many things to like about this book, not least the mountain of facts and tidbits that the author enriched the book by. However what I personally like about the book is how it explains that the concept of species is man-made. It’s a labeling system that has no counterpart in nature. In fact, he goes on to explain that each generation is a unique stage in the evolutionary history. We only get to group them when a specific group have significantly drifted from another closely related group. Where significant drift is typically defined to mean the two groups can no longer interbreed.

Overall, The Greatest Show on Earth and Jerry A. Coyne‘s Why Evolution Is True are my two most favorite evolutionary biology books, yet.


Meta;
Type: Nonfiction.
Categories: Evolutionary biology.
Edition(s): Audio.
Rating: 5/5.
Recommendation: Highly recommended for all.

QR Code Business Card