I had pretty much assumed that nearly all software developers would know what I mean when I use the words anti-pattern and code smell. Over the last couple of months, I have come to the conclusion that this is not strictly true.
What is an anti-pattern?
When asking this question, I have received a number of different responses. Everyone seems to have a basic understanding, but most don’t have any clearer idea than “it’s bad code.”
To understand what an anti-pattern is, you must first know what a pattern is.
Over time, many different software developers have had to solve the same or similar problems. How many different developers have needed to restrict user access to portions of an application? Or had to communicate object states between threads or machines? Some developers come up with good solutions, others are able to solve the problem, but do it poorly or inefficiently. These are patterns, and only recently have we been giving them names. For example, when good developers solve the problem of securing an application, most of the time it may look like what we now call the Role Based Access Control pattern.
Anti-patterns are patterns. They are just undesirable ones. Taking our same example, when bad developers solve the problem of securing an application, you may end up with poorly-designed objects resulting in what we call the Divergent Change anti-pattern (or any number of others).
So that’s it. When I talk about anti-patterns, I am referring to common mistakes or the reoccurring results of poor decisions.
What is a code smell?
Code smells seem to be even more misunderstood. I often hear people mistake “code smell” with “bad code”. This is not always, or even usually, true.
Imagine you are walking down the street, and your neighbor’s house is on fire. How do you know? Intuition? No. You look at the house and see smoke, maybe hear someone screaming or the sound of police sirens. There are any number of symptoms that would indicate there was a fire.
These symptoms (smoke, fire trucks, etc.) are analogous to code smells. Code smells are not the problem. They do not produce compile errors and are not even bugs. They are simply evidence that there might be a bug or other issue nearby.
Now imagine you are walking down the street and you see smoke rising above a house. Do you call 9-1-1 right away to try and save their house from becoming a blazing inferno? No. You would investigate, and maybe discover that they were just grilling in their backyard.
My point is that code smells are not the problem. The benefit of understanding code smells is to help you discover and correct the anti-patterns and bugs that are the real problems.