Decorators Instead of ES7 Decorator
Or HoF - An elegant solution for “Decorators are not valid here.”
At DeclareCerto, we have quite a few services in Typescript, and recently I was refactoring some code that had a cross-cutting logic such as connection handling for data repositories. The first thing that came to my mind was obviously Aspect-Oriented Programming using annotations. I knew that ES7 is introducing Decorators, and I decided to try (why not, right?). But in my projects, I try as much as possible to use composition instead of classes and inheritance because it normally is easier to test and the readable is better since it is less code and straight to the point (it looks like C modules).
The original code was like this:
As you can see, the connect and disconnect function calls are being repeated in both places (find and create).
A higher-order function that uses “Generics” would be a good alternative to the ES7 decorator since it would extract the reusable code into a single function.
The previous code would be the one imported in the next code block (line 2).
If you check the file utils.ts, you can see the implementation of the HoF withConnection. This function returns an anonymous function that first calls the connect, then the target function, and then the disconnect function.
I hope this will help you improve your code, and please let me know if you have any questions or suggestions.
If you want to know more about decorators, check this book.
If you want to know more about higher-order functions, check this article.
The image used in this article belongs to Refactoring Guru.