RebootJeff.com

Try. Learn. Repeat.

Welcome to RebootJeff.com

I’m a JavaScripter writing about web software development. I write about other interests too.

Tennis, cars, videography, music, composition of the universe, the aesthetics of everything, and Batman tend to be on my mind as well.

Navigation

Find me on

Queues & Stacks From Scratch With JS Patterns

- - posted in JavaScript, data structures, design patterns, technical posts | Comments

In my previous post, I began my quest to help noob programmers by introducing the basic computer science topic of data structures. I provided a quick overview of queues and stacks, so please read all about ‘em before engaging your eyeballs with this blog post. This time around, we’ll check out four different patterns for creating classes in JavaScript while learning how to build stacks and queues from scratch.

Before we go, I should warn you that I’m going to focus on describing the class instantiation patterns rather than thoroughly explaining the implementation of the data structures. Just keep in mind that we are going to explore building stacks and queues with objects rather than arrays. More specifically, we will use a property called storage that is an object, not an array. Now I know what you’re pondering.

Why?

That is a beautiful question. Please ask it all the time (but please don’t troll me by leaving “Why?” in the comments section of this blog post). In this case, the answer to “Why?” may be a tad disatisfying. The answer is “because we can”, but don’t worry! It’ll be fun. Now, let’s start instantiating some motherhugging classes.

1. Functional Instantiation

The simplest way to implement classes is with a “maker” function that creates a new instance of the class and returns that instance so it can be stored as a variable. The new instance is just like any other JavaScript object. It can have properties that store relevant information about the instance (e.g., with a Car class, instances might have a price property). It can also have properties that store functions. These functions serve as methods that are tightly associated with the instance.

Characteristics

  • Creates new copies of the same functions when creating a new instance of the same class. This lack of reuse takes up more memory and can leave an unsavory taste in some programmers’ mouths.
  • There is no quick way to modify all instances of the class after they’ve been created. This will become more clear after examining the other instantiation tactics.
  • Private variables can be created/used by harnessing closure scope superpowers, but I won’t get into that today.
  • If you understand JavaScript functions and objects, then you can understand classes implemented via functional instantiation (other instantiation techniques require knowledge of this and/or new).
  • Could be used to create callable instances (i.e., the class could return a function rather than an object filled with properties).

Example code:

Stack from scratch (functional instantiation)
var makeStack = function(comment){
  // Provide private variables in closure scope
  var size = 0;
  var storage = {};
  var instance = {};  // Start building an instance of Stack class

  // Add extra properties for the hell of it
  instance.annotation = comment;

  // Add functions to the instance to serve as methods
  // (they will provide an interface to the stack's storage)
  instance.push = function(data){
    storage[size] = data;
    size++;
  };

  instance.pop = function(){
    if(size > 0){  // Only perform pop actions if the stack has data
      size--;
      var data = storage[size];
      delete storage[size];  // Don't forget to delete from storage!
      return data;
    }
  };

  instance.size = function(){
    return size;
  };

  return instance;
};

// Create and use an instance of the Stack class
var myStack = makeStack("I'm a stack! Whoa.");
myStack.push(1);              // myStack stores 1
myStack.push('b');            // myStack stores 1 and 'b'
myStack.push(3);              // myStack stores 1, 'b', and 3
console.log(myStack.pop());   // logs 3
console.log(myStack.size());  // logs 2

2. Functional Instantiation w/Shared Methods

By utilizing an object filled with methods, several classes can be created that have the same methods without creating new copies of said methods. The classes will use their own function references to refer to the same set of shared methods. Therefore, using shared methods eats up less memory than functional instantiation without shared methods.

Characteristics

  • Reuses functions (which conserves memory) by getting function references from a utility such as Underscore.js’s _.extend(instance,methods).
  • Retains the same benefits as functional instantiation without shared methods.

Example code:

Queue from scratch (functional instantiation with shared methods)
var makeQueue = function(queueName, comment){

  // You can use object literal notation for `instance` (instead of dot notation),
  // but then we have to use `this` and we lose the privacy of closure scope
  // (e.g., `storage` is no longer private), so this kind of sucks.
  var instance = {
    name: queueName,
    annotation: comment,
    head: 0,
    tail: 0,
    storage: {}
  };

  // The _.extend() function is provided by the Underscore.js library
  _.extend(instance, sharedQueueMethods);

  return instance;
};

// The object below stores methods that could be shared with other classes
var sharedQueueMethods = {
  enqueue: function(data){
    this.storage[this.tail] = data;
    this.tail++;
    // The tail points to the next EMPTY "spot" for data to be stored
    // it does NOT point to the last OCCUPIED "spot" in the storage
  },
  dequeue: function(){
    if(this.head <= this.tail){  // Check the queue's size
      var data = this.storage[this.head];

      // Deleting is even more important for queues than for stacks
      // (memory leaks are a bigger threat for queues)
      delete this.storage[this.head];
      this.head++;
      return data;
    }
  },
  size: function(){
    return this.tail - this.head;
  }
};

