Why Programming to Interfaces?

Why Programming to Interfaces?

If you dealt with design principles or patterns, you're highly likely to encounter a common phrase that says programming to interfaces, not implementation. In this post, I will try to make you understand what this phrase is about and how you can take advantage of using interfaces.

Developing complex software might take a long time to implement system functionality. If you design software without concerning the changes that may be demanded by your customer in the future, it's possible that applying these changes takes more time than the time you spent on developing the software. So, while progressing on the development of the software, it's better to follow some principles to make the software more flexible and maintainable. One of these design principles is "Programming to interfaces, not implementation".

What is Interface?

Interfaces are created for full abstraction and the class that implements an interface should implement all methods that reside in the interface. Interfaces don't care how the methods are implemented.

I'm not going into details about interfaces in order not to wander from the main purpose of the post.

Implementation

Think of you're developing a lock system. One day your executives tell you that they want you to add iris recognition in addition to current recognition methods.

Let's see what happens if you didn't follow the principle.

public class FingerprintRecognition {

    public boolean isRecognized() {
        ...
    }
}

public class ProtectedSystem {

    FingerprintRecognition fr;

    public void unlock() {
        if (fr.isRecognized()) {
            ...
        }
    }
}

In this implementation, adding new functionality causes changes in some parts of the code in addition to adding a new class for iris recognition.

What happens if you follow the principle?

public interface IRecognition {

    boolean isRecognized();
}

public class FingerprintRecognition implements IRecognition {

    ...

    public boolean isRecognized() {
        ...
    }
}

public class IrisRecognition implements IRecognition {

    ...

    public boolean isRecognized() {
        ...
    }
}

public class ProtectedSystem {

    IRecognition r;

    public void setRecognition(IReconition r) {
        this.r = r;
    }

    public void open() {
        if (r.isRecognized()) {
            ...
        }
    }
}

In after days, if another recognition method is added to the system, there is no need to change anything in ProtectedSystem class since we've used an interface as a recognition type. The only thing you need to do is adding a new class for the new recognition method. So, it increases the maintainability of the software you develop.

Finishing

This is my first experience in writing a blog post. Thank you for reading it and I hope you found it informative.