Monday, April 24, 2017

Patterns for Object Inheritance in JavaScript ES2015

With the long-awaited arrival of ES2015 (formerly known as ES6), JavaScript is equipped with syntax specifically to define classes. In this article, I’m going to explore if we can leverage the class syntax to compose classes out of smaller parts.

Keeping the hierarchy depth to a minimum is important to keep your code clean. Being smart about how you split up classes helps. For a large codebase, one option is to create classes out of smaller parts; composing classes. It’s also a common strategy to avoid duplicate code.

Imagine we’re building a game where the player lives in a world of animals. Some are friends, others are hostile (a dog person like myself might say all cats are hostile creatures). We could create a class HostileAnimal, which extends Animal, to serve as a base class for Cat. At some point, we decide to add robots designed to harm humans. The first thing we do is create the Robot class. We now have two classes that have similar properties. Both HostileAnimal and Robot are able to attack(), for instance.

If we could somehow define hostility in a separate class or object, say Hostile, we could reuse that for both Cat as Robot. We can do that in various ways.

Multiple inheritance is a feature some classical OOP languages support. As the name suggests, it gives us the ability create a class that inherits from multiple base classes. See how the Cat class extends multiple base classes in the following Python code:

class Animal(object):
  def walk(self):
    # ...

class Hostile(object):
  def attack(self, target):
    # ...

class Dog(Animal):
  # ...

class Cat(Animal, Hostile):
  # ...

dave = Cat();
dave.walk();
dave.attack(target);

An Interface is a common feature in (typed) classical OOP languages. It allows us to define what methods (and sometimes properties) a class should contain. If that class doesn’t, the compiler will raise an error. The following TypeScript code would raise an error if Cat didn’t have the attack() or walk() methods:

interface Hostile {
  attack();
}

class Animal {
  walk();
}

class Dog extends Animal {
  // ...
}

class Cat extends Animal implements Hostile {
  attack() {
    // ...
  }
}

Multiple inheritance suffers from the diamond problem (where two parent classes define the same method). Some languages dodge this problem by implementing other strategies, like mixins. Mixins are tiny classes that only contain methods. Instead of extending these classes, mixins are included in another class. In PHP, for example, mixins are implemented using Traits.

class Animal {
  // ...
}

trait Hostile {
  // ...
}

class Dog extends Animal {
  // ...
}

class Cat extends Animal {
  use Hostile;
  // ...
}

class Robot {
  use Hostile;
  // ...
}

A Recap: ES2015 Class Syntax

If you haven’t had the chance to dive into ES2015 classes or feel you don’t know enough about them, be sure to read Jeff Mott’s Object-Oriented JavaScript — A Deep Dive into ES6 Classes before you continue.

In a nutshell:

  • class Foo { ... } describes a class named Foo
  • class Foo extends Bar { ... } describes a class, Foo, that extends an other class, Bar

Within the class block, we can define properties of that class. For this article, we only need to understand constructors and methods:

  • constructor() { ... } is a reserved function which is executed upon creation (new Foo())
  • foo() { ... } creates a method named foo

The class syntax is mostly syntactic sugar over JavaScript’s prototype model. Instead of creating a class, it creates a function constructor:

class Foo {}
console.log(typeof Foo); // "function"

The takeaway here is that JavaScript isn’t a class-based, OOP language. One might even argue the syntax is deceptive, giving the impression that it is.

Composing ES2015 Classes

Interfaces can be mimicked by creating a dummy method that throws an error. Once inherited, the function must be overridden to avoid the error:

class IAnimal {
  walk() {
    throw new Error('Not implemented');
  }
}

class Dog extends IAnimal {
  // ...
}

const robbie = new Dog();
robbie.walk(); // Throws an error

As suggested before, this approach relies on inheritance. To inherit multiple classes, we will either need multiple inheritance or mixins.

Another approach would be to write a utility function that validates a class after it was defined. An example of this can be found in Wait A Moment, JavaScript Does Support Multiple Inheritance! by Andrea Giammarchi. See section “A Basic Object.implement Function Check.”

Time to explore various ways to apply multiple inheritance and mixins. All examined strategies below are available on GitHub.

Object.assign(ChildClass.prototype, Mixin...)

Pre-ES2015, we used prototypes for inheritance. All functions have a prototype property. When creating an instance using new MyFunction(), prototype is copied to a property in the instance. When you try to access a property that isn’t in the instance, the JavaScript engine will try to look it up in the prototype object.

Continue reading %Patterns for Object Inheritance in JavaScript ES2015%


by Tim Severien via SitePoint

How Privileged Are Programmers? Are You a John, Too?

John was a developer. To be specific, he was a young, white, straight, young, self-taught developer. He wasn't rare, but he was special. John grew up with a couple parents, who paid for everything he needed. John regularly filled his belly, with the finest food his family could provide. John got every toy he asked for, once he learn that asking for 3 toys was a good way to get at least 1 toy.

