Blog

Front End Development topics with a touch of humor

Objects

Objectify your code

September 27, 2020


In the beginning, there was only spaghetti.

Imagine it... lines and lines of spaghetti code, green digits flowing down on black, for ever and ever, to the ends of the universe. Patches of local order did exist, tiny swirling permutations of fractal beauty and logic in the roiling mass of inchoate chaos.

We called this BASIC.

Enter Object-Oriented Programming

I'm exaggerating a little for effect, of course. It's not true that there was no order in programming before Object-Oriented Programming (OOP). There was always order of a sort, since the time Mr. Babbage and Ms. Lovelace began scribing their wondrous cards. But for my money, OOP is an intuitive way to collect and order code.

But what is OOP? What are Objects? Let's start with some examples.

Ahoy matey--class Pirate

Say we were writing a program that involved a variety of pirates. Each pirate would be an individual, with differing names, genders, skills, characteristic sayings, and teeth. They could never be represented by the same code, any more than an individual person could be represented by the same desciption as his neighbor.

Yet they would have similarities, and even their differences could be grouped according to categories.

For example, while Pete and Mika and Valeria all have different names, they do have names.

        name: Pete
        name: Mika
        name: Valeria
        

While they have different skills, they do have skills.

        skill: piracy
        skill: squeezing into small spaces
        skill: extra-loud shout
        

From spaghetti comes order. Add some curly braces, and we're almost there.

        {name: Pete, skill: piracy}
        {name: Mika, skill: squeezing into small spaces}
        {name: Valeria, skill: extra-loud shout}
        

We see the beginnings of a pattern, a way to order the things that make up a pirate. This is a part of how we humans process the world--we see a great slobbery Mastiff and a scampering, yipping Chihuahua and we think, dog, despite their incredible differences. We see a cute little bonsai and a towering redwood and think, tree.

        {name: bonsai, size: very tiny, location: humidified greenhouse}
        {name: redwood, size: ginormous, location: California forest}
        

We can define such patterns or object templates using the keyword, class. This is how we'd write it in JavaScript:

        class Pirate {
            constructor(name, age, gender, teeth, skill, motto) {
                this.name = name;
                this.age = age;
                this.gender = gender;
                this.teeth = teeth;
                this.skill = skill;
                this.motto = motto
            }
        }
        

Think of it as a blueprint. Pirates have these qualities. But Pirate is not a pirate--it's just a plan for one. It doesn't exist in the world. It can't sail, or loot or pillage, or do anything interesting. For that, we must create an instance using the new keyword.

        const pete = new Pirate("Pete", 52, "male", no, "piracy", "Shiver me timbers!");
        //undefined

        console.log(pete);
        //Pirate {name: "Pete", age: 52, gender: "male", teeth: false, skill: "piracy", …}
        

Here we have created a Pirate, using the class structure, in the first assignment. When we log out the variable (pete), we see that he has been brought into existence! Let's make another one!

        const valeria = new Pirate("Valeria", 35, "female", true, "extra-loud shout", "Swab the decks, matey!");
        //undefined

        console.log(valeria)
        //Pirate {name: "Valeria", age: 35, gender: "female", teeth: true, skill: "extra-loud shout", …}
        

Now pete has a friend, valeria! Another Pirate, but with her own unique qualities.

Adding a method to an object

To refresh, in case the cannonball went right over your bandana-wrapped head, we have just made our own objects, using a class Pirate. Each individual pirate is an object that was created using the constructor function. Each pirate is an instance of the class Pirate. When we created the pirate, we gave him his particular traits with with the arguments in the parentheses.

But so far, it's just a list of qualities. While this has many uses, it's static. We can also give functions to our objects.

What is a function that every pirate has? Swimming, you say? Nay, friend! Many pirates could not swim--they were careful not to fall off that rigging. Swabbing? No, they saved that for the noobs. Swordplay? I think not--what about those who specialized in spiked clubs or scary-looking knives? No, what all pirates can do--as we all know--is say, "yo ho ho!"

        class Pirate {
            constructor(name, age, gender, teeth, skill, motto) {
                this.name = name;
                this.age = age;
                this.gender = gender;
                this.teeth = teeth;
                this.skill = skill;
                this.motto = motto
            }
            yoho() {
                console.log("yo ho ho");
            }
        } 
        

Everything, you'll notice, is the same, except that after the constructor function is a new function, yoho(). Being attached to an object, this type of function is referred to as a method. Being part of the class, this means that all members can use it. Thus:

        pete.yoho();
        //yo ho ho

        valerian.yoho();
        //yo ho ho
        

And if we made a new pirate:

        const mika = new Pirate("Mika", 16, yes, "squeezing into small spaces", "I didn't do it, I swear!");
        mika.yoho();
        //yo ho ho
        

He comes with this ability, too.

Foundational

Objects are foundational to JavaScript. Even though all the periods may look forbidding at first, it is a huge advance over many lines of spaghetti code, held together merely by position and line number and GOTO statements. Objects impose order on programs, which makes it more useful to use. Eventually you will get very comfortable typing the dots, maybe even chaining four or five in a row to get where you need, to access methods and properties of functions. Simply by knowing something is an object, you will be able to guess much of what it does and how it does it, and half the battle will be won.

Image by Jae Rue from Pixabay