Knowing or unknowingly we all introduce code smell in our test automation code and thus I feel that after every 3-4 sprints, there should be a dedicated sprint for Refactoring our test automation code. It’s an essential part of any software development and thus we should constantly review our code for bad design and try to chuck out any kind of code smell.
Code Smells:
Code smells and anti-patterns are usually not bugs and they do not currently prevent the program from functioning. In fact, they indicate poor design and implementation in software that may increase the risk of future failures. And thus these are technical debts.
Refactoring:
Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure — Martin Fowler
Here are the common causes of Code smells:
1) Comments
If you feel like writing comments for all the classes and methods, first try to refactor it as your code should be self-explanatory and self-documenting to the max-content. The naming convention should be strong- Names assigned to variables, methods, and classes should be clear and meaningful.
2) Large Classes
Large classes containing too many methods and properties are very hard to understand and maintain due to their complex structure.
3) Shotgun Surgery (Ripple effect)
A change in one place requires us to alter many different classes.
4) Duplicated code
The same code structure in more than one place will also be called the Ripple effect.
5) Incorrect locator strategy
Instead of the ones provided by a browser (Dev Tools) in the form of a “Copy full XPath”, “Copy XPath”, etc., use reliable locators such as id or name, etc. if possible otherwise write your own XPath.
6) Static waits
Hard-coded waits like thread.sleep lets the test pause for n number of seconds. It slows down your test execution time. Use smart waits like Explicit and Fluent as these wait for only the amount of time that is required.
Go through this insightful article by Mikhael Levkovsky to know more about Code smell:
https://hackernoon.com/5-easy-wins-to-refactor-even-the-worst-legacy-code-7vuc3069
Code climate is one such static quality analysis open-source project that analyzes your repositories from Github, BitBucket, and other platforms and displays the number of Code Smells.
You can buy this book if you are interested in learning more about Refactoring:
https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599/ref=sr_1_1?keywords=Refactoring%3A+Improving+the+Design+of+Existing+Code&qid=1579624156&s=books&sr=1-1