#100Devs - Javascript OOP Part 2 (cohort 2)

Class 31 of our Free Web Dev Bootcamp for folx affected by the pandemic. Join live T/Th 6:30pm ET leonnoel.com/twitch and ask questions here: leonnoel.com/discord

Skip to first slide
Slide 1 of 124

 

Javascript - OOP Part 2

Leon Noel

#100Devs

Cut class 'cause it wasn't 'bout cash
School wasn't no fun, couldn't bring my gun

Know a change gon' come like Obama 'nem say
But they shooting everyday 'round my mama 'nem way


Slide 2 of 124

Agenda


Slide 3 of 124

Questions

About last class or life


Slide 4 of 124

Checking In

Like and Retweet the Tweet

!checkin


Slide 5 of 124

!newsletter


Slide 6 of 124

Networking - Next Week


Slide 7 of 124

Client Deadline: March 5th


Slide 8 of 124

Client Alternatives


Slide 9 of 124

Grassroots Volunteer*


Slide 10 of 124

Free Software / Open Source

https://www.firsttimersonly.com/


Slide 11 of 124

GIT BOWL

SUNDAY
1:00pm EST


Slide 12 of 124

LINK


Slide 13 of 124

Never Miss The Stream Team


Slide 14 of 124

Welcome, verolafox

Friday @ 11:00am ET! 


Slide 15 of 124

Objects

What are objects?


Slide 16 of 124

USE
UNDERSTAND
BUILD


Slide 17 of 124

Finna Make Sum Nerds Angry


Slide 18 of 124

Objects


Slide 19 of 124

Think of a physical object

What are it's attributes and behaviors? 


Slide 20 of 124

How about a stopwatch

What are its properties and methods? 


Slide 21 of 124

Stopwatch Object

let stopwatch = {}

stopwatch.currentTime = 12

stopwatch.tellTime = function(time){
  console.log(`The current time is ${time}.`)
}

stopwatch.tellTime(stopwatch.currentTime)

Notation?


Slide 22 of 124

Objects

What if we want to make

a lot of objects?

How much money you got? How many problems you got? How many people done doubted you? Left you out to rot?


Slide 23 of 124

Car Factory?

Constructors then Classes


Slide 24 of 124

Car Factory

Constructor

function MakeCar(carMake,carModel,carColor,numOfDoors){
  this.make = carMake
  this.model = carModel
  this.color = carColor
  this.doors = numOfDoors
  this.honk = function(){
    alert('BEEP BEEP FUCKER')
  }
  this.lock = function(){
    alert(`Locked ${this.doors} doors!`)
  }
}

let hondaCivic = new MakeCar('Honda','Civic','Silver', 4)

let teslaRoadster = new MakeCar('Tesla','Roadster', 'Red', 2)

Slide 25 of 124

Car Factory

Look Ma! New syntax!

class MakeCar{
  constructor(carMake,carModel,carColor,numOfDoors){
    this.make = carMake
    this.model = carModel
    this.color = carColor
    this.doors = numOfDoors
  }
  honk(){
    alert('BEEP BEEP FUCKER')
  }
  lock(){
    alert(`Locked ${this.doors} doors!`)
  }
}

let hondaCivic = new MakeCar('Honda','Civic','Silver', 4)

let teslaRoadster = new MakeCar('Tesla','Roadster', 'Red', 2)

Classes are like templates for objects!


Slide 26 of 124

BUT WHY?

Why Use Objects?
Why Would We Need A Factory?


Slide 27 of 124

What if there was a system, a paradigm, a set of rules, an agreed upon way to structure our code that:

 

Made it easier to add new stuff

Made it easier to read through what was already coded

And made it so you were not afraid to make changes

 

Music & Light Warning - Next Slide


Slide 28 of 124

OOP BABY


Slide 29 of 124

OBJECT ORIENTED PROGRAMING 


Slide 30 of 124

Let's See Some Code


Slide 31 of 124
let hourlyRate = 250
let hours = 160
let taxRate = .35

function calculateProfit(rate, numOfHours, taxes){
  return rate * numOfHours * (1 - taxes)
}

let profit = calculateProfit(hourlyRate, hours, taxRate)

console.log(profit)

