Going from functional programming to Object Orient Programming(OOP) was a mental shift for me. Part of developing understanding was learning the vocabulary. In this blog post series, I will go over the four OOP principles: Encapsulation, Abstraction, Inheritance, and Polymorphism. This blog series is complete, so feel free to jump around:

  1. Abstraction – Current Post
  2. Inheritance
  3. Polymorphism
  4. Encapsulation

Abstraction

Imagine a dog.

Was it a Cerberus, a three headed dog? If you ask a room full of people to imagine a dog, it is highly unlikely that everybody would imagine the same dog, unless you’re at a Yorkshire Terrier convention. People may imagine a Golden Retriever, a Pit Bull, or an Australian Shepherd . Even though the answers are different, we can see that they’re all types of dogs. This is because humans have the innate ability to create abstractions. Here, ‘dog’ is an abstract concept that has certain characteristics. We can identify other dogs by comparing them to this abstract.

We carry this human skill to programming. When we create a class, we’re often creating a blueprint for an object. For example, we could create a Dog class, and then create multiple dog objects.

Class Dog {

    Dog(string breed) {

        this.breed = _breed;

    }

    move() { ...}

    bark() {...}

    eat() {...}

}

Each time we instantiate this Dog class, we must define the ‘breed’ of the dog. Thus, we can create different types of dogs using the same class. This is abstraction.

Conclusion

Why do we use abstraction? Imagine creating a Yorkshire Terrier class with the functions move, bark, and eat. Imagine creating a Australian Shepherd and a Golden Retriever class with the same exact functions. That’s a lot of duplication. Instead of having multiple classes, you can simply have one class. Abstraction is a useful principle to keep in mind because it helps us cut down on duplication. Try to find ways you can practice abstraction in your code.

Share This