Leveraging existing code is a great way to become more efficient as a developer.
Oftentimes, we can take advantage of existing code even if it's written in another language, especially if that code is organized into a standalone library. That's where wrappers, ports, and rewrites come into play—three techniques for incorporating non-native code into our applications.
What do these terms mean and when would we use one technique versus another?
Write functions in the native language whose sole purpose is to call the functions in the external library. The goal is to do as little as possible in the native language. For example, translating data types from the native language to the external library language, etc.
Wrappers make sense when the external library is:
- written in a more efficient language than the native code (eg, a C++ library called from Python)
- large/complex and would be time-consuming or error prone to translate
- regularly updated; in a well-maintained library the interfaces (what your wrapper is concerned with) will change less often than the implementation of the features; so if you have wrappers around the functionality, updating to a new version of the library should be fairly straightforward
A port is simply a translation from one language to another. In general, the same logic is maintained as much as possible.
Porting makes sense when one or more of the following is true:
- you want to eliminate the dependency on the external library
- the native language is more efficient than the external library
- the library is simple and you want to save on the overhead involved with wrapping
- you intend to make and maintain changes to the ported code in the native language
- there are no plans to use the external library in its own language
- you want to learn one or both of the languages involved
Think of a Rewrite as a Port with a lot of refactoring. The goal is to take advantage of features of the native language to improve the library in some way (efficiency, readability, etc.)
Rewriting makes sense in all of the same scenarios as porting. Deciding whether to do a simple port or a full rewrite usually comes down to two questions:
- Is there a better way to implement the features of the external library in the native language?
- Is it worth the additional development time?
Wrappers, ports, and rewrites are three techniques we can use to take advantage of external libraries.
- Wrapper: thin shell around an external library ("I'm surprised you didn't know that")
- Port: translation of code from one language to another
- Rewrite: refactoring of code from one language to another
By knowing their strengths and weaknesses–and when to use each one–we can maximize the benefits and minimize the costs of our chosen approach.
Originally posted to StackOverflow
Cover image created with Microsoft Designer