Is it easy to add new features and functionality?


Slide 32 of 124
let hourlyRate = 250
let hours = 160
let taxRate = .35

function calculateProfit(rate, numOfHours, taxes){
  return rate * numOfHours * (1 - taxes)
}

function holdForTaxes(profitMade){
  return hourlyRate * hours - profitMade
}

let profit = calculateProfit(hourlyRate, hours, taxRate)

let taxesHeld = holdForTaxes(profit)

console.log(profit)

console.log(taxesHeld)

Slide 33 of 124

Can another developer look at my code and understand what is happening?


Slide 34 of 124
let hourlyRate = 250
let hours = 160
let taxRate = .35

function calculateProfit(rate, numOfHours, taxes){
  return rate * numOfHours * (1 - taxes)
}

function holdForTaxes(profitMade){
  return hourlyRate * hours - profitMade
}

let profit = calculateProfit(hourlyRate, hours, taxRate)

let taxesHeld = holdForTaxes(profit)

console.log(profit)

console.log(taxesHeld)

Slide 35 of 124

Slide 36 of 124
let hourlyRate = 250
let hours = 160
let taxRate = .35

function calculateProfit(rate, numOfHours, taxes){
  return rate * numOfHours * (1 - taxes)
}

let profit = calculateProfit(hourlyRate, hours, taxRate)

console.log(profit)

Can I make changes without losing sleep at night? 


Slide 37 of 124
let hourlyRate = 250
let hours = 160
let taxRate = .35

function calculateProfit(rate, numOfHours, taxes){
  return rate * numOfHours * (1 - taxes)
}

function holdForTaxes(profitMade){
  return hourlyRate * hours - profitMade
}

let profit = calculateProfit(hourlyRate, hours, taxRate)

let taxesHeld = holdForTaxes(profit)

console.log(profit)

console.log(taxesHeld)

Slide 38 of 124

DATA & FUNCTIONALITY


Slide 39 of 124
let hourlyRate = 250
let hours = 160
let taxRate = .35

DATA


Slide 40 of 124

Functionality

function calculateProfit(rate, numOfHours, taxes){
  return rate * numOfHours * (1 - taxes)
}

Slide 41 of 124

Slide 42 of 124

let seriousBusinessPerson = {
  hourlyRate: 250,
  hours: 160,
  taxRate: .35,
  calculateProfit: function() {
    return this.hourlyRate * this.hours * (1 - this.taxRate)
  }
}

Slide 43 of 124

Is it easy to add new features and functionality?


let seriousBusinessPerson = {
  hourlyRate: 250,
  hours: 160,
  taxRate: .35,
  calculateProfit: function() {
    return this.hourlyRate * this.hours * (1 - this.taxRate)
  }
}

Slide 44 of 124

let seriousBusinessPerson = {
  hourlyRate: 250,
  hours: 160,
  taxRate: .35,
  calculateProfit: function() {
    return this.hourlyRate * this.hours * (1 - this.taxRate)
  }
  calculateTaxesHeld: function(){
    return this.hourlyRate * this.hours - this.calculateProfit()
  }
}

Slide 45 of 124

Can another developer look at my code and understand what is happening?


let seriousBusinessPerson = {
  hourlyRate: 250,
  hours: 160,
  taxRate: .35,
  calculateProfit: function() {
    return this.hourlyRate * this.hours * (1 - this.taxRate)
  }
}

Slide 46 of 124

Can I make changes without losing sleep at night? 


let seriousBusinessPerson = {
  hourlyRate: 250,
  hours: 160,
  taxRate: .40, //changed
  calculateProfit: function() {
    return this.hourlyRate * this.hours * (1 - this.taxRate)
  }
}

Slide 47 of 124

This fusion of data and functionality into one object

Music & Light Warning - Next Slide


Slide 48 of 124

Encapsulation Baby


Slide 49 of 124

Slide 50 of 124

Encapsulation

The process of storing functions (methods) with their associated data (properties) - in one thing (object)*

*Nerds shaking violently


Slide 51 of 124

Is it easy to add new features and functionality?


Slide 52 of 124

Slide 53 of 124

Heats water for espresso and steam for your milk


Slide 54 of 124

Steam wand sucks...