// Create and use an instance of the Queue class:
var myCoolQueue = makeQueue("Jeff's Queue",'Hello, world!');
myCoolQueue.enqueue('a');             // myCoolQueue stores 'a'
myCoolQueue.enqueue(2);               // myCoolQueue stores 'a' and 2
myCoolQueue.enqueue('c');             // myCoolQueue stores 'a', 2, and 'c'
console.log(myCoolQueue.dequeue());   // output: 'a'
console.log(myCoolQueue.size());      // output: 2

3. Prototypal Instantiation

The key to prototypal instantiation is the use of Object.create() to utilize shared methods. Unlike functional instantiation with shared methods, there is no need to use an extend() function.

While it’s possible to use a prototype’s functions with Object.create(ExampleClass.prototype);, it’s also possible to (ironically) avoid the word “prototype” altogether by using Object.create(sharedMethods);.

Characteristics

  • Reuses shared functions via Object.create(Example.prototype) or Object.create(objectOfFunctions).
  • Unlike functional instantiation, function references are shared. Each instance of the class does not get its own function references that point to the shared methods. This saves even more memory (although it is a very small improvement).
  • Unlike functional instantiation, there is no way to use closure scope to enforce privacy of variables.
  • Variables are stored on the returned object (aka instance), which means the shared stack methods need to use the keyword this to access the necessary data. It’s not a huge bummer, but if you’re a beginner, then this can be a confusing concept.
  • Can use prototype chains for dynamic method modification and inheritance (subclasses!).

Example code:

Stack from scratch (prototypal instantiation)
var makeStack = function(comment){
  var instance = Object.create(sharedStackMethods);
  instance.annotation = comment;
  instance.size = 0;
  instance.storage = {};

  return instance;
};

var sharedStackMethods = {
  push: function(data){
    this.storage[this.size] = data;
    this.size++;
  },
  pop: function(){
    if(this.size > 0){
      this.size--;
      var data = this.storage[this.size];
      delete this.storage[this.size];
      return data;
    }
  },
  size: function(){
    return this.size;
  }
};

// Create an instance of the Stack class:
var myStack = makeStack("I'm a stack! Whoa.");
// Using the instance doesn't change from one class pattern to another
myStack.push(1);              // myStack stores 1
myStack.push('b');            // myStack stores 1 and 'b'
myStack.push(3);              // myStack stores 1, 'b', and 3
console.log(myStack.pop());   // logs 3
console.log(myStack.size());  // logs 2

4. Pseudoclassical Instantiation

This is the most commonly used class pattern. It’s also the most complicated because, in addition to using the this keyword, it involves two concepts that the other class patterns don’t require: the new keyword and prototypes. Prototypal instantiation uses prototypes via Object.create(), but pseudoclassical instantiation needs you to explicitly type out ClassName.prototype.methodName, which is just another source of confusion for beginners.

Also, it’s the only class pattern that uses a true constructor for creating new instances. Other class patterns use instantiator functions that explicitly return a new instance. The pseudoclassical class pattern does not perform such a return thanks to the new keyword.

Characteristics

  • Uses prototype chains to provide methods to instances of a class.
  • Allows for dynamic method modification and inheritance (subclasses!) via prototype chains.
  • Refers to the instance that’s being created with the this keyword.
  • Needs the new keyword to make an instance of a class.
  • Has a true constructor that is named with a noun rather than a verb. The name is capitalized.
  • Is the most commonly used class pattern.

Example code:

Queue from scratch (pseudoclassical instantiation)
// Class name is now a noun (no verb), and it starts with an upper case letter
var Queue = function(queueName, comment){
  // Notice the use of 'this'
  this.name = queueName,
  this.annotation = comment,
  this.head: 0,
  this.tail: 0,
  this.storage: {}
};

// Notice the use of 'prototype'
Queue.prototype.enqueue = function(data){
  this.storage[this.tail] = data;
  this.tail++;
};
Queue.prototype.dequeue = function(){
  if(this.head <= this.tail){
    var data = this.storage[this.head];
    delete this.storage[this.head];
    this.head++;
    return data;
  }
};
Queue.prototype.size = function(){
  return this.tail - this.head;
};

// Create an instance of the Stack class by using the 'new' keyword:
var myCoolQueue = new Queue("Jeff's Queue","The grass is always greener, but just as hard to mowww!");
// Use the instance just like in previous examples
myCoolQueue.enqueue('a');             // myCoolQueue stores 'a'
myCoolQueue.enqueue(2);               // myCoolQueue stores 'a' and 2
myCoolQueue.enqueue('c');             // myCoolQueue stores 'a', 2, and 'c'
console.log(myCoolQueue.dequeue());   // output: 'a'
console.log(myCoolQueue.size());      // output: 2

