DEV Community 👩‍💻👨‍💻

Cover image for Don't abstract code too early
James Won
James Won

Posted on

Don't abstract code too early

When we first learn to code we learn that abstracting is a good thing.

"You should avoid repeating duplicate code. Follow DRY (Do not Repeat yourself"

This advice is well-intentioned and wholly correct in many cases. But not all cases.

The readability, timing and usefulness of abstraction are just as important to consider as DRY.

Some good reasons to make you think twice before abstracting

  1. If you abstract too early you won't really understand the different facets of how the code should be used.

  2. You can over-engineer/over-predict what you need. This seems innocuous but from my experience this causes some of the most catastrophic bugs and tech debt.

  3. Sometimes they really should be different blocks of code or functions. They may seem similar - but it may just work better if they are separate.

  4. They can be harder to test. And as an extension harder to maintain.

Some useful things to consider before abstraction

  1. Do I need this abstraction now? If it only used in one scenario don't anticipate a scenario that hasn't arrived yet.

  2. Do I sufficiently know what I need to abstract?

  3. Are the cases I am wanting to accomodate with the abstracted code really simpler using the same code?

  4. Can I easily test the abstracted code and make sense of what it does?

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.