Skip to content

Clean(er) Code

April 19, 2014

Lately I have been attempting to build a stronger habit of writing clean code.  Currently, I am reading Robert “Uncle Bob” Martin’s Clean Code: A Handbook to Agile Software Craftsmanship. I would definitely recommend it to other developers who want to make sure they have a good idea of what code should not look like.

While maintaining a small personal project of mine, I encountered a function for calculating the MD5 hash of a file based on its provided file name.

        public static string MD5(string filename)
        {
            string result;
            using (var fs = new FileStream(filename, FileMode.Open))
            using (var bs = new BufferedStream(fs))
            {
                using (var md5 = new MD5CryptoServiceProvider())
                {
                    var hash = md5.ComputeHash(bs);
                    var formatted = new StringBuilder(2 * hash.Length);
                    foreach (byte b in hash)
                    {
                        formatted.AppendFormat("{0:x2}", b);
                    }
                    result = formatted.ToString();
                }
            }
            return result;
        }

At the time I wrote this, I am sure I considered this to be a relatively short and clean function. It’s fairly to the point.  However, it’s definitely not following the single responsibility principle.  With a little bit of quality time, I converted this function into a set of functions which I believe are now much cleaner and as an added bonus, more reusable.

The finished product:

        public string FromFile(string filename)
        {
            using (var fileStream = new FileStream(filename, FileMode.Open))
            {
                return FromStream(fileStream);
            }
        }
 
        public string FromStream(Stream inputStream)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                return md5.ComputeHashString(inputStream);
            }
        }
        public static string ComputeHashString(this HashAlgorithm algorithm, Stream inputStream)
        {
            var hash = algorithm.ComputeHash(inputStream);
            var formattedHash = new StringBuilder(2 * hash.Length);
            foreach (byte b in hash)
            {
                formattedHash.AppendFormat("{0:x2}", b);
            }
            return formattedHash.ToString();
        }
Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: