Wednesday, July 23, 2014

Making stringly-typed code palatable via implicit operator

Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
-- http://programmers.stackexchange.com/questions/163185/torvalds-quote-about-good-programmer

Smart data structures and dumb code works a lot better than the other way around.
-- Eric S. Raymond


Strongly-typed code is all the rage now, but some of us still manages to stash various information to string instead of structuring the information to a class.



But if you are in an unfortunate codebase and it has a dumb data structure to begin with, e.g., it has stringly-typed data, at least make a smart data structure facade. Not only smart data structure is easy to code on, it can make the codes that depends on the smart data structure very simple, smaller and easy to read.




using System;

using System.Collections.Generic;


using System.Linq;


namespace Craft
{
    class MainClass
    {

        public static void Main (string[] args)
        {
            var list = new Dictionary<string,decimal> ();
            list.Add ("1_VariablePayBasis", 1337);
            list.Add ("1_DecisionAmount", 168);
            list.Add ("3_BasePay", 5201314);


            // Dumb data structure. Smart code.

            foreach (var kv in list) {

                // boilerplate codes. a.k.a. Smart Code
                string[] strings = kv.Key.Split('_');
                int pk = Convert.ToInt32(strings [0]);
                string fieldName = strings [1];


                Console.WriteLine ("{0} {1} - {2}", pk, fieldName, kv.Value);
            }
            Console.WriteLine();


            
            // Smart data structure. Dumb code.

            // via explicit casting, being explicit with implicit :-)
            foreach (var fv in list.Select(x => (FieldValue)x)) {
                Console.WriteLine ("{0} {1} - {2}", fv.PrimaryKey, fv.FieldName, fv.Value);
            }
            Console.WriteLine();



            // Smart data structure. Dumb code.

            // neat implicit! it still feel a bit explicit though. we can't use var here
            foreach (FieldValue fv in list) {
                Console.WriteLine ("{0} {1} - {2}", fv.PrimaryKey, fv.FieldName, fv.Value);
            }

        }
    }

    public class FieldValue
    {
        public int PrimaryKey { get; set; }
        public string FieldName { get; set; }

        public decimal Value { get; set; }



        public static implicit operator FieldValue(KeyValuePair<string,decimal> kv)
        {
            string[] strings = kv.Key.Split('_');
            int pk = Convert.ToInt32(strings [0]);
            string fieldName = strings [1];

            return new FieldValue { PrimaryKey = pk, FieldName = fieldName, Value = kv.Value };
        }
    }
   
}


Live Code https://dotnetfiddle.net/qX2UeA


Happy Coding! ツ

No comments:

Post a Comment