Smell is one of the basic human senses, and among other things it lets us enjoy pleasant scents. Unfortunately, every coin has two sides, so it also gives us the dubious pleasure of sniffing ugly, stinking things. There is a reason for that: if something smells bad, it is probably spoiled and should be thrown away. This association guided one of the gurus of software engineering, Kent Beck, who proposed introducing this term for fragments of code that have the "potential" to cause architecture problems later or simply lead to bugs. Such code smells, or bad smells, are looked for during code reviews or noticed while modifying software, and they are usually subject to refactoring.

It is important that bad smells in code foreshadow potential problems later. In themselves they are usually a part of the code that works and would pass the tests. But anyone who has ever programmed knows that software development largely builds on existing code, and repeating bad habits or relying on ugly solutions (left behind by someone else or by ourselves) will cause bugs in the future, and fixing them will cost a lot of time and nerves. That is why it is so important to develop reflexes for avoiding certain things and to try to write good code more or less "on autopilot". Still, you should also be aware that bad smells do not always come from a lack of skill. They are just as often the result of haste and a chasing schedule, so even the best developers produce them. That is why they should not be treated as "ultimate evil". What is more, they do not always need to be perfumed. We will briefly come back to that at the end of the article.

Over the years, many kinds of bad smells have been identified, and you can find them in many catalogs, such as this one. In this text we will not analyze all of them in detail and will focus on the most common ones instead.

Code duplication

This is by far the most popular bad smell, found at many levels, and it probably comes from haste more often than from a lack of knowledge. Its consequences are fairly obvious: if code that has been duplicated needs to be fixed, you have to do it in two or more places. That is a pointless waste of time and energy, and it also strains our nerves, because we have to remember not to forget anything. Here is a modest example with repeated fragments of code (in practice the duplicates are usually much more extensive):

...
$node1 = $document->createNode('node1');
$node1->setAttribute('attr1', 'val1');
$node1->setValue('element1');

$node2 = $document->createNode('node2');
$node2->setAttribute('attr2', 'val2');
$node2->setValue('element2');

$nodeParent->setChild($node1);
$nodeParent->setChild($node2);
...

Fortunately, the solution here is simple: extract such code into a separate method (or even a class) and use it in all those places. That way the function is not only separated out but can also be found with the search features of integrated development environments (IDEs). There are two possible difficulties. The first is parameterizing such a piece of code properly if there were any differences between the duplicated places. The second is deciding where the fragment belongs. If it was used in only one file, it is simple (an extra method nearby), but if it is a listing used in many different locations, you usually create an appropriate class in some shared module: a core, helper or utility module.

Chain of conditional statements

Colloquially called an "if ladder", this construction uses a very long list of if, else if or switch statements in one place, sometimes filling the entire height of the screen. The purpose, of course, is to perform the right operation or return a specific value in a given case. The problems begin when there are really many of these lines in a row and browsing such code becomes troublesome. The content of these ifs matters too, although in both cases the outcome is negative. If each case executes only one line (for example, returns something), the mere presence of the (often long) conditional statements overwhelms the eye, and if there are more operations, it usually happens in a very long file, which is yet another type of bad smell. On top of that, if there are many such places in the code, then when you add a new case you have to remember to put it in all of them. Again, a small example:

...
if($img->format == 'png') {
	// przetwarzaj grafikę w formacie PNG
}
elseif($img->format == 'bmp') {
	// przetwarzaj grafikę w formacie BMP
}
elseif($img->format == 'gif') {
	// przetwarzaj grafikę w formacie GIF
}
else {
	// przetwarzaj grafikę w innym formacie (np. JPG)
}
...

You can counter such ladders with design patterns suited to the situation, for example State, Strategy or Abstract Factory. If you do not want to reach for a fairly powerful refactoring right away, it is worth checking whether the individual branches have similarities that would let you merge some statements into one, perhaps with extra parameters. Extracting the code into a separate class that returns the right value for a given situation can also help. Then you move the problem elsewhere, but at least it will not be part of other classes with a more "serious" responsibility.

A very long class or method

We have already mentioned this smell, and no wonder, because it also occurs very often and also comes with an apparent convenience. Apparent, because putting code "side by side" in one file may seem a quick and comfortable solution, but a program usually grows rather than shrinks, and that results in ever longer files, classes, methods and so on. As a result, browsing the code later can be very tedious, and changes can be hard to process in various situations, for instance by the mechanisms of version control systems (such as Git). Searching such sets of files is also a nuisance, because we have to filter through one or several files, and we cannot jump to the right fragment by a specific file name, which many IDEs allow.

The solution is obvious: if a method or class is too long, split it into additional submethods or subclasses. This has an extra advantage. If we stick to a good naming convention (following the principle of self-documenting code), we gain an additional element that describes what the program does at that point. Classes that are too long usually take on too much responsibility. The principle says it should be coherent, so for example a class that handles requests about a user should not contain code about the status of a business trip. Splitting the code into more classes gives us extra filtering options in the IDE, because it will be easier to find the file responsible for a given thing (if we name it well). And as if that were not enough, smaller files are easier and faster to read. For methods it is worth following a general rule: if a method does not fit (in height) on one screen, that is a signal that it is worth looking at for refactoring.

This bad smell is related to another, more specific one, sometimes called a "god class". Some software architectures are based on a convention in which there is one (or several) very large classes that refer to all the others and de facto form a critical part of the system. This most often makes them long, inconvenient to edit and browse, and worst of all, any change can cause problems in other parts of the program. It is a clear signal that you should consider splitting it into several classes.

Is it always worth fixing?

Here we come to the question of whether it always pays off to remove a given bad smell right away. It depends on whom you ask. A software engineering researcher will answer differently than someone who builds applications commercially. Everything depends on the situation, the conditions and the state of the project.

You should always take the available resources into account, both people and time. Of course, it is worth fixing code while the schedule is not yet tight and the fix itself is not very time-consuming. The situation becomes more problematic when the project deadline is approaching, or when the refactoring will bring big changes and the need to test many places for potential problems. That is why it is worth analyzing the possible consequences of a given smell. If the code is very unlikely to be extended soon, it may be worth waiting with the cleanup until that development actually becomes necessary. But when we are dealing with a key part of the system, or code that contains mechanics that are often copied, especially by junior developers, it is worth getting to work right away.

Remember that a bad smell found somewhere whose fix is postponed may be forgotten, or after many weeks we will not remember what was wrong with it. There is also the notion of technical debt, which arises when such bad spots stay in the code for too long and begin to affect an ever-growing system, causing various problems. Pulling a project out of such a hole is then extremely difficult, and remember that the client will not spend extra money on it.

One solution is partial refactoring and following the boy scout rule, which says to clean up code "while you are at it" when working somewhere nearby. We mentioned this rule in our article about software maintenance. On the other hand, it is not always worth focusing on writing perfect code right away when that is time-consuming and the clock is ticking. We usually will not foresee every case anyway, and instead of working on functionality we will get stuck chasing perfect constructions. Everything depends on the developer's skills and experience, but it is worth knowing when to actually strive for perfection and when to ease off a little, because it will not bring us significant benefits.

Summary

Bad smells are once again one of the "classics" of software engineering, very often tied to practice. Knowing which source code is "pretty" and which can bring problems is fundamental, and it is worth building on that knowledge throughout a developer's career. At some point the solutions suggest themselves and become easier and easier to apply. Naturally, today we touched on only a sliver of the possible types of bad smells, and we encourage you to keep reading and learning.

Best regards and thank you, Jakub Rojek.