OBJECT ORIENTED PROGRAMMING CONCEPTS SIMPLIFIED!

Anupsajjan
Analytics Vidhya
Published in
11 min readAug 2, 2020
A class is like a blueprint, which describes the properties. And the object is a live form of blueprint.

Object-oriented programming, the most confusing topic among beginners! But it has a very high significance of importance when it comes to a cleaner way of programming. You are here expecting something simple and easy way to get started with basic of oop’s, right? Fantastic! You are in a right place, I will try covering this topic with a lot of real-world examples and analogy so that you can always compare the concept with these analogies to grasp the concept completely! And I assure you that these concepts will fit right away in your brain forever! So onboard this vehicle of OOPS and let's get started!

There are four major oop’s concepts, as you may have already overcome, those are -

1.ENCAPSULATION
2. ABSTRACTION
3. INHERITANCE
4. POLYMORPHISM

But let’s not start with all these jargon😀, let’s start building these concepts one by one by knowing why we need them in the first hand!🧐
So we all use a switchboard, right? (You might wonder, how is this related to oop’s? ). Let’s see . . .

switchboard with no interface.

Let’s say you lived in a world where switchboards looked like this, having all connection wires available, but no buttons to interact!. How easy is it to switch on and off your fan?

You might look at the switchboard and separate out the wires that are related to fan and those related to the bulb and so on, and then you can connect fan wires somehow and finally switch on the fan!🥱

A bit hard right? You can do some learning to understand how these connections work and switch on and off your fan whenever required!. So do we say that this implementation is wrong?. No ! This however works and does its job, but it’s a bit hard for someone to use it directly(and very unsafe too ! what if you connect two fan wire and one bulb wire by mistake 😐).

Let’s consider that this is the code you used to switch on and off your appliances. This is just a pseudo-code, just understand the logic!

What can you observe in the above code? You have an appliance and it has 3 wires to connect. For each appliance, you create 3 variables to represent the wires, and those 2 functions, which connect and toggle the switch respectively are used.
Just think🤔, what if you had another appliance, and you want to use it?
So, to the above code, you will add 3 more variables to represent wires and then call those 2 functions to switch on and off the appliance.

What if you have 100 more appliances and all having connection to this switchboard? 🥺🥺. You have to create 3 variables for each of the appliances and call those 2 methods! Just think, how much code repetition you will have to do!!! This can cause serious code maintainability issues in large scale projects!

help those, who write such code!

According to the DRY (Don’t repeat yourself) principle, you should always strive to avoid redundancy in your code! Let’s solve this problem. But how to start?
Let’s see, what’s repetitive in our code.

wire1_red = somevalue
wire1_brown = somevalue
wire1_white = somevalue

If we see carefully, all this repetitive code is related to each appliance. So why not combine all of these into one single entity and provide a simple interface to interact?

So here is our beloved switchboard! What change do you see compared to the previous switchboard?. Each appliance-related connection wires are now grouped into one single entity called a switch, which has a function inbuilt to make the connection active or inactive. And what else do you observe🤔? You are no longer interacting with those dangerous electric wires directly to use your appliance.

This is what the whole idea of encapsulation is!
Encapsulation: enclose (something) in or as if in a capsule.

According to encapsulation-

  1. We need to pack all related fields(all 3 wire variables) and functionality(method for toggling the switch) into a single entity. [ To relate with our example- All the wires were packed and connected internally within a switch and presented the user with a clean interface.].
Encapsulation without private fields

Here you can see that all fields and methods related to the appliance are put inside a class.

NOTE: This section is for beginners who don’t know what class is. Please skip this part if you already know about it.Class is similar to a blueprint, which contains related fields and functions to implement a certain behavior.Let’s say to implement car behavior, you can create a class Car and it can have certain properties like 
1. speed,
2. mileage,
and some functions like
1. def moveCar()
2. def applyBreak() and so on.
But this is not a car yet! This is just a blueprint. To bring a car alive we have to create an object out of the blueprint.
In most of the languages you can create an object like this:
myNewCar = Car()So the variable myNewCar is an actual car now! You can access its properties or call its methods now. For ex:$print(myNewCar.mileage)
$myNewCar.applyBreak()

2. Only expose those fields and methods to the user which are necessary. [The wires were unnecessary for the user to use the appliance(and insecure too!). Hence try hiding those wires from user].

Encapsulation with private fields and methods

In the above code, you can notice that the class fields are now made private using double underscores. It means that the field is for “internal use only”(private to the class) and cannot be accessed from outside the class.

Here you can draw three important inferences:

1. “Fields are made private”, hence providing better security as data fields of the class will not be modified from outside methods!

2. “Some class methods are made private”. Here connectWires method is made private, as it's unnecessary to the user to know or modify how wires are connected(what if you connected wrong wires and resulted in a short circuit 😂, so never give access to user or client which he is not supposed to access).

3. This whole idea of encapsulating related fields and restricting access to some fields by making them private to the class, puts the ‘state of the class’ in the hands of the methods it exposes(public methods), hence the object always stays in control and becomes its own master!

Now can you think what the code might look like if you have 100 appliances connected to switchboard?

It looks so simple, right? Yes it is 😀