Queues & Stacks in JavaScript (With Batman and Superman)

- - posted in JavaScript, data structures, technical posts | Comments

The proverbial “they” say (says?) it’s good to write technical blog posts. Blog posts that get down and dirty with the nitty gritty of low-level, in-the-weeds details and nuances accompanied by jargon, acronyms, and name-dropping are all the rage in the dev community. More importantly, I really want to help beginners learn programming, so I may as well teach some basic concepts via my blog. (Later on, I hope to contribute more to The Odin Project, which is a free, open-source, online resource for beginners created by a very cool individual.)

So as my first foray in technical blog posts, I present to all loveable noobs: the introductory data structures known as stacks and queues.

What’s a Stack?

A stack is a collection of items (or data) that follow a particular rule: the last item to join the collection is the first one to leave.

  • The Last data In is the First data Out (LIFO)
  • Add data: push
  • Remove data: pop
  • Data enters and exits at the same end of the stack (at the top)

Simple implementation

Simple Stack (array-based example)Stack Overflow
var stack = [];
stack.push(1);  // use the push method provided by the Array prototype
stack.push(2);
stack.push(3);
console.log(stack);  // output: [1,2,3]

var popped = stack.pop();  // use the pop method provided by the Array prototype
console.log(popped);  // output: 3
console.log(stack);  // output: [1,2]

Ridiculous analogy

Imagine you’ve found an old, abandoned well. You think to yourself, “Bruce Wayne fell down a well when he was a kid, and I wanna be just like the Batman, so I’m gonna fall down this sweet well!” But you hesitate because …it’s a well, and wells are scary, ya know?

Unbeknownst to you, your arch-nemesis is out walking her pet hyenas. She spots you, and quickly runs over to shove you into the well. She giggles in delight at the sight of your plight. She then hides and waits for more people to walk near the well so she can push them too.

It just so happens that this well has the diameter of a single person’s width. When someone is pushed into the well, they land on top of the last person who fell in before them. This creates a stack of people and some rather pronounced discomfort. Eventually, there are 5 people in this deep-yet-thin well, and you decide it’s time to call for help to get rescued.

To your disappointment, the not-so-dark knight named Superman arrives to pull you well-dwellers out (one at a time). The last one pushed into the well is the first to pop out. LIFO.

What’s a Queue?

A queue is a collection of items (or data) that follow the real-life “rules” of waiting in a line of people: the first item to join the collection is the first one to leave the collection.

  • The First data In is the First data Out (FIFO)
  • Add data: enqueue
  • Remove data: dequeue
  • Data exits at the: head of the queue
  • Data enters at the: tail of the queue

Simple implementation

Simple Queue (array-based example)Stack Overflow
var queue = [];
queue.push(1);  // "enqueue"
queue.push(2);
queue.push(3);
console.log(queue);  // output: [1,2,3]

var dequeued = queue.shift();  // "dequeue"
console.log(dequeued);  // output: 1
console.log(queue);  // output: [2,3]

Ridiculous analogy

Batman decides to do some in-the-field combat training. He drops into the middle of a gang meeting and yells, “I’ve sent your buddies to jail. I know you want revenge. Catch me if you can. P.S. I’m Batman!” Why does the cowled hero do this? We all know Batman is a smart dude, and sure enough, he has a clever plan. He lures the baddies who are running after him into a narrow alley.

The gangsters can only approach Batman one at a time to fit in the narrow alley, so they form a line (aka queue). The gangster at the front of the line is the first gangster knocked out (aka dequeued) by Batman (first in; first out). You might even say that Batman’s fists aim for the head of the queue and foolish gangsters enter at the tail of the line of doom.

The Story Will Continue

Stay tuned for more blog posts on data structures. My next technical blog post will examine how to implement stacks and queues from scratch (without arrays) to get a deeper understanding of push, pop, enqueue, and dequeue. I know you can’t wait for the moment I deliver on this promise. I can hear your panting through my WiFi, but please stay patient. I was busy working on a web app and then a mobile app. Now, I’m busy with job searching while possibly starting mini-project.

On a mildly amusing, unrelated note: isn’t it funny to think about the phrase “stay tuned”? It’s getting rather archaic now that terrestrial, over-the-air TV and radio are losing popularity. Yes, these are the random things I think about as I write blog posts.

[HackR Diary] My Formal Apology

- - posted in Hack Reactor, HackR Diary, coding bootcamps, software development | Comments

My previous blog post was nearly 3 weeks ago. Why? What’s stopped me from posting more stories of life at Hack Reactor? For the past several days, I have been working on an individual project. I was very confident going into it, and I should eventually blog specifically about the initial stages, but as it turned out …there is a crap-ton of stuff to juggle when developing a web app. There are so many things that can go wrong in your workflow –not just in your code.

