Thursday, July 16, 2020

Intermediate, meaningful variable names

Here's another good idea from Uncle Bob. While it's technically faster and more compact to directly include complex conditions in code, consider creating and populating a meaningful variable and then referencing that. For example, this code is  less clear...

            if (length * width * height > 1000000)
                throw new ArgumentException();
  
Whereas this code is more clear...

            bool BoxTooBig = (length * width * height > 1000000);
            if (BoxTooBig)
                throw new ArgumentException();
  
Even better...

            int MaxBoxSize = 1000000;
            bool BoxTooBig = (length * width * height > MaxBoxSize);
            if (BoxTooBig)
                throw new ArgumentException();

                             
Sometimes more is more.

Here's a piece of code I found in a new application being developed...

            if (dr["Flags"].ToString().Substring(17,1) == "C")


Clearly this application has dire need of some TLC but at least we could have...

            const int DocumentStatusOffset = 17;
            const string CompletedStatus = "C";
            if (dr["Flags"].ToString().Substring(DocumentStatusOffset, 1) == CompletedStatus)


No comments:

Post a Comment