Bad Smells and Refactoring

Software needs to change. And in the process, the source code tends to drift away form original design. And bad smells would gradually emerge.

Large class is one of the bad smells. And one of the examples that always come to my mind when talking about this bad smell is the MessageContext class. Right now, this class has 4094 lines of code. And there are so many instance variables and so many methods. And because of this, given an instance of this class, it is so hard to understand the state of that instance.

The bad smells tell you that something is going wrong with the source code. And to ensure that the code lives longer, we need to clean up the code to ensure that the bad smells go away. The good news is that, we can always fix the bad smells through refactoring techniques.

Code refactoring is the process of changing a computer program's code to make it amenable to change, improve its readability, or simplify its structure, while preserving its existing functionality. - Wikipedia

There is one key factor to note in the above definition. That is, refactoring is about fixing internal structure while preserves existing functionality. To preserve internal structure, you need to have appropriate tests in place, lots of them, to ensure that the system before and after the refactoring to be identical in terms of functionality.

One of the problems with open source projects is that, more often than not, all developers want to do attractive and sexy tasks. Hence, less appealing tasks such as documentation and testing get pushed to the corners and hardly taken back on to center stage. Hence, refactoring is always tough, because the testing factor is missing or not good enough to guarantee preserving functionality. This thread from Axis2 list provides ample evidence on resistance to change, siting difficulties in guaranteeing if all stuff that used to work, would work after a change as expected. The change proposed in this mail tread is not a refactoring, but the same problems would apply. However, if there were enough tests, such a concern would not arise.

Software needs change. Bad smells will arise. Refactoring can help fix them. Testing must be in place to guarantee functional consistency. Testing should not be an afterthought, it is a pre-requisite.

Comments

afkham said…
Just like "code smell" we could also sense "design smell" or "architecture smell". The rule of thumb is that if your design or architecture is too complicated to explain, includes many workarounds & becomes very complex when handling certain scenarios, there is something wrong in the design, architecture or the architectural decisions.

Another thing which is related to "code & design smell" is, if you are writing procedural code (e.g. if-elseif-else type of code) in an OO language, you need to revisit your design.