Things That Kept me Busy

  • Defaut installation of node/npm on Ubuntu led to file permissions issues. Oh shit.
  • Figuring out Yeoman: Before npm install -g yo: I wonder what will happen. After yo generator-angularexpress: What is all this stuff?! Oh nice.
  • Figuring out Grunt: How can I get it to work with Stylus? Oh nice.
  • Easy, but time-consuming (to make sure you don’t break something that used to work)
    • Organizing files/folders in a professional way (inter-file require statements can break)
    • Using environment variables (typos can be devastating)
  • Facebook Authorization
    • Making 2 FB apps (one for dev environment; one for production environment)
    • Figuring out the proper callback URL
  • Databases
    • Juggling MySQL in development environment, then switching to PostgreSQL in production.
    • Why is the production database getting flooded? Oh there’s a random configuration setting I missed in Sequelize.
  • Random Heroku hiccups (at one point, a node module provider went down, causing Heroku’s npm install to die).

These are just a few of the little obstacles that add up. You don’t see them coming. They take quite a bit of time to hunt down.

Nerdy Chuck Norris Jokes

As an apology for not blogging much in the past 3 weeks, here are some jokes from the best API ever:

All arrays Chuck Norris declares are of infinite size, because Chuck Norris knows no bounds.

Chuck Norris doesn’t have disk latency because the hard drive knows to hurry the hell up.

Chuck Norris can’t test for equality because he has no equal.

Chuck Norris burst the dot com bubble.

All browsers support the hex definitions #chuck and #norris for the colors black and blue.

MySpace actually isn’t your space, it’s Chuck’s (he just lets you use it).

Chuck Norris can solve the Towers of Hanoi in one move.

Chuck Norris finished World of Warcraft.

Chuck Norris doesn’t use web standards as the web will conform to him.

Whiteboards are white because Chuck Norris scared them that way.

Chuck Norris can delete the Recycling Bin.

Chuck Norris’s beard can type 140 wpm.

Chuck Norris can unit test entire applications with a single assert.

Chuck Norris doesn’t need sudo, he just types “Chuck Norris” before his commands.

Chuck Norris doesn’t need a debugger, he just stares down the code until the bug confesses.

The class object inherits from Chuck Norris

Chuck Norris knows the last digit of PI.

Chuck Norris’ Internet connection is faster upstream than downstream because even data has more incentive to run from him than to him.

Chuck Norris’s keyboard has the Any key.

Chuck Norris can install iTunes without installing Quicktime.

Chuck Norris’s OSI network model has only one layer - Physical.

Chuck Norris compresses his files by doing a flying round house kick to the hard drive.

Chuck Norris uses canvas in IE.

Chuck Norris’s database has only one table, ‘Kick’, which he DROPs frequently.

Chuck Norris’s brain waves are suspected to be harmful to cell phones.

Chuck Norris sits at the stand-up.

Chuck Norris has never registered an account. He just logs in.

Code runs faster when Chuck Norris glares at it.

[HackR Diary] Week 5: Final Sprints

- - posted in ActiveRecord, AngularJS, Hack Reactor, HackR Diary, Ruby, Sinatra, coding bootcamps | Comments

caltrain

Good morning

No more sprints! I’m both sad and relieved. The sprints have provided enough structure to ensure a guided education thus far. They’ve equipped me with enough skill to yield the self-belief that I can actually build a complete web app …which is good because that’s exactly what I’m going to do starting this week. Looking back on week 5 makes me think I might miss the relative safety of paired programming, but I’m pumped to be diving into my own project.

By the way, this blog post is really long. I think I’m going to split up future blog posts, and I’m going to post more frequently.

Recap of Events

Alumni Panel

Early in the week, there was a truly invaluable guest speaker event. Six Hack Reactor alumni held a Q&A session with current students. One alumnus is a Hacker-in-Residence at Hack Reactor. His role is a paid, part-time, short-term job supporting the school. There are a handful of Hacker-in-Residences at HackR at any given time. After their stints, they are put through the same job finding process that students who didn’t want to become a Resident normally go through.

The other five alumni were from Adap.tv, Adobe, DocuSign, Edmodo, and Versal, respectively. They had a variety of roles including smartphone app development, front-end MVC engineering, internal QA, data visualization, and full-stack development. I have to admit that I was a bit judgemental about the QA role at first, but it actually sounded legit by the end of the Q&A session. For what it’s worth, the Adap.tv guy was hired even though he doesn’t have a college degree! In my opinion, that’s awesome, and it really says a lot about the meritocracy found in the tech job market (…or the non-traditional, new-school nature of the Bay Area).

