Consider interface segregation

Abstraction is great and using interface is one way to achieve dependency inversion. But we need to use interfaces properly.

During the development, we got a request to observe username text changes. Whenever the user types something, we need to get this data, validate and do something.

At first glance, it seems very easy to implement this. Since we know dependency inversion and we rely on the abstraction, all we need to do was adding a new method to LoginListener.

We’ve added this new method and implemented in LoginActivity. Everything worked properly. We achieved exactly what we wanted.

But later on, we needed to use LoginFragment somewhere else. That’s very good because we can reuse it. All thanks to principles that we followed.

But there was a problem which the new class didn’t need the last method we added recently. It is completely useless and redundant.

No methods should be forced to implement.

You can say that, “well leave it empty” but think about a lot of methods and you leave them empty. It is ugly and it could mislead other developers. You always need to put a comment which says “hello we don’t use it”.

Solution is :

Split the interface.

We basically created another interface which is totally optional. It is good practice to don’t force classes to implement every interface if they are optional.

Whoever needs this data, can implement this interface and use it. LoginActivity in our example implemented both and used them.

We didn’t force AccountActivity to implement this method anymore.

Like what you read? Give Orhan Obut a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.