Code Smells

From Wikipedia: “In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem.”

We all need to get things done and most of the time we need to do them in a hurry. Unfortunately the result is that our code are not always a clean as it should be. Fortunately we are not alone in this world and other people experience the same problems that we do.

Code Smells are one of those things that can help us to identify when we are doing things that may hurt ourselves in the future. We may not always be able to fix them, but whenever you encounter a Code Smell, see if you can either justify it or fix it.

Code Smells are not the problem themselves, but they indicate that other problems exist in the code. Solving them is important, but it is even more important to understand why they are bad.

Code Smell for the week: Huge methods/functions

Whenever a method becomes too big it gets hard to follow the logic of the method. Such a method should be broken down into smaller methods that groups together related functionality. If the refactored methods then contains unrelated functionality, consider moving them to separate classes.

When doing the refactoring of big methods, it is common to encounter problems like the constant use of a shared variable throughout the method. This is in its own a Code Smell and may be mentioned at a later stage.

When is a method TOO big?

The size of a method is not the only determining factor. Whenever your method performs more than one definable thing, it's probably too big.

Another telling factor is the levels of indentation within the method. If you start having more than 4 levels of indentation in one method, you have good reason to believe that the method is too big. In methods that are too big, it can become very hard to follow the indentation levels.

Some things to consider:

  1. Don't overdo it. Functions that are too small can hamper the readability of the code.
  2. Don't expose functions to the global name space unless needed.

Please discuss Code Smells amongst each other. It is often more important to know why code smells are bad rather than knowing how to fix them. Knowing why they are bad will most likely result in us producing less Code Smells.