There was a ton of insight gleaned from the alumni panel. Examples of advice include:

  • Ask employers about their onboarding process (smaller companies might not have one, and that can be a turn-off for some newbies).
  • Invest in social capital. Wow, that was a really buzzwordy sentence so let me translate: get to know your co-workers. “Ask them out” to coffee breaks, happy hours, lunches, etc. This may sound like basic networking at first, but I think the point is that in software development, you’re going to be asking others for help quite a lot, so it’s good to build a rapport ASAP to make asking for assistance as natural as possible. This is something I never really considered before, but after all the paired programming I’ve done at Hack Reactor, it makes a ton of sense to establish rapports that foster collaborative vibes.
  • Ask employers to set up a meeting between you and your potential boss. It’s ok –this is totally ok. I used to work in an industry where this would never really be possible, so I had to ask if this is ok after one alumnus mentioned how one of his prioties when job hunting was to find a cool boss. I want a cool boss too!
  • NEVER make the first move for salary negotiations. Let them make an offer before you start specifying any numbers.
  • Specific to HackR: Don’t be too eager to accept your first job offer. You will get more. Shop around. It’s tempting to accept your first or second job offer just because employment is such a major goal when deciding to join Hack Reactor in the first place. However, joining Hack Reactor isn’t something you do just to get a job –it’s something you do to get an ideal job.

Sorry, but I forgot to take thorough notes during the alumni panel, so the list above is rather short.

More Guest Speakers

Now might be a good time to point out that Hack Reactor has guest speakers at least one evening per week. Attendance is optional. Oftentimes students choose to work on their assignments/projects at the workstations rather than stay in the lecture area to listen to the guest speaker.

What’s my point? This week was the first time I didn’t really have enough time to fully invest in the guest speakers. Rudely, I’ve forgotten that names of the speakers, but one guy spoke about databases (i.e., engineering decisions you might face when designing/creating/maintaining/scaling a database) and another guy (from Khan Academy) spoke about React, the JavaScript library written and open-sourced by Facebook. Relevant link: React presented at JSConf

Picking Personal Projects

To be honest, I wasn’t thrilled with the way HackR arranged the transition from sprints to personal projects. Students were under the impression that we’d get more support/attention for coming up with project ideas, but we weren’t given much time to brainstorm. Instead of dedicating a lecture to a guided brainstorming session, students had to come up with ideas in their spare time (which is tough when busy worrying about Ruby and Angular for the sprints).

Social Night: Haunted House

Once again, I did not attend social night. On one hand, I feel bad that my cohort has generally had low participation in the weekly social nights. On the other hand, the consensus seems to be that the social nights just don’t feel all that appealing. The first one was awesome; the others were “meh.”

Instead of going to the Social Night event last Saturday, I went to a nice happy hour/dinner with a few other students. Afterwards, I went back to HackR to continue tackling client-side user authentication with my Angular sprint partner. We failed, but we got a lot of other stuff done during the day, so I felt ok about the sprint as a whole. Plus, my partner and I established a fun rapport so even failing to get “auth” working was a funny time.

What I Learned

Week 5 included assignments for building a URL shortening web app to further improve students’ full-stack skills.

Ruby, Sinatra, ActiveRecord, SQLite

Server-side code used a lot of Ruby and Sinatra. HackR chose not to teach us students Ruby on Rails (RoR) because Sinatra is simpler than Rails. It’s easy to be bummed about this, but in hindsight, I’m not worried about it. Yes, Rails is a big deal right now in Silicon Valley, but I’m under the impression that RoR was embraced because of it’s great for rapid prototyping. Times are changing though. There are now more options for rapid prototyping. More importantly, I’m at the point in my HackR-guided education where I have built up enough fundamental know-how to make me confident that I can learn RoR later.

For now, it’s more important to learn concepts about MVC/MV* development, user authentication, databases, etc. Speaking of databases, there isn’t much for me to say about SQLite because students were harnessing ActiveRecord magic to manipulate a simple SQLite database with only two tables. We had to use tux to do database probing, which is slightly less convenient than using MySQL’s terminal interface (as we did in the previous week).

Angular

The students were pretty hyped up to learn Angular as our final sprint. We’ve invested a lot of time into learning Backbone, but word on the street (a really nerdy street) is that Angular is the “new hotness” that will take over the world of front-end JavaScript for single-page web apps.

Overall, I think the students’ reception of Angular was torn. Some love the power (Angular’s data-binding is pretty addicting); some find discomfort in the need to learn some rather bizarre syntax (Angular forces you to write HTML with “directives”).

Here’s the low down: Backbone feels like the traditional, familiar option whereas Angular feels like the more experimental, exotic option. Yes, it took us awhile to appreciate Backbone, but once we got comfortable with it, we realized how easy it is to comprehend after you get your mind around it.

For Angular, the learning curve is a lot less steep, but it also seems like it will be harder to master. There is more “magic” …and now I’m realizing I should explain that word.

