Interfaces were built to create public API and minimize client code to access fungible objects. I do use interfaces heavily for all the purposes you probably are familiar with. Today I would like to introduce a new and opinionated way I am using interfaces which helps me to create consistent structures of similar classes.
The purpose of the new way is just to keep a consistent structures for classes of similar purpose. The idea came to me when I get to develop an Android Application for a client a few years back.
That was my first development. When I created many activities and fragments, I found out that I have been doing same tasks and some times separating those tasks into functional parts with closely “similar function names”. When I needed to make a change I would try to look for a specific function that may encapsulate the related task. At that point the idea came to me, I could find things faster if all the classes had same name for similar functions.
So, I created two interfaces, an ActivityInterface and a FragmentInterface, and the purpose was not to expose any API at all.
A few functions the ActivityInterface had:
public void processIntents(); // Write all the incoming intent processing logic here public void initUIComponents(); // bind class objects to UI elements here public void registerEvents(); //register events here // and some more functions
Benefits of such an interface:
- You have a consistent structure generated automatically for an Activity
- You know where you would find a specific task faster
- You can decide where to put a new thing faster
- You can have a clear view how your class works.
After that android development, I have been actively using “Structure Interfaces” in my Java projects, too. I would not say these interfaces structures objects because these are not meant to create any API.
I just came across a pattern which is exactly the same as what I did discover myself. It’s called “Template Method Pattern” which is implemented by abstract class. It has more features as you have different access modifiers, fields, and also concrete methods. Have a look at Template method pattern (November 2, 2016)