Interfaces and Polymorphism – Object Oriented Programming

Introduction

I assume that as you got here on my blog, you have basic knowledge on Object Oriented Programming. You might already understand inheritance, and other principles behind Object Oriented Programming. Let us answer this question. What is the primary purpose of “Interfaces” in Object Oriented Programming?

So, let us discuss about Interfaces. How do you use it? Have you ever wondered on how is it being used? What’s the actual use of an interface?

Bad Code:

<?php
interface SomeInterface {
    public function methodA();
    public function methodB();
}

class SomeClass implements SomeInterface {
    // Will not work!.
}

Good Code:

<?php
interface SomeInterface {
    public function methodA();
    public function methodB();
}

class SomeClass implements SomeInterface {
    public function methodA() {
        // Implementation here
    }
    public function methodB() {
        // Implementation here
    }
}

We already know that when you implement an interface, the implementor class is required to implement the defined methods from the interface that the implementor class implements. So, what’s the good use for that?

Hello Polymorphism

Remember this topic of yours? Your professor in college might be discussing this topic, and you as a student feels sleepy and ask in your mind “what the heck is that polymorphism thing!?”.

I won’t blame you. You might be thinking that polymorphism is kind of useless, and in fact, you could develop a fully working project without even attempting of using it, and most regular developers I assume don’t even bother thinking of using it. (through yummy and delicious spaghetti code of yours, or any other anti-patterns you have in your hand, of course, who cares, it simply works though).

Multiple Implementation – The heart of Polymorphism

Let us visualize a very simple login system that connects to more than one endpoints: DB Login and API Login.

DB Login checks validity of user credential across a certain database, and API Login checks validity of user credential across another service.

To be continued…

Leave a Reply

Your email address will not be published. Required fields are marked *