Aside: What is “magic”?

When I say “magic,” I’m using it colloquially to refer to abstraction that feels harder to comprehend and feels less intuitive. For analogy*, a door knob abstracts mechanical bits. You may not be a locksmith, but it’s probably easy for a child to imagine how it works. Even as a child, you probably had some intuition that door knobs just have some simple mechanism for converting rotational movement of the knob into longitudinal movement of the latch On the other hand, it’s a bit hard for a child to imagine how a digital camera works. Even an old-school film-based camera feels magical at that tender age when you’re first capable of comprehending door knobs. Ahhh…those were the days, am I right?

*By the way, can we make “for analogy” a thing in the same way that “for example” is a thing?

Also, if you google “parts of a door knob,” you will see some complex diagrams, but I will defend my analogy! For the sake of argument, let’s just say door knobs use simple cams.

Back to my thoughts on Angular

So why does Angular seem so magical? By using Angular’s library of directives, you can have the browser display a list of items without writing DOM-manipulating code (i.e., jQuery). You can sort those items without writing a sorting function. You can filter those items without writing a sorting function. In Angular, you’re not supposed to use jQuery to change/update the HTML on the page. Angular takes care of that for you. How does it do that? Magic (directives). I haven’t even touched Angular’s feature that allows you to just create your own semantic HTML tags (e.g., <tab><pane>Content for Pane 1</pane><pane>Content for Pane 2</pane></tab>).

Routers, Templates, User Authentication

With MVC frameworks comes routers and templates. With web apps comes user authentication (sometimes).

On the server-side, routing involves RESTful APIs, which are fairly tidy interfaces that allow clients to talk to servers. On the client-side, routing involves flow control and updating the URL in the browser address bar so that it looks pretty/semantic. For example, you may want to switch to an editing panel when the user clicks a button. The router changes the URL to end in /edit without causing the page to refresh. The router also calls a function that might do edit-related things such as rendering an editing panel.

Templates are used to create sections of HTML that will contain dynamic content. Let’s say you want to render an unordered list (<ul></ul>), and the app will determine how many items (<li></li>) will be in the list. Templates take care of that.

On the server-side, routing and templating is pretty easy with Sinatra. On the client-side, routing with Angular feels easier than routing with Backbone. Templates are way easier in Angular for me.

In any case, I find user authentication isn’t very straightforward, but I haven’t tried many gems for Ruby nor Passport for Node.js. You need to check for authentication, redirect visitors as necessary, encrypt passwords (AND usernames –don’t forget that), save login info into a database, manage sessions/cookies, etc. A surprising amount of mistakes can be made.

[HackR Diary] Week 4: Now Entering Callback Hell

- - posted in Hack Reactor, HackR Diary, SQL, coding bootcamps, databases, dev tools, nodejs | Comments

photo of Joe Bowers presentation

Joe Bowers from Mixpanel discussing tech decisions based on company culture

Another week down, another blog post arriving a Monday rather than the planned Sunday. Woops. Week 4 ended on a more stressful note for me (more on that in the What I Learned section below), so I really felt the need to relax and decompress yesterday rather than write up this blog post. That said, once I complete roughly 25% of a blog post, I really start enjoying the writing process.

Because the school educates us students at such a tough pace, it’s tempting to say every week is a game changer, the most challenging week ever, the most interesting, etc. Well I’m going to induldge and say week #4 was the craziest week thus far.

I discovered that the Hack Reactor directory contains a partially complete list of all alumni’s employers. I started looking up some of the companies during a break from work. I didn’t have much time, but what I saw really inspired me. Now I’m even more excited about my own future prospects. Hooray!

There were two guest speakers this week. They both were quite technical, and I took time to smell the roses by taking a moment to think to myself, “Wow I’ve learned a lot because I understand all this very technical, very specific stuff discussed by these speakers.” Hooray!

There were a couple of toy problems that gave me some trouble this week. Maybe I’m putting too much pressure on myself, but solving a toy problem gives me a lot of self-confidence …and failing a toy problem puts a figurative frown on the figurative face of my mood for the rest of the morning (or longer). Dammit!

Students are told not to worry about comparing themselves to peers, but the seniors are killing it. I feel happy for them, but sometimes their impressive projects make me second-guess myself. Can I come up with a cool idea for an app? Self-doubt is creeping in. I only have one more week to think of something. Dammit!

As you can tell from the previous four paragraphs, the previous week was a bit of a battle between fear and pride. The worst part was falling behind on the databases sprint. The best part was watching seniors’ presentations.

Recap of Events

Guest Speaker: Pamela Fox

On Monday, Pamela Fox (formerly Coursera, currently Khan Academy) gave a great Backbone presentation at Hack Reactor. I wrote about it right here.

Guest Speaker: Joe Bowers

