It’s a .NET Life

February 4, 2009

Code Noise Part 2!

Filed under: .NET, Agile, Refactoring — Tags: , , — david.yancey @ 2:48 pm

Last time we looked at what Code Noise was.  This time we are going to look at good practices for eliminating code noise.

Clean Naming:

Clean names reveal intent.
Clean names reveal intent.
Clean names reveal intent.

The point I’m trying to get across here is that good clean names reveal intent.  So what do I mean by this?  Names should tell what it does, why its there, and how it’s used.  You should not have to add a comment to explain what the intent is.  This applies to variables, functions, and class’s.

Let’s take a look at an example:  Before scrolling down to the “clean” version of this example try to determine what the intent of this code is.  After a bit of study, you will determine what the intent is.

public List<int> GetThem(int num1)
        {
            List<int> myList = new List<int>();
            int num2 = 2;
            int num3 = 0;
            myList.Add(num2);
            for (num2 = 3; num2 <= num1; num2 += 2)
            {
                for (num2 = 3; num2%num3 != 0; num3 += 2)
                    if (num3 == num2)
                    {
                        myList.Add(num2);
                    }
            }
            return myList;
        }

Now take a look at this example we can see what the intent of function and each variable.  By taking the time to use better intent revealing names we can reduce the amount of comments needed and have cleaner code.

public List<int> GetPrimeNumbers(int upperLimit)
        {
            List<int> PrimeNumbers = new List<int>();
            int testNumber = 2;
            int checkNumber = 0;
            PrimeNumbers.Add(testNumber);
            for (testNumber = 3; testNumber <= upperLimit; testNumber += 2)
            {
                for (testNumber = 3; testNumber%checkNumber != 0; checkNumber += 2)
                    if (checkNumber == testNumber)
                    {
                        PrimeNumbers.Add(testNumber);
                    }
            }
            return PrimeNumbers;
        }

 

Exception Handling

Tip #1:  Avoid generic exception handling.

Okay now before you start spamming me with comments, emails, general hatred let me explain why.

Generally when we catch a generic exception its to take care of “unhandled exceptions”.  While we don’t want unhandled exceptions presented to the customer we don’t want to default to using Try/Catch blocks just to handle a generic exception.  When we handle an exception we need to know what we are handling and why.

Tip #2:  Instead of returning error codes throw custom exceptions.

Checking return codes for errors can cause unnecessary code noise .  Instead throw a custom exception and catch that exception instead.

Tip #3:  Wrap 3rd party COT’s exception handling in a local custom exception class.

Most 3rd party COT’s exceptions are meaningless to our applications.  It would be better to catch those exceptions together in a local class and throw more meaningful exceptions.

 

These are just a few areas to look at when coding to help ensure clean code.

 

Have fun.

 

David Yancey

November 25, 2008

Refactoring: Getting started is the hard part

Filed under: .NET, Agile, Refactoring, TDD — Tags: , , — david.yancey @ 12:50 am

Just the thought of ‘refactoring’ can be daunting to a programmer. 

Martin Fowler defines ‘refactoring’ as:

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its heart is a series of small behavior preserving transformations. Each transformation (called a ‘refactoring’) does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it’s less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

When I first started to look at our library of Legacy Code my first thought was to just scrap the library and start over.  Now try to sell that idea to the stake holders.  Not going to happen is it.  So that’s where refactoring come’s in.  But there are a few obstacles we have to over come in this process.

  1. Sell the process to the product owner/business:
    J.B Rainsburger used an analogy that helps us with this obstacle.  The use of credit cards.  Each time we purchase an item with a credit card, we are purchasing that item with something we don’t have which is money.  Now let’s take this and apply it to programming against that library of legacy code.  Each time we do we are developing on credit and spending something we don’t have which is time.
  2. Single Methods with large amounts of code:
    First let me refer you to an excellent book by Michael Feathers titled Working Effectively with Legacy Code.  In this book Michael suggests that we take that method and create a class with only that code.  With this class we can now start writing unit tests for the code and begin refactoring.  Now in our legacy code where we just pulled the large method from create a call to the method in our new class. 
  3. Duplicate Code:
    “When N things need to change and N>1, Shalloway will find at most N-1 of these things.”  Basically what Alan Shalloway is saying here is that if you have more than 1 duplication of code chances are high you won’t find all instances of that duplication.  This is where design patterns come in and the phrase “refactor to patterns”.
  4. Where do I start?:
    The hardest obstacle to overcome is where to start.  Practice

    • Start off by finding a section of code that you feel may could use some refactoring. 
    • Work on refactoring it for 30min.
    • Throw that code away. 
    • Take a break
    • Repeat.

    “Throw away my code!!!” you might be saying to yourself right now. Yes, Throw it away. What this does for you is reminds you that you are just practicing and 2nd it separates you from your code.

  5. TDD and Refactoring?:  Yes its possible.  As you go through your refactoring you’ll see that you are refactoring to patterns, while you are doing this, ask yourself “how would I want to test this code?”  Retrain your way of thinking in how you approach code and you’ll soon find yourself refactoring through TDD and Design Patterns.

 

So there you have a few tips on how to overcome a few obstacles when you start to look at refactoring your legacy code for the first time.

 

David Yancey

Powered by WordPress