Thursday, September 11, 2014

Double Post To Start Off Renewed Blogging Attempt

I'm doing two posts today in my renewed effort to blog. Don't expect this pace from me though. in fact, keep your expectations low.

Today I'm pointing out that clever code is not a good thing. You should code in a way that even non coders understand what you are trying to achieve (if you are using a high level language that is, if you are using a low lever language, then go ahead and ignore this advice, nobody will be able to understand anything you could write without a great deal of effort no matter what).  A quote by Brian Kernighan is "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

So you should write code like this:

          public string GetMonthAbbreviation(int MonthId)
         {
             switch (MonthId)
             {
                   case 1:
                              return "JAN";
                              break;
                    case 2:
                              return "FEB";
                              break;
                    case 3:
                             return "MAR";
                             break;
                    case 4:
                             return "APR":
                            break;
                     default:
                            return "N/A";
                            break;
'              }
          }

And NOT like this:

               private Dictionary<string, string> Monthlist;

               public Constructor()
               {
                     Monthlist = new Dictionary<string, string.>;
                     MonthList.Add("1", "JAN");
                     MonthList.Add("2", "FEB");
                     MonthList.Add("3", "MAR");
                     MonthList.Add("4", "APR");
                }

              public string GetMonthAbbreviation(string MonthId)
              {
                       return (MonthId != null && MonthList.ContainsKey(MonthID)) ? MonthList[MonthId] : "N/A";
               }

Which seems easier to understand?

No comments:

Post a Comment