What should the engineers do?


Slide 55 of 124

Do they get rid of the water boiler?

probably not...


Slide 56 of 124

At first, do they even need to think about the water boiler?


Slide 57 of 124

So the water boiling is abstracted?


Slide 58 of 124

Let's look at some code


Slide 59 of 124

function AgencyContractor(hourlyRate, hours, taxRate){
  this.hourlyRate = hourlyRate
  this.hours = hours
  this.taxRate = taxRate
  this.calculateProfit = function() {
    return this.hourlyRate * this.hours * (1 - this.taxRate)
  }
  this.invoiceClient = function(){
    return `Your invoice total is ${this.hourlyRate * this.hours}`
  }
}

let leon = new AgencyContractor(250,160,.35)
console.log( leon.invoiceClient() ) //40000
console.log( leon.hourlyRate ) //250
console.log( leon.calculateProfit() ) //26000

Ut Oh...


Slide 60 of 124
function AgencyContractor(hourlyRate, hours, taxRate){
  this.hours = hours
  this.taxRate = taxRate
  let rate = hourlyRate
  let calculateProfit = function() {
    return rate * this.hours * (1 - this.taxRate)
  }
  this.invoiceClient = function(){
    return `Your invoice total is ${rate * this.hours}`
  }
}

let leon = new AgencyContractor(250,160,.35)
console.log( leon.invoiceClient() ) //40000
console.log( leon.hourlyRate ) //undefined
console.log( leon.calculateProfit() ) 
//Uncaught TypeError: leon.calculateProfit is not a function

Better...

*Nerds shaking violently


Slide 61 of 124

So now my client can still get their invoice, but not see my hourly rate


Slide 62 of 124

Water boiling was hidden from the steam wand

Hourly rate was hidden from the client


Slide 63 of 124

Complex or unnecessary details are hidden


Slide 64 of 124

This enables you to implement things without understanding or even thinking about all the hidden complexity


Slide 65 of 124

Smaller more manageable pieces of code


Slide 66 of 124

Do stuff once

Music & Light Warning - Next Slide


Slide 67 of 124

Abstraction Baby


Slide 68 of 124

Slide 69 of 124

Abstraction

Hide details

and show essentials

SIMPLE, PREDICTABLE, MANAGEABLE


Slide 70 of 124

Let's Start A Farm


Slide 71 of 124
class Animal{
    constructor(name){
        this.name = name
    }
    speak(){
        console.log(`${this._name} makes a sound`)
    }
}

Slide 72 of 124

What if we want a bunch of different animals on the farm?


Slide 73 of 124
class Animal{
    constructor(name){
        this.name = name
    }
    speak(){
        console.log(`${this.name} makes a sound`)
    }
}
class Dog extends Animal{
    constructor(name,breed){
        super(name)
        this.breed = breed
    } 
}

let simba = new Dog('Simba', 'Sheperd')

We can extend animal


Slide 74 of 124

* If you find yourself starting to create a number of objects that have similar features, then creating a generic object type to contain all the shared functionality and inheriting those features in more specialized object types can be convenient and useful. 

*mdn on oop


Slide 75 of 124

We just eliminated a bunch of redundant code

AKA

Music & Light Warning - Next Slide


Slide 76 of 124

Inheritance BABY


Slide 77 of 124

Slide 78 of 124

Inheritance

Make a class from another class for a hierarchy of classes that share a set of properties and methods


Slide 79 of 124

Let's Code

Make A Child Class


Slide 80 of 124

Back To The Farm


Slide 81 of 124

New workers keep renaming animals in our system

 

 


Slide 82 of 124
class Animal{
    constructor(name){
        this.name = name
    }
    speak(){
        console.log(`${this.name} makes a sound`)
    }
}

let simba = new Animal('Simba')

simba.name // "Simba"

simba.name = 'Bob' //nothing happens

simba.name // "Bob"

Slide 83 of 124

What could help here?


Slide 84 of 124
class Animal{
    constructor(name){
        this._name = name
    }
    get name(){
        return this._name
    }
    speak(){
        console.log(`${this._name} makes a sound`)
    }
}

let simba = new Animal('Simba')

simba.name // "Simba"