A spoiled child with many toys

John got average grades, but it was ok because [according to mum]; "he's just bored of schooling, and too clever". He walked right out of high-school and into a programming job. The pay wasn't great; only enough for a small apartment and modest groceries [for one]. In time he'd earn more.

Over the years, John quickly got bored of programming. He loved the thought of the career, but it was all so boring. He moved jobs every year or so, and only then when his idiot bosses stopped seeing how much he mattered to their company.

Person leaving a job happily

It was just as well, because most of the other developers he worked with were idiots too. Did they even know how to program? All they wanted to do was talk and ask questions and they weren't as interested in John's work as intelligent people should be. He did once work with a girl developer, though. She was so pretty for a programmer. I mean, if you can call CSS and HTML programming.

Illustration of a female web designer

I am angry.

For the longest time, I was John. I thought every boring task beneath me, every other developer mediocre at best. I was my own hero, and my mom was right (albeit annoying) that I was brilliant. If only those around me could see this.

Continue reading %How Privileged Are Programmers? Are You a John, Too?%


by Christopher Pitt via SitePoint

Quick Tip: Introducing Android O’s Adaptive Icons and Pinned Shortcuts

Pera

Pera – HTML5 Responsive Agency Template

'Pera' is a One Page HTML template suited for a digital agency portfolio. Features include a sticky header (that smooth scrolls to the sections, services overview, portfolio section with category filter and big image pop-up, team, testimonial slider, skills graph, pricing table, client logos, a contact form and a Google Maps footer.

by Rob Hope via One Page Love

Search and Autocomplete in Rails Apps

Adding search to Rails apps

Searching is one of the most common features found on virtually any website. There are numerous solutions out there for easily incorporating search into your application, but in this article I'll discuss Postgres' native search in Rails applications powered by the pg_search gem. On top of that, I’ll show you how to add an autocomplete feature with the help of the select2 plugin.

I'll explore three examples of employing search and autocomplete features in Rails applications. Specifically, this article covers:

  • building a basic search feature
  • discussing additional options supported by pg_search
  • building autocomplete functionality to display matched user names
  • using a third-party service to query for geographical locations based on the user's input and powering this feature with autocomplete.

The source code can be found at GitHub.

The working demo is available at sitepoint-autocomplete.herokuapp.com.

Getting Started

Go ahead and create a new Rails application. I’ll be using Rails 5.0.1, but most of the concepts explained in this article apply to older versions as well. As long as we’re going to use Postgres' search, the app should be initialized with the PostgreSQL database adapter:

rails new Autocomplete --database=postgresql

Create a new PG database and setup config/database.yml properly. To exclude my Postgres username and password
from the version control system, I'm using the dotenv-rails gem:

Gemfile

# ...
group :development do
  gem 'dotenv-rails'
end

To install it, run the following:

$ bundle install

and create a file in the project's root:

.env

PG_USER: 'user'
PG_PASS: 'password'

Then exclude this file from version control:

.gitignore

.env

Your database configuration may look like this:

config/database.yml

development:
  adapter: postgresql
  database: autocomplete
  host: localhost
  user: < %= ENV['PG_USER'] %>
  password: < %= ENV['PG_PASS'] %>

Now let's create a table and populate it with sample data. Rather than invent anything complex here, I'll simply generate a users table with name and surname columns:

$ rails g model User name:string surname:string
$ rails db:migrate

Our sample users should have distinct names so that we can test the search feature. So I'll use the Faker gem:

Gemfile

# ...
group :development do
  gem 'faker'
end

Install it by running this:

$ bundle install

Then tweak the seeds.rb file to create 50 users with random names and surnames:

db/seeds.rb

50.times do
  User.create({name: Faker::Name.first_name,
              surname: Faker::Name.last_name})
end

Run the script:

$ rails db:seed

Lastly, introduce a root route, controller with the corresponding action and a view. For now, it will only display
all the users:

config/routes.rb

# ...
resources :users, only: [:index]
root to: 'users#index'

users_controller.rb

class UsersController < ApplicationController
  def index
    @users = User.all
  end
end

views/users/index.html.erb

<ul>
  < %= render @users %>

views/users/_user.html.erb

<li>
  < %= user.name %> < %= user.surname %>
</li>

That's it; all preparations are done! Now we can proceed to the next section and add a search feature to the app.

Continue reading %Search and Autocomplete in Rails Apps%


by Ilya Bodrov-Krukowski via SitePoint

Spenser Wolz

Spenser Wolz

Minimal personal page for Washington-based designer, Spenser Wolz. That UnifrakturMaguntia font really looks great as a text logo.

by Rob Hope via One Page Love

New Short Course: React State Management With MobX