DEV Community

loading...
Cover image for Do I really understand classes and Objects? But why should I use it?πŸ€”

Do I really understand classes and Objects? But why should I use it?πŸ€”

procode profile image ProCode ・5 min read

If you like my educational blogs Consider buying me a coffee😊 or support me in patreon so that I can continue spreading education for free.

Does understanding a concept to the core gives you a really satisfactory feeling? Well get ready for some of that now. In this blog I will try to dig in and understand the idea of Classes and Objects, one of the core fundamentals Object Oriented Programming.

//   Let's Start!

Before talking about the solution uselessly, let's build up a problem first. Why do we need Class and Objects? Let's think of a problem where you and I have to build a user management system for an application, where we keep track of our users and their properties and behaviours that are allowed within our application. For example the user's name , ID and other application specific information. So what do you think we should use to keep track of our user?
To actually see the hurdles with using other methods we should use them ourselves shortly. Okay let's be real,you are only reading this so not "we", I should use them shortly, and I'm ready to be the lab-rat here.

The Problem

My Company wants me to build an user management system, where 10 to 100 user information is pulled from database and I am told to find a way to work with this data according to user's interaction with our application. The user's information includes:

  • User's ID
  • User's Name
  • User's Clicks Count(Updates Accordingly)

Using Arrraysto solve the problem?(Oh No!😣)

Okay! Now let's pretend I don't know what Objects and classes are and the only logical way I see to solve the problem(Provided you don't choose to manually declare 400 variables) is to use arrays. Let's see how we do that.

let userId = [1 , 2 , 3,...,100];
let userName = ["User1", "User2",.., "User100"];
//Pretty Random Click Counts
let userClicks = [6 , 23  ,..., 72];

//Function to update Click Counts
function clickCount(uName, uId)
{
  //Updating click of user at index uId
  userClicks[uId] += 1;
  console.log(uName + " Clicked " + userClicks[uId] + " times.");
}

/*
Now let's say a user clicks 
and we know userId of this
user so we call the 
function clickCount with this information.
*/
let knownId = 2;

clickCount(userName[knownId], knownId);

Phew! Did you see the problem with this? First of all, I had to create different arrays for storing user information, I am also assuming that at the same index in all the arrays the information belongs to the same user. Also there's no way to bind all the user information and function together and tell the computer this belongs to a specific user.

There could obviously be other solutions like by using Structures, enums. But we'll see how we can implement object and classes here! But before doing that first we need to be aware of what are they and how to use them and in the process, we'll write a solution for this problem.

What are classes and objects?

A class is a way to bind all the data describing an unique entity and it's associated functions together
Now what does that mean? Remember in the problem above we had some data about the user and a function along with it. A class is just a way to bind these user data and functions together and tell the computer that this belong to a specific user. These data and functions are the properties and behaviour of a particular user with in the application.

In layman's terms

House BluePrint
Have you seen those bluePrints of houses? How many house do you think you can create from a single house plan? A lot right? A class is like a blue print. You can create Objects from it, as many as you want.so:

  • Class == House Plan
  • Object == The House

So how do we implement a class for the problem we are trying to solve? Let's see:

class user
{
    constructor (uId, uName)
    {
        this.userName   = uName;
        this.userId     = uId;
        this.userClicks = 0;
    }

    CountClicks()
    {
        this.userClicks += 1;
    }   
}

Easy , right? Now we can create as many users as we want from this user class.
The variables inside the constructor function are known as member variables/data members and the function is called member function/method, they are specific to each object. A particular user(object) is called an Instance of the class. Now how do we create object of these class? We'll see but before that are you confused about the this keyword in the code? As I only intend to talk about the idea of Objects and Classes in this blog and not much about the coding part, but you can refer to this tweet in my account, also I am planning to write a blog on the this keyword and Static methods, so stay tuned😁.


The Constructor function is used to initialise every object and give it, it's unique set of values. And it's necessary while writing classes. When we make a new object with the help of new keyword, the constructor function is automatically called.

Creating objects

class user
{
  constructor(uId, uName)
  {
    this.userName = uName;
    this.userId = uId;
    this.userClicks = 0;
  }

  countClicks()
  {
    this.userClicks += 1;
    console.log(this.userName + " clicked " + this.userClicks + " time.");
  }
}

//Creating Objects
let user1 = new user(1, "Tom");
let user2 = new user(2, "Jerry");
let user3 = new user(3, "ProCode");

//Using methods
user1.countClicks();
user2.countClicks();
user3.countClicks();

Smooth! Right? Always remember DRY! while coding,
DRY = Don't Repeat Yourself

So what do you think an object is?
An object is an unique entity which has it's properties and behaviours defined within the class. Ah leave it, you can make up your own definition!

Conclusion

  • The Class is the base structure of an object. It's like the manufacturing system in a factory, once created many similar products (object) can be created from it.

And did you realise we have already created a solution for our problem?😁
To check your understanding about the concept you can do this exercise:
Define a class car which have three member variables of your choice and two member functions speed() and break() which atleast prints "speeding" and "applying break" respectively.

Finally, it was not much of a coding tutorial, I wrote this to understand the idea of Objects and Classes more strongly.I hope you'll like it.

And if you do, please share!

Who am I?

I am a self-taught coder, Coding my life.
If you like my educational blogs Consider buying me a coffee😊 or support me in patreon so that I can continue spreading education for free.

Discussion (0)

pic
Editor guide