DEV Community

Discussion on: How to write clean and readable code

Collapse
 
cubiclesocial profile image
cubiclesocial

Some code duplication is okay. Here's a good rule of thumb to follow:

  1. Write code inline.
  2. The second time you need to write/use the same code, make a mental note that you are duplicating code. If, at this point, you can see yourself needing that code over and over and over again, then refactor here. Otherwise, carry on by duplicating the code.
  3. The third time you need to write/use the same code, it's probably time to consider refactoring the code into a function, class, or a formal library.

In short, one duplication isn't all that bad. It happens. Two duplications is where it's probably time to refactor the code as it is an indicator of something that could end up getting fairly ugly rather quickly.

However, there are a couple of exceptions to the above rule of thumb. The first is that having libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries depend on other libraries causes performance and resource usage problems. You want your application function call stack to be pretty flat. If you import a whole library that imports a bunch of other libraries just to call one teensy tiny function and that function has no particular dependencies on anything else (e.g. it is static or close enough to static), it is far better to copy that one function into your own code than to import a gazillion libraries and waste a ton of system resources. Could you have 10 copies of the same function across multiple libraries floating around as a result? Sure. But the call stack stays flat and resource usage is minimized.

The second exception to that rule of thumb is that application performance is a reason to NOT refactor inlined duplicated code into their own functions. Calling a function has significant overhead whereas inline code, even repeated, can be many times faster when run inside a tight loop. You need to be doing some serious data/number crunching in a loop or writing a virtual machine for this to be a problem though. Code readability is generally a good priority to have. Regardless, knowing when to not refactor is just as important as knowing when to refactor.

Collapse
 
ajebodev profile image
Emmanuel Echefu

Rightly stated.... ;) Do read up my other posts if it's not too much trouble, ( dev.to/ajebodev/debugging-code-a-s... that's a link to my most recent post). Have a great day, look forward to further interactions.