simba.name = 'Bob'  //nothing happens

Slide 85 of 124

We just rescued a bunch of animals! 

How should we build out our system? 


Slide 86 of 124

Let's Code

Animal System


Slide 87 of 124

We want to do a morning roll call and fortunately Dr. Dolittle works here


Slide 88 of 124

ROLL CALL


Slide 89 of 124
let simba = new Dog('Simba','Shepard')
let machi = new Dog('The Machine','Pitbull')
let salem = new Cat('Salem', 'American Shorthair')

let farm = [simba,machi,salem]

for( a of farm ){
    a.speak()
}

//Simba barks
//Machi barks
//Salem Meows

Slide 90 of 124

Wait A Minute


Slide 91 of 124
for( a of farm ){
    a.speak()
}

//Simba barks
//Machi barks
//Salem Meows

Slide 92 of 124

 Code written to use an interface automatically knows how to work with any number of different objects that provide the interface


Slide 93 of 124

Slide 94 of 124

Sibling descendants of a base class will all have the same interface but varying implementations


Slide 95 of 124

Slide 96 of 124

When you are not sure of the objects type at runtime and the most specific method is called.


Slide 97 of 124

Therefore the behavior of the method called may differ, depending on the objects type at runtime


Slide 98 of 124

Slide 99 of 124
for( a of farm ){
    if(a instanceof Dog){
      console.log('Bark')
	}else if (a instanceof Cat){
      console.log('Meow')         
    }
}

//Simba barks
//Machi barks
//Salem Meows

Disgusting

Why?

 


Slide 100 of 124

Provides a way to perform a single action in different forms.

 

Provides an ability to call the same method on different JavaScript objects.


Slide 101 of 124

Instead of conditionals and switch cases

Music & Light Warning - Next Slide


Slide 102 of 124

POLYMORPHISM BABY


Slide 103 of 124

Slide 104 of 124

The Four Pillars

What if they actually made any sense...


Slide 105 of 124

Encapsulation

The process of storing functions (methods) with their associated data (properties) in one thing (object)


Slide 106 of 124

BUT WHY?


Slide 107 of 124

Made it easier to add new stuff

 

Made it easier to read through what was already coded

 

And made it so you were not afraid to make changes


Slide 108 of 124

Abstraction

Hide details

and show essentials


Slide 109 of 124

BUT WHY?


Slide 110 of 124

Smaller more manageable pieces of code

Helps you to split the complexity your software project into manageable parts


Slide 111 of 124

Make code changes and still sleep at night


Slide 112 of 124

Inheritance

Make a class from another class for a hierarchy of classes that share a set of properties and methods


Slide 113 of 124

BUT WHY?


Slide 114 of 124

Helps you eliminate redundant code


Slide 115 of 124

Polymorphism

 Code written to use an interface automatically knows how to work with any number of different objects that provide the interface


Slide 116 of 124

BUT WHY?


Slide 117 of 124

Helps you avoid if/else and switch cases


Slide 118 of 124

Makes your code more reusable

 


Slide 119 of 124

Supports The

Other Pillars


Slide 120 of 124

Group Work

https://live.remo.co/e/100devs-networking-night-group-0
https://live.remo.co/e/100devs-networking-night-group-0-1
If Remo does not work for you, please jump into one of our

Discord Voice Channels!


Slide 121 of 124

Talk Through OOP


Slide 122 of 124

Right Of Passage

https://live.remo.co/e/100devs-networking-night-group-0
https://live.remo.co/e/100devs-networking-night-group-0-1
If Remo does not work for you, please jump into one of our

Discord Voice Channels!


Slide 123 of 124

Get It To Work 

 

Then:
 

Make it easier to add new stuff

 

Make it easier to read through what was already coded

 

And make it so you are not afraid to make changes


Slide 124 of 124

Homework

 

DO: Please review, play, and break the code we go over tonight.

Get lost in it, come with questions, and ready to review on Thursday.
DO: Get a paid client, Volunteer, or Contribute To Free Software
DO: FINISH Professional Checklist 

Want To Push (Due: Tues. May 5th)?
Do: Codewars Array Ladder (search array problems) - 8kyu, 7kyu, 6kyu, 7kyu, 8kyu