The two kinds of reusability
As a developer, you’re told that your code artifacts (e.g. libraries, components, classes, functions) should be reusable. It’s not enough if your stuff just works and is fast. If it’s not reusable you’re a bad developer.
So what is this holy grail called reusability all about? What does some code artifact need to fulfill to be reusable? Turns out there are two fundamental kinds of reusability which are quite different:
- Reusable in many different contexts
- Easily reusable
Fundamental kinds of reusability
Reusable in many different contexts
An example for an artifact that is reusable in many different contexts might be a function that has one or many complex dependencies as parameters. The concrete example would be a function that takes an array of some data as a parameter and generates some HTML out of it.
The code using such a function would first have to perform the database query to get the necessary data, put it in the structure the function understands and then call it. Reusing this function is not easy but this design has the advantage that the function can generate the HTML from multiple sources, not only from a database.
An example for an artifact that is easily reusable might be a function that has few parameters and the ones it has are simple ones like strings and booleans. This might be a function that takes a database connection string as a parameter and generates some HTML with data it obtained by querying the database. To do so it would have to know the structure of the database.
The code using such a function would just have to call it with the connection string as parameter and get the readily displayable HTML. Reusing that function is really easy but this design has the drawback that the function can only create HTML from that database.
Work from the first kind of reusability towards the second. So start by implementing your functions and classes in a way to make them reusable in many different contexts. Afterwards you add some code that wraps and combines these functions and classes to make them more easily reusable.
Always make sure you and the people you’re communicating with have a common understanding of which of the two kinds of reusability is talked about.