On Thursday, Joe Bowers (pictured at the top) gave an intriguing talk about intra-company coding culture. There are a lot of decisions to make with regards to software architecture/design, and Joe explained that many decisions are made based on coding culture/philosophy. In other words, many decisions come down to subjective thinking and preferences for certain aesthetics. His primary example was about Mixpanel’s tendency to embrace code cleanliness to the point of sacrificing DRYness and abstraction. Their code is very explicit, so you always know what it’s doing without having to spend hours studying various layers of abstraction or other quirks that might improve elegance at the cost of human-readability.

Social Night: Lit Crawl (skipped)

I’m not sure what SF Lit Crawl is, but that was the designated event for social night. I decided not to join because I felt like I needed to spend more time studying ORMs (more on that below). Spending Saturday evening at Hack Reactor is actually quite nice. There were probably 10-20 students/staff still hanging out at HackR. Sadly, I wasn’t very productive. I think my brain was just too tired from battling asychronous database queries.

On a related note, I’ve told HackR staff that the Social Nights are not well-organized. It’s clear that they are not given a high priority (attendance is optional for students), and I think they’re missed opportunities for cohort bonding. With a class size of nearly 30 students, it’s hard to get to know everyone when you spend most of your time with one person every two days (during 2-day paired programming sprints).

Seniors’ Group Project Presentations (practice)

So. Friggin’. Stellar.

Just. Absolutely. Outstanding.

I was truly blown away by the seniors’ final projects. HackR students work on two major projects during their time here. The first is an individual project, the second is a group project. Students present their projects to some Hack Reactor staff and fellow students as practice for when they have to present to employers on hiring day.

The group projects I saw last Saturday were incredible. They only had 2-3 weeks to create something worth bragging about, and they certainly surpassed my expectations. I’m half-inspired and half-worried. What they’ve done makes me prouder to be associated with Hack Reactor, but now I definitely feel more pressure to reach a similar level of awesomeness. Here are a few highlights:

  • Personal website powered by Famo.us: Making a personal website might not sound impressive, but don’t get the wrong idea. I’m not talking about an About.me page. The site has very sexy Twitter/Facebook feed integration. The product looks like something Feedly or Flipboard would create (pro quality). More importantly, the team behind the product is one of the first to use brand new tech called Famous. Famous is a JavaScript framework for continuously rendering webpages with the power of client GPUs rather than CPUs. It replaces typical HTML with a bunch of div elements that are constantly being updated (at ~60 frames per second) with new values for their properties. The Hack Reactor students not only used the new tech (which is still in private beta), they also contributed to the Famous codebase. In fact, Famous will be using the students’ product at future HTML5 conferences to demo the power of the framework!
  • Virtual Furniture Placement: A group of 4 (or was it 5?) made an app that takes user-uploaded photos of empty rooms and allows the user to place virtual, 3D furniture into the photos. The 3D rendering looks so good! It’s amazing what you can do with JavaScript (I believe they used three.js). This is definitely an app that every home seller and furniture seller should use.
  • Reddit Submission Scheduler: It’s basically Buffer, but it’s for Reddit instead of Twitter. The students have built a product that I imagine every marketer wants: an app that allows you to submit a post to Reddit at a future date/time. I actually wonder if Reddit will ban the app because it could potentially be abused to proliferate spam. That said, if Buffer can work for Twitter, than surely something similar can work for Reddit. The idea is simple and unglamorous, but it certainly meets a big demand. It’s easy to imagine a company willing to buy the students’ app.

What I Learned

Node.js (without Express)

Finally! Server-side code! Up to this point, the students have been just working with client-side assignments. With the Node.js sprint, we started sending HTTP requests back and forth between client and server. We have yet to use Express or any other Node.js framework to make life easier. We used modules like http, fs, url, and so on. The asynchronous nature of Node.js was weird at first, but to be honest, a lot of us got around that complexity by using synchronous variants of methods (e.g., fs.readFileSync()in place of fs.readFile()).

Databases

At first, I was excited by the idea of learning database goodness. But then the asynchronous nature of Node.js started raining on my parade. We worked with MySQL and a SQL-for-Node.js ORM called Sequelize. ORMs are libraries that provide a way to interact with databases without having to write SQL code. In the case of Sequelize, you just write JavaScript code with the Sequelize class/methods to query the database.

It’s not all sunshine and rainbows though. I found Sequelize to be troublesome. You can get stuck in callback hell because unlike the http module for Node.js, the Sequalize module lacks synchronous variants of methods. We have yet to explore the benefits of asynchronous/non-blocking server-side code, so it’s hard to embrace the “pyramid of doom” (aka callback hell). When I asked for help, I was told to investigate another library for adding “promises” to my code. Promises help make asynchronous code much more manageable, but I didn’t have enough time to truly learn and implement them.

