Code Smells

Code Smells – Issue Number 3

Code Smells – Issue Number 3 (Image by http://www.sxc.hu/)

Code Smells

Welcome to the third edition of Code Smells! Periodically I’ll be posting about how to detect code smells and what they mean in terms of the big picture of your code. The previous installment can be found right here.

What’s a code smell? Wikipedia says it perfectly:

In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. Code smells are usually not bugs—they are not technically incorrect and don’t currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.

These code smells are often based on my own opinion and experience with programming. If you disagree with what I’m saying in my post, please don’t hesitate to post a comment. I’d love to clarify anything I may have worded poorly and discuss your perspective–especially if you have a completely different take on things!

The Stink List

Code Smell #7: Using exceptions to control logical flow. This is a pretty nasty path to get into and a bad code smell to stumble upon. Luckily, it’s generally relatively easy to improve. Using exception handling to control logical flow is, in general, misleading. It’s relying on a mechanism used to catch unexpected errors in order to direct the flow of your program. Often times we can use things like if statements to check for these conditions before throwing exceptions.

A common scenario where I see this is parsing. I’ll illustrate this code smell with a little C# example:


var input = "This is not a number";
try
{
  var parsed = int.Parse(input);
  DoSuccessfulStuff(parsed);
}
catch (Exception)
{
  DoFailStuff();
}

It seems a bit contrived, but I’ve seen lots of code written like this–and you know what? This works. It gets the job done. However, there are other mechanisms built-in to .NET that let us do parsing a little bit nicer:


var input = "This is not a number";
int parsed;

if (int.TryParse(input, out parsed))
{
  DoSuccessfulStuff(parsed);
}
else
{
  DoFailStuff();
}

The second set of code doesn’t need to catch exceptions to know that the parsing wasn’t successful. It may not be obvious from this example but throwing and catching exceptions can be quite expensive compared to a few logical sanity checks instead (and before getting into a debate on this, just know the impact it has on your program. I’ve had things go from taking several seconds to multiple minutes, but there are certainly cases where performance will be negligible).

The additional kicker in my contrived example is using the base Exception class to create what a colleague of mine refers to as Pokemon Exception Handlers. Thus, even if you didn’t want to restructure your code, using a specific exception type would:

  • Indicate to other programmers what you’re trying to accomplish
  • Not swallow other potential problems and have them go unseen

Now, this code smell isn’t always possible to avoid entirely. If you’re interfacing with third party components, sometimes you do have to rely on catching exceptions that you can’t otherwise check for ahead of time. If you don’t have the code, you can’t know for every path how/when/why exceptions will be thrown. The same thing could be said when running within an environment where state cannot be guaranteed. Sometimes it’s just necessary. In this case, I would suggest that instead of using Pokemon Exception Handlers, you try to catch the specific exceptions you know you need to watch out for.

Takeaway:

  • If a simple logic check can be used instead of throwing/catching exceptions, it’s likely a better bet.
  • Try to avoid exception handlers that catch all exceptions. Something nasty might sneak by as a result of it.
  • Interfacing with some code or working working in certain environments means you have to rely on exception logic. Take a deep breath and move on.

Code Smell #8: Having an object hierarchy that requires many very light weight classes. Object oriented programming and how object hierarchies are structured are pretty complicated topics of discussion, so I’m not about to try and over simplify it with discussion of this code smell. This is mostly something I’ve gathered from my own programming experience, so I’ll try to illustrate with examples that parallel things I would have come across.

When I’m building an object hierarchy, sometimes it’s not really apparent just how big and complicated it might get. I might start off with a base class and two child classes of it. Over time, the top three levels in my hierarchy have all turned into some sort of class abstraction, and I don’t hit concrete implementations until a few levels down hte hierarchy. Not a big deal–Sometimes it’s just hard to tell where things will go. When things get to the point where in order to introduce a new class and functionality all I need to do is inherit a class and override a single property or method, that’s a bit of a red flag for me.

On the surface, this seems pretty cool. The hierarchy is apparently solidified enough that extending it is really simple if all I need is a single property or method replacement. So why is this a code smell?

In my opinion, it has to do with the duplication of code. If I end up having many child classes (where child in this case represents the child-most class of my mature object hierarchy) that differ only by a single property or method, then I should look at how these classes are being constructed. I wrote recently about how I used lambda expressions to refactor similar code with classes that differed by a single method. My solution, in this case, was to examine the factory that created my classes. Instead of having 10’s of different child classes with a bunch of boilerplate code, I had one factory that could specify the code that differentiated each class.

The benefit of this?

  • Keep class hierarchies from ballooning our of control. Changing an API down the road can mean making changes in many spots.
  • Reduce duplication of boilerplate code. This might be the code required to define a simple constructor or override a getter property.

This is only one small example, but if you get into this situation in your class hierarchy, I’d recommend investigating to see if you can refactor in a similar approach. Maybe your class hierarchy is incredibly mature and isn’t changing much. If that’s the case, you may not even want to touch it. So be it. If you’re still actively adding classes to your hierarchy, it may be better to try analyzing it sooner rather than later.

Takeaway:

  • Object oriented design is a complex topic of discussion.
  • There’s no one perfect way to make your class hierarchies.
  • Having many child classes that differ by a property/method or two may be worth checking for refactoring opportunities.

Summary

I hope you enjoyed this issue of Code Smells. As always, it’d be great to open the floor to discussion. I don’t believe in absolutes, so identifying code smells is not meant to be me preaching some made up laws of programming. Let me know your thoughts on these code smells or share code smells of your own!


Code Smells – Issue Number 2

Code Smells (Image from http://www.sxc.hu/)

Code Smells

Welcome to the second edition of Code Smells! Periodically I’ll be posting about how to detect code smells and what they mean in terms of the big picture of your code. The previous installment can be found right here.

What’s a code smell? Wikipedia says it perfectly:

In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. Code smells are usually not bugs—they are not technically incorrect and don’t currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.

Onto the code smells!

The Stink List

Code Smell #4: (Thanks to reddit user fkaginstrom) You have an large number of parameters being passed in to your function call. Functions that take in a ton of parameters stink for a few reasons. How many is too many though? This is a topic that people have debated all over The Internet. This Stack Overflow answer even quotes an author saying to never have more than three parameters in a function. In my opinion? There’s no fixed number. It’s going to vary from situation to situation, project to project, class to class, and method to method. Putting a fixed number on it is sort of setting up a rule to be broken.

What can you do to avoid this kind of smell? This C#-based Stack Overflow thread has a bunch of great ideas. One simple solution is just to bundle things into logical groupings of data. An example (although, it’s potentially a poor example since it’s only two parameters) is x and y coordinates. You can bundle these into a custom point type and pass this into functions. Now a function that may have taken four pairs of coordinates is reduced from eight parameters down to four. This approach also introduces the dependency on your custom type for your function, but I’m just offering it up as an option. If you’re always passing around the same group of X pieces of data around, it may make sense to bundle them into a single container type.

A side effect of reducing the number of parameters your functions require is readability. It might seem minimal, but having functions with only a handful of parameters keeps them from becoming unwieldy and much easier to understand when scanning through code. Readability is sometimes overlooked by developers, but when you’re in a team (and most developers work in teams), it goes a long way.

Code Smell #5: (Thanks to reddit user fkaginstrom) Your class has a large number of methods. If we keep the Single Responsibility Principle in mind (which states that a class should have one reason to change), it’s a warning sign that we might be creeping in on violating it. How? If more and more methods keep getting added, more responsibilities/capabilities can sneak in. This MSDN blog article also highlights some examples of the Single Responsibility Principle. Essentially, as the methods within your class grow in numbers, your class becomes responsible for more types of things. If you later on want to use  just one of those things in a different context, you’re now required to use one big heavy-weight type. Of course, this heavy-weight type comes with it’s own bundle of dependencies, setup requirements, and so on.

How do you avoid this? You can start by refactoring your monstrous type into multiple types. If your type has 12 methods that it defines, and they fall under three general categories of functionality, consider making three interfaces to group the functionality. Then you might consider adding three classes that stay true to these interfaces. The MSDN article I mentioned before does a good job of explaining  how this kind o approach works.

Code Smell #6: Your single method has grown to hundreds of lines. This is one code smell I find that newer programmers introduce more frequently than experienced programmers. However, when you’re working on an enormous code-base, sometimes this type of thing sneaks right up on you. So what’s the problem with having one method do a ton of things? It’s a convenience, isn’t it? let’s say someone only has to call one method that can launch a rocket, play golf, and invest in the stock market while filming a block-buster movie. That’s power and ease of use, no?

This related to Code Smell #5, in my opinion. The convenience of being able to call a method that does all sorts of fancy things at once is the exact inverse of the problem you face when you want to test the method. If I just want to test that I can successfully start the burners in the rocket, I have no choice but to call the method that does everything. What makes this problem even worse is that once your code has been structured this way, breaking down big methods into smaller methods can prove to be a challenge. When you see how dependencies are passed down the call hierarchy, or where certain classes have knowledge of others, things become scary.

I’ll give one real life example of something I saw recently in a particular code base. A test had to be written to cover a problematic area of code that had been refactored. There needed to be some sort of verification in code that proved this section was behaving as expected under particular conditions. Great stuff. Except the section of code existed inside of a method that did the following:

  • UI interaction
  • Database read
  • Data processing
  • File read
  • Data processing 2
  • Database write
  • External disk operation* (This one was pretty specific to the project I’m describing, but it wasn’t just a simple file read/write)
  • File write
  • UI interaction

Where the highlighted “Data processing 2” is the section of the method that needed testing. How’s that for fun? In order to test this one section properly it required refactoring of all of the encompassing code so that we could test it as a unit.

Have your own code smells? Share them in the comments. Follow Dev Leader on social media outlets to see code smell updates as they come out!

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+


Code Smells – Issue Number 1

Code Smells (Image from http://www.sxc.hu/)

Background

I thought this might be kind of fun (fun can also be read as “upsetting”), so I’m giving it a shot. It’s pretty frequent as programmers we go back and revisit some code and find ourselves shaking our heads at what we see. These code smells often don’t show their faces when they’re being created, so don’t beat yourself (or anyone else) up just yet. Common signs you’ve stumbled upon a code smell are when you find yourself saying:

How could that co-op have possibly coded this?! Blast those interns!

Or

What the heck was John thinking when he put this together?! Does he not have a brain?!

Or

No wonder we find so many bugs in this part of code! Look what Jane did!

But it never truly hits home until you get one of these:

What is this crap?! This is by far the worst code I have ever seen. How cou–Oh. Wait. I did that.

Code is always a work in progress. If it’s not, it’s because you’re writing a one off script or your code doesn’t do much of anything. Our skills as programmers are always transforming as are our perspectives. You’re guaranteed to have one of these moments if you’re programming long enough and look back on your code that was once The Pinnacle of Awesome.

With that said, I’m hoping to share some code smells that come up as I see them in my own projects or when talking with friends/colleagues. You might be about to type up one of these code smells, so pay attention! I don’t know how frequently I’ll put one of these posts together, but I might as well start now. Every time I get a handful of code smells I’ll try to push something out to The Interwebz.

The Stink List

Code Smell #1: Your variable is named or prefixed with “temp”, “tmp”, or some variation of “temporary”. This is unnecessary. If you have a variable, by definition it’s something that’s temporary. Nothing in code lasts for forever. You’re just lengthening a variable name or not putting enough thought into a good name.

Code Smell #2: Your variable is one character long. The exception to this is probably for simple loops. You almost always see code that is iterating over a counting variable “i”. Maybe that’s not so bad. If you nest three loops and you have for i, j, and k, things can get messy. If you find you’re using single character names outside of loops… STOP. Just name your variable something that won’t be a puzzle for someone one day from now.

Code Smell #3: You prefix things as “New”, “First”, “Last”, or some other definitive/completely ambiguous position. If you have something that’s “Newest” now and then tomorrow a new one is made, you now have to go change all of your code that used “Newest”, because it’s not the newest now. Same with something like “old” or “new”. It’s the “old” one now, but what happens when your “new” one becomes old because of a third generation? Now you have two olds and a new. What the heck are you going to do? Pick a good name from the start.

Have your own code smells? Share them in the comments. Follow Dev Leader on social media outlets to see code smell updates as they come out!

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress