Does your code smell bad?
Before we get into the code smell, imagine the name of any of your coworkers you want to punch for bad code. I assume you have a lot in mind. If your colleague also has the same observation about you, what would be then? Therefore, if you want to be a good coworker, you should also be a good programmer.
Code Smell !!!
Code Smells are not the bugs of the program. Your program might function perfectly even when there are code smells. They do not prevent the program from functioning or are incorrect. They just signify the weakness in design and might increase the risk of bugs and program failure in the future.
Typical examples of code smells include the following:
- duplicate code
- dead code
- long methods
- long parameter list
- unnecessary comments
- unnecessary primitive variables
- data clumps etc.
Now let's see how to eliminate this bad habit to be a good colleague.
How to eliminate Code Smell?
One of the best methods for getting rid of bad code smells and maintaining good code hygiene is code refactoring. Refactoring is a restructuring technique used to make the code clearer, shorter, and more effective without affecting its essential functionality.
Right now, What do you think? How to refactor and when?
It is best practice for programmers to clean up existing code before adding any new code. Secondly, after the team has deployed the code into production. Another good time to refactor code is after a team has deployed code into production.
Let's see few hacks to refactor existing code to make it code smell to good smell.
Few Refactoring techniques
- Code is broken down into smaller blocks of code. Fragmented code is then isolated, extracted and placed into a separate method. Then compose it a parent method.
- Make a simplified method that is done with only one task.
- Try to utilize Dependency Injection to reduce parameters of a method.
- Remove dead code.
- Follow the Law of Demeter. A method should know only its direct dependencies.
- Be consistent. If you do something a certain way, do all similar things in the same way.
Let's end with a quote-
“Any fool can write code that a computer can understand, good programmers write code that every human can understand. — Martin Fowler”
Thanks for your time.