Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Interfaces Are Cool!

DZone's Guide to

Interfaces Are Cool!

Creating interfaces is easy and can make your life easier- check out a few use cases of interfaces and where they're most effective.

· DevOps Zone ·
Free Resource

DevOps involves integrating development, testing, deployment and release cycles into a collaborative process. Learn more about the 4 steps to an effective DevSecOps infrastructure.

A while back, I blogged about learning about interfaces as I didn't really understand the value of them. I do now.

I created an application that used interfaces so I could learn how it worked. I created a Logger Interface and created multiple classes that implemented that interface so I could swap out the different implementations easily. I created a SQL Logger and a File Logger and my code could be written and be completely unaware of which implementation it was using.

This application uses SQL Azure, so I have a monthly bill to pay. Wouldn't it be cool if I could reduce this bill? How about using the cheaper table storage instead?

Easy!

Create a new class that implements my interface, and all I need to do is write the three methods defined in my interface so I can swap from SQL Azure to table storage.

Another benefit to interfaces is testing. Say I have an interface called inotification for sending notifications; I can have several implementations of this email, Twitter, Slack, etc.

None of these implementations should be used in unit tests, as you don't want a tweet being sent every time you run your tests. Why not create an implementation that simply returns something for each method call and doesn't actually do anything. I can then run my tests with my fake implementation which tests my code logic but not the implementation I have chosen (this can be tested later on with integration tests or user testing if required).

This is pretty much all I have to say about interfaces. I just like how I can swap different implementations.

It does take a bit of work to get the interface set up. I found that when writing the second implementation the interface would need to change slightly, mostly as it was badly designed to begin with. I think for beginners there may be some value to writing multiple implementations of an interface so you can be sure your interface is good, however I am sure with experience this will not be required.

Read the 4-part DevOps testing eBook to learn how to detect problems earlier in your DevOps testing processes.

Topics:
devops ,interfaces ,testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}