In this post, I'm sharing my opinion on why you should abstract your third party libraries or any even native ones, into separate classes and methods, instead of using calling them directly.

The best benefit is that it's easier to change your codes later on. So first let me describe what I mean.

Authentication

Let's say in your front end web application, you're using local storage to store the token returned by the authentication server. In this way, you can include it in the headers whenever you make a request to the server.

Logging out

When you logged out, you just remove this token item from your local storage.

Deal closed.

But what happens if the next time you hop on the system, you are already logged in without first going through the login screen. This is a security concern.

Until you've removed the token from Local Storage, the application always assume that you're logged in - even if the token might already be expired - there can be sensitive data displayed.

A better way is to force the user to login whenever the current tab or browser window closes. If you're using local storage, you have to manage the expiration yourself or manually remove it.

A better solution for our use case is to switch to Session Storage, which will clear the item automatically whenever you close the tab or window. This is more secure.

Replacing LocalStorage by SessionStorage

Now assume you've directly called and used the localStorage method throughout your codes. If you want to replace it by the sessionStorage one, you need to go everywhere in your codes where you've called the method to change it. And of course test everything again.

Even if you have Unit Tests as safety net, you are not following the Don't Repeat Yourself (DRY) principle.

Abstraction

So in the example above in Angular, I have a StorageService class that deals with the storage capability and leave the implementation to the third party library.

If tomorrow, instead of using Session Storage, I want something more flexible such as Redis, I only need to modify the methods in this class.

The one thing I need to make sure though, is to have the same method signature - unless of course there is a reason to make those modifications.