Let me break it to you, this post has nothing to do with charity! Now, let’s start with a question:
How do we enrich something?
By making it abundant, rich in features and resourceful!
In simple OOP terms, we add additional feature methods to the class!!
Let’s try to enrich a Person class, starting with the basic class:
Now, to make a person speak French, we have to add another method to our Person class:
This is perfectly fine! Just add the additional feature to the existing class and make it rich.
But… there are cases when we cannot add features/methods to classes, like, library classes (java.util.Date, String, etc).
To add features to such classes we have to make “wrapper classes”. Suppose we want to add the “spell the digits” feature in the standard libraries Int class, we would have to make a wrapper class over Int.
Problem with this wrapper class approach is, if the desired class’ objects are used in a lot of places, then refactoring the class objects to our Rich-Wrapper class objects becomes a real pain!
Solution: Implicit classes and extension methods
We will now make slight changes to our wrapper class:
- Add an implicit keyword in front of the class.
- Put the implicit class in a container object, which has a reason but also is generally a good practice. This way, we can import the “rich” feature at will!
- Import contents of the container object.
- Use the method on simple objects directly!
This pattern of creating an implicit class to enhance a library’s features has a funny name
“Pimp My Library Pattern”
The example we shown above was a very basic example of Implicit class and its extension methods. The application of Implicit classes reach far beyond this!
One such example, is creating a generic method time profiler:
Then, what are your waiting for? Since, now you’ve learned to “pimp” any library, go make the mundane library objects rich with features you like!