So what I’m basically saying is that last week ended on a crappy note: an unfinished assignment. I’ve been told not to worry because there will be more opportunities to learn databases when working on projects (during the 2nd half of the Hack Reactor course).

In other news…

The Next Phase

There isn’t much time! In just a couple of weeks, the individual project phase begins. I have no good ideas for what to create! In my limited spare time, I’m playing Hawken, browsing Imgur, and freaking out about the personal project phase.

Nuances of JavaScript

On a more positive note, Hack Reactor shared this YouTube video via Twitter:

As I watched it, I realized that it covered material I learned in the first week or so at Hack Reactor. It felt pretty awesome. You may wonder why it took a week to learn content covered by a simple presentation on YouTube. My opinion is that the video is not meant for beginners; it’s meant for seasoned coders trying to learn JavaScript.

Disclaimer

After a few weeks of this HackR Diary blogging, I’ve noticed that I’ve missed a few things. Despite my best efforts, these posts are not as comprehensive as I originally imagined. For example, last week, I forgot to talk about learning eventing systems. Overall, I’ve been forgetting to talk about specific aspects of student life like food options, daily mini-presentations, fitness challenges, the “halp system”, volunteering for tech blogging, and so on and so forth…

So much to write about; so little time.

[HackR Diary] Event: Pamela Fox on Backbone

- - posted in Backbone, Coursera, Hack Reactor, HackR Diary, JavaScript, TIL, event | Comments

Last updated on Oct 16, 2013 (see strikethrough text).

Last Monday, the Hack Reactor students were treated to a Backbone presentation by Pamela Fox. It was packed with a ton of insight. I frantically took notes on my smartphone (like a fool), so now I present to you a collection of cool cucumbers.

What I Learned

Backbone Nuggets

  • Region management (which you can “outsource” to the likes of Chaplin or Marionette) is worth checking out. Apparently, it helps limit the amount of rendering you need to do by allowing you to target specific regions of the web page.

  • Not all Backbone libraries are created equal! Some provide sweet functionality at the cost of depressing performance losses. The Backbone ecosystem is cool, but not entirely safe. Pamela once removed a library from Coursera’s codebase that was responsible for a full second of page load time.

  • Backbone is so flexible that you might feel like an Backbone expert one day and then feel like a noob the next day when you see someone else’s radically different and compelling usage.

  • Break up your views into more views. Make sibling views and nested views. No single view should be a bajillion lines of code. If you find yourself making long js files in Backbone, it’s time to split things up, my fellow noob.

  • Don’t optimize prematurely. Performant code is harder to read. Making code harder to read early on can be annoying. I wonder if Pamela is pro-guard operator or anti-guard operator.

  • RequireJS kills your foolish usage of global vars. Perhaps I should use it.

  • Single-page web apps can be harder to debug (than multi-page web apps?) because state gets saved across various renders. Errors can be hard to reproduce during the debugging process because there might be many user interactions that need to occur in a particular sequence to cause the error.

  • Ask potential employers about their companies’ testing practices. How much regression testing do they do? How many tests have they created? More tests means less fear when contributing to the codebase as a fresh employee.

  • Making forms with Backbone (or any MV framework?) is great because forms lend themselves to the model-view-collection paradigm with ease. Forms are collections of questions, which are models, which have their own views. Each question view can draw from a set of views meant to provide a particular format (a view for a question answered by checkboxes, a view for question answered by text fields, a view for question answered by generic menu, etc). This also means Backbone is good for creating control panels for admin users (e.g., admin control panel for teacher conducting a Coursera class).

Re: Coursera

Pamela used to work for Coursera. She drew from her experiences with that company to provide a lot of context and real-world examples for the arguments she put forth in her presentation.

  • To address SEO concerns associated with single-page web apps, Coursera used Just-in-Time rendering. Coursera would detect whether or not a visitor was a search/social engine bot crawling the sit. Upon identifying the bot, Coursera servers would respond by firing up a rendered instance of the web app using Selenium. The bot would then be directed to the code produced by the rendering. This prevents the bot from crawling an HTML file that has nothing but <script> tags pulling in Backbone code. Side note: Google is not cool with the just-in-time technique. Coursera had to use a different technique for Google, but that was not disclosed during Pamela’s talk :(

  • It’s not the most organized (nevermind –it’s split into easy-to-understand folders), but you can find a lot of Coursera code on Github (open source, baby!)

  • When viewing their source code with your browser, you’ll see mostly <script> tags. There is very little <body> HTML. That’s due to extensive use of Backbone.

What I Thought

Pamela is a fantastic speaker. What I liked most about her talk was the use of real-world examples. As a student, it’s always so informative to hear about life in the wild (so to speak). Seeing as how this was a Hack Reactor event exclusively for students, it’s hard to judge it impartially, but I’m going to go ahead and claim it was awesome.