DEV Community

Aaroh Mankad
Aaroh Mankad

Posted on

Cleaning Up Your Code: Abstracting Reused Code

This is an excerpt from my article "Cleaning Up Your Code" on Medium. I'll be publishing each section daily, read ahead on Medium!

If you’ve found pieces of code in your codebase that are heavily duplicated or rely on the same logic, they are probably great contenders for abstraction.

Abstracting code into a separate function or class can help reduce code complexity. If your algorithm related to that block of code changes, you only have to change it in one place versus changing it in multiple places across your codebase.

What does a good abstraction look like? Well let’s take our example from earlier. The great_names.cpp file is really easy to read! However, we would have to rewrite that code block if we ever wanted to find a cell based on a different FLAG_CODE or in a different gameBoard. So let’s move that code into an isolated function.

Before you decide to start splitting your code apart, here are some things to keep in mind:

  • Keep your functions small: A small function is easy to read, but also very easily reused. Your function should be able to be used for a wide variety of use cases, not just the one case it used to be in.

  • Limit the functionality: If your code does more than one exact thing, it will be difficult to use it across your codebase. Continue splitting your code until your functions have only one purpose each.Then you can implement a function to call these smaller functions in any way you wish!

  • Ensure no side effects: A function should be thought of as a walled off piece of code that you control. It should purely accept input and return output. A pure function is a function that does not affect any code it does not have direct access to. A simple example would be an impure add function that adds two variables outside of its scope. This is very hard to keep track of and should be avoided in most situations.

Thanks for reading! What are your approaches to breaking up reusable blocks of code?

Top comments (0)