Hence these are the advantage that encapsulation provides:

  1. Reusability 🤨(We have seen how the code duplication was overcome by using class).
  2. Maintainability😮 (As the code is much cleaner now, suppose even if we wanted to change the number of wires a switch uses, we can do that change easily in the class and that won't affect any of the user code!)
  3. Data hiding 🙆‍♂️(We saw how to make certain fields as private to enhance the security of the application. Object always stays consistent until its state is in the hands of the methods it exposes!)
Image source: https://tenor.com/

Well, that was a detailed explanation! Hope it was clear 😊! As you now have an overview of what OOP is, it will be easy to cover the remaining topics!
Now take a break, have a walk around🚶‍‍🚶‍♀️, and then let's continue with the next concept!

Now as you mastered encapsulation 😉, you gained confidence and tried to build a video streaming app like NETFLIX🎥!. Initially, you made an app that is available on IOS, Android, and web. On all 3 platforms, you are able to provide video streaming of a maximum of 480p quality for now with no download option, and you plan to improve the quality in the future. Right now you made a class VideoPlayer based on your learning, which encapsulates all related fields. As shown below, this is the current implementation of the VideoPlayer class 🎬.

As you have a lot bigger codebase with hundreds of files, you separated the code for each platform (android, IOS, and web) into separate files, to maintain a clean structure and avoid confusion. As shown below, code for web, android, and IOS is the same right now. All are creating an object of the VideoPlayer class and using the play, pause... methods.

So till here, everything is looking good! 😊. Now you are getting famous, hence you think of introducing new features —
1. Support 1080p streaming.
2. Support video download options.
3. Don't allow users to watch Video on Web, after showing a short intro of the video, notify them to download the app to continue watching.

But you could only add the 1st two features in android due to technical issues, hence IOS users must wait :(

I will pause for a moment. Can you meanwhile scroll through the above code and think 💭, what changes you need to do, to support these new features on Android?🤔

One possible approach would be is to add separate methods, specific to android, and web in VideoPlayer class. All methods have been modified to support each platform separately.

By seeing the above code, you can observe that old methods have been renamed to support each platform separately in the VideoPlayer class, and hence each IOS, web, and Android should modify their code to adapt to this new change.

New android specific code looks like this now -

You can observe in the above-shown code that we needed 2 changes, to modify or add some features in our system because we were using those 2 methods in only 2 places. But in reality android handler will not be this small, it can be a very big file with thousand lines of code or having 10s of different files having a large amount of code😳 where these 2 functions might be referenced multiple times. In such a case, just adding this new feature would result in replacing the function names wherever they are used. This could add to the maintainability issue and headache with confusion for the developer to modify the code.

As shown below, there is the same effect on IOS, and Web code for this new feature. Hence imagine, what would be the real scenario in big applications!

So what is the solution?

How about having a class, which has these methods like playVideo(), downloadVideo(), pauseVideo() . . . and if you call them from either IOS or android or web, they work as if they know what to do regarding a specific platform. For android, playVideo will play 1080p and for others, it will get 480p and so on.

To implement this, you can create someone, who puts some restrictions and says that, anyone who wants to have the videoPlayer functionality, must implement these methods compulsorily. Such a class that defines the rules to implement videoPlayer is called an abstract class. Abstract classes have certain methods unimplemented and just defines the declaration, and it also can have some methods already implemented too. Let's look at a sample abstract class that puts this restriction.

The above class has some of these methods, like playVideo, downloadVideo, and pause_play_Video. They are not implemented and are left empty for those who want to implement them. It’s like, if you want to get VideoPlayer features then you must implement these methods compulsorily. For ex: Govt says, if you want to sell a car, then that car must have Horn, indicators, air-bags etc, otherwise you won’t be allowed to sell the car. Hence you either create a car that implements all these features or you don't create a car at all!

So we can have 3 separate classes each for IOS, web, and android, and each of them will implement these above-mentioned methods as per their requirements!. Below is the implementation.

Here you can observe that all 3 classes have been written separately and each of them implemented these 3 abstract methods as per their requirement!

If any class implementing abstract class methods, misses some methods to implement then an error will be thrown. Hence programmer will always be aware that, to implement some functionality, this is the interface that I have to follow and these methods must be implemented to achieve that functionality!

So can you think what the platform-specific handler code will look like?

Yes! you can observe that all handlers (only 2 are shown above) now use the same method names (playVideo instead of playVideoIOS, playVideoWEB). Ios handler will instantiate VideoPlayerIOS class, web, and android handlers will instantiate their own respective class. And all these classes implement the abstract methods, hence all have same names.

Are you seeing that big advantage? If not, think what changes are needed for IOS to support 1080p streaming and video download option enabled?

YES. You are right 😃, only changing the implementation of videoPlayerIOS class methods, we can achieve this addition of a new feature, and nothing else need to be changed anywhere! Just scroll above and hover over the codes, you will understand this big difference!

Did you just see, how a better-designed software makes the whole application easy to maintain and reduce the complexity and overhead of managing code?

This is the fair idea of what ABSTRACTION is! Abstraction helps to hide the complexity. Encapsulation promotes hiding data members, and abstraction promotes hiding methods.

MAJOR BENEFITS OF ABSTRACTION ARE:🦝

  1. It separates the method signature from its implementation.
  2. For the users, it keeps them from getting exposed to anything other than the method signatures they need to know, reducing complexity.
  3. Helps avoid repetitive code
  4. Gives flexibility to programmers to change the implementation of the abstract behavior.

Abstraction is a natural extension of Encapsulation . Encapsulation recommends that you create entities/objects which contain closely related fields and functionality/methods. Abstraction further recommends that the entities expose only their method signatures to external users who shouldn’t need to worry about the underlying implementation.

We will meet again in the next series, where I will cover Inheritance and polymorphism!

Curious how I learned this?

This is a part of #IBELIEVEINDOING CHALLENGE July Edition by CRIO.DO.
I discovered this recently as an Instagram post and I find myself lucky to have found this! The method of learning by doing is really useful as the knowledge persists for a longer time compared to traditional learning.

I recommend you to have a look at their amazing work at https://crio.do/😀

Hope you found this article helpful 😃! If so do give a clap 👏. (You can give a lot of claps too 😉).

Signing off! See you soon.👋

--

--