DEV Community


Posted on

Is removing Duplicate code always good?

While refactoring code, If I see duplicate code, I will do below

  • Make a function with common code snippet
  • Remove all the similar duplicate code
  • Calling common method whenever required.

My opinion on duplicate code.

  • Need to update the code in all the places when some changes need in that code snippet 
  • Need to test all the flow which involves this code snippet 
  • There is a definite chance to miss to modify in all places (Major problem)

Removing duplicate code is good for maintainability as we will have less code(and less bugs ;-))

But Removing duplicate code is not always good.
As per the design principle keep it simple, stupid(KISS),
unnecessary complexity should be avoided. All functions kept simple rather than made complicated.

Let's take below examples with sample code.

  1. Validating date format (startdate and enddate)
  2. Validating username (admin and customer)

These code samples are only for example purpose, so writing very basic validation code.

1. Validating date format:

See duplicate code in the two methods validate_start_date and validate_end_date.
In this case you can remove duplicate code and make a common method as validate_date().

Reason for making a common method are.
  • validation format is same (yyyy-mm-dd) for both methods


2. Validating username:

for admin and customer users, even though code is almost same in both methods, validate_admin_username() and validate_customer_username(), It's NOT advised to replace into common method validate_usernmae() like validating date for below reasons.


  • Simplicity is the higher priority than maintainability
  • Remove dependency between admin and customer - As per KISS design principle , not making complicated 
  • Different Feature enhancement may come in future for admin and customers

If we keep separate methods for admin and customer, later it will be very easy and simple for adding features separately for admin and customer.

In conclusion, It is absolutely fine to have duplicate code until it matches KISS principle.

Happy Learning!!!

Top comments (0)