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
