Representational State Transfer (REST)

What is REST?

REST is an architecture which describes a system that transfers generally non-static content between a client and server. This content is called a resource, and is always some uniquely identifiable “thing”. RESTful services implemented on top of HTTP are a popular solution for web applications today.

Representational

REST is representational in the sense that every request must uniquely identify a resource. A resource is something which is uniquely identifiable. The meaning of uniquely identifiable can essentially be defined by the system, and is dependent on the level of granularity at which the system works.

For instance, on one system, perhaps a hospital is a unique resource, but on another system, each of the hospital’s buildings are considered independently, so you could not for instance request the completion date of the hospital, but only of a specific hospital building.

State

A RESTful service always returns stateful data. That is, it is returning the current or specified state of the specific resource, which is not necessarily and not usually composed of static data.

For instance, suppose that our hospital added a new wing. The resource representing the hospital, if it is a correct stateful representation, would then reflect this new building. Any request made prior to the addition of the new wing would return it’s current state – without the new wing.

This should not be confused with the statelessness of the requests. A RESTful server maintains no data about the state of the client or its requests.

Transfer

Transfer of course refers to the movement of data between a client and server. Data can flow both ways in a RESTful service, which usually supports the CRUD operations in addition to request types like HTTP OPTION, etc.

How did REST come about?

First, HTTP

The Hypertext Transfer Protocol, or HTTP, was the necessary precursor to what we consider a modern implementation of a RESTful service. HTTP provides a client-server architecture that focuses on text-based requests of documents. Because the text-based requests use URIs (unique resource identifiers), they are uniquely suited for use in a REST implementation, which is based on the concept of resources.

HTTP was originally proposed by Tim Berners-Lee, as a document storage and retrieval system between remote clients and servers. The original HTTP had only one method, GET, meaning that it would not be as suitable for a REST implementation as it is today.

HTTP soon added many methods, which made HTTP suited for a REST implementation. These methods included POST, PUT, and DELETE, which are used in today’s RESTful services to represent update, create, and delete operations respectively.

The Concept

The concept was coined in 2000 for a PhD dissertation by Roy Fielding. The concepts behind REST were used as the backbone for the URI standard used in HTTP requests. HTTP was therefore RESTful in its initial implementation (v 1.1). The difference between this and modern REST concepts is that the resource can be many more things than simply a static HTML document.

From this point, RESTful concepts were heavily adopted in the Web 2.0 age of asynchronous requests which loaded content in real-time into the browser. RESTful concepts enabled relatively simple and very consistent APIs to be created which abstracted this process heavily and eased implementation of complex applications handling asynchronous data requests.

What makes something RESTful?

There are five aspects necessary for a system to be considered RESTful, and one optional.

Client-Server Interactions

The architecture must start with a client-server model, where a single server hosts the unique resource, which a client may request.

Stateless Requests

This constraint means that the server cannot store session data from a client. Each request must include the session data necessary to execute the request.

Cacheability

Requests much be created in such a manner as to be identifiably cacheable or not. This allows an intermediate component to perform caching, without special system knowledge.

Layered Architecture

Each point of processing should not have awareness of other parts of the processing chain.

Uniform Interface

The system must define a consistent API, which decouples the requests from the implementation.

Transfer of Logic

An additional concept sometimes considered is the ability to transfer logic representations that can be executed on the client. This includes scripts, applets, etc. Many people are surprised to learn that this idea is part of the original PhD dissertation, and that implementation did not catch up to the possibility of the concepts for about a decade.

What is the purpose of REST?

The purpose of REST is to provide an architecture which creates sufficient abstraction in a large complex, distributed system of unique resources, so that a client-server model of resource access, alteration, and creation, can occur without significant complexity and overhead, even in a system of global scale such as the World Wide Web has become today.

How is REST Used?

REST today is the backbone of HTTP. All common HTTP requests are stateless, and conform to all the five criteria for a REST implementation.
However, the more common modern usage of REST today is in the implementation of a RESTful service on top of HTTP. These services are used to provide a layer of abstraction from data access and representation, so that client code can easily manipulate the resulting structures and compose requests to interact with this data.

Many times, the RESTful service is implemented as an API for simple external access, with an authentication scheme built on top of it. These heavily abstracted interfaces can allow several entirely tangent applications to consume and alter data in a manner consistent with their implementation, while maintaining a single distinct data source.
It also can allow for the distribution of the total request load across several servers, which simply have to be aware of the API implementation and a data source.

Conclusion

REST is an important architectural model that defines itself as a set of five or six restrictions on top of an “unbounded” architecture. REST is not any one implementation, or any one concept or use case. It’s a highly extensible architecture that drives the web as we know it today, but is independent of its implementation in HTTP.

Many descriptions of REST are overly academic or too specific to a single implementation. I hope that I’ve provided a good resource on the fundamental meaning and purpose of REST, independent of HTTP, as well as its use in HTTP and web services today.

Given that this is a complex topic, on which all information essentially traces itself back to that single dissertation, it’s possible that some information may be inaccurate, so please let me know if you find these types of mistakes and they will be corrected immediately.

The CSS Box Model

Intro


One of the most poorly understood components of a web application is the styling. Many of the developers I’ve worked with haven’t taken the time to learn the principles that CSS relies on — especially how the rules cascade — and how padding, margins, borders, and content create the layouts of a page.

The latter is called the “box model” and is what we’ll be looking at today.

The box model is composed of four parts:

  • Content
  • Padding
  • Borders and
  • Margins

Content


CSS Box Model Content
CSS Box Model Content

In a block element, the content area is determined by:

  • The height and width, if set, otherwise
  • The height and width of its content

In an inline element (almost anything directly containing text) the content area is determined by:

  • The line-height and width, if set, otherwise
  • The height of a line (font size), and the width of its container

It’s important to note that inline element’s borders, padding, and margins will apply to each line that the content appears on.

Padding


CSS Box Model Padding
CSS Box Model Padding

Padding is the space between the border and the edge of the element’s content area. You can think of it as a margin between the border and content.

Background colors only apply to the content area, and padding space.

Borders


CSS Box Model Border
CSS Box Model Border

Borders begin immediately outside of the content area, which is essentially all you need to know. This is true for both inline and block elements.

Background colors apply to all space inside the border.

Margins


CSS Box Model Margin
CSS Box Model Margin

Margins begin just outside of the border, and determine the space between it and the elements around it.

Box-sizing


The CSS box-sizing property can cause exceptions to the above rules. The two valid values for box-sizing are:

  • content-box
  • border-box

Content-box

Our original CSS Box
Our original CSS Box

Content box is the default value for this property in CSS, and means that elements will behave as shown above. In other words, the content determines height and width, or if set explicitly, the height and width control the size of the content area.

This means that an element which has a width of 50px with 5px of padding, a 1px border, and 3px of margins would take up 50px + (5px + 1px + 3px) * 2 (two sides) = 68px of width.

Border-box

The same box but using border-box
The same box but using border-box

In this case, the width and height, when set, control the size of the element including content, padding and borders. Only the margins are not included.

This means that an element which has a width of 50px with 5px of margins would take up 50px + 5px * 2 (two sides) = 60px of width, regardless of padding or borders.

Padding-box

This value is not supported is most browsers, but if/when supported the height and width would include both the content and padding.

Margin collapsing


Another important exception to these rules is margin collapsing. Margin collapsing means that instead of two element’s margin’s being “added” together, they simply lay on top of one another, and the larger margin is displayed.

Margin collapsing occurs in 3 basic cases:

  • Adjacent sibling elements
  • Parent whose first or last child’s margins collide with parent margin
  • Empty elements

Adjacent sibling elements

Adjacent Siblings Margin Collapse
Note how the center margin is 15px instead of 30px

If two tags are located one after another then their margins will collapse.

Parent with first/last child margin collision

This occurs when the top margin of a parent element “touches” the top margin of its first child, or when the bottom margin of a parent element “touches” the bottom margin of its last child.

In either of these cases, the child element margin is “pushed” outside of the parent element, and the larger of the two is what will be displayed.

Empty blocks

When a box’s top and bottom margins touch (because there is no content), then the margins will collapse. Meaning it will essentially only have one margin, which is the largest of the two.

Summary


The CSS box model is very simple — once you understand and apply it — knowing these fundamental rules of CSS layouts, as well as the gotchas that can occur, should help you make quick work of many common layout problems.

OOP in JavaScript

Intro


In this article I will introduce you to some common design patterns in JavaScript, including patterns commonly seen in OOP languages, with some compare and contrast after each explanation when useful.

Background


There’s a common thread in the programming community that JavaScript isn’t a real language. After all, it doesn’t appear to support inheritance, data protection, or any of the other things programmers are used to seeing in modern programming languages.

It’s my opinion that this is a fallacy. I believe that people are so used to the “way things are done” that college courses teach you, that they simply reject the “new way” without giving it a chance. JavaScript is that new way, and it’s capable of nearly all the things that OOP languages are.

I will show you how to do those things and more in this post.

Basic Inheritance


In JavaScript, the concept of inheritance is implemented through the idea of shared “prototypes”. A prototype is exactly what it says. This is our definition of our object and what we believe it should do.

The prototype is set via the prototype property of an object, as such:

function Thing(){
}

Thing.prototype.doSomething = function(){
  console.log('I\'m doing something!');
};

If you’re new to JavaScript, your first question might be why a function has properties in the first place. In JavaScript everything is an object — ’nuff said.

Now, what does this have to do with inheritance? Well, if we want object SubThing to do something that object Thing already does, then we should say that Thing is SubThing’s prototype, based on what we said above. This is how we do that:

function SubThing(){
}

SubThing.prototype = new Thing();

This is basic inheritance in JavaScript. It works because the new keyword calls the function definition that follows it, then returns an object with a hidden [[prototype]] property based on the visible prototype property that we set.

Creating Instances in JavaScript


Creating instances in JavaScript is done in much the same way as any other language, but someone coming from a more classic OOP language may not understand where exactly the object to instantiate is here.

Any function definition can be used with the new keyword in JavaScript to initialize an object. Using one of our function definitions above, that would look like this:

var subThing = new SubThing();

As stated above, what this really does is create an object with a hidden [[protoype]] property based on the prototype we defined (in this case inherited from Thing).

Accessing Properties of an Object


So far, we’ve explained what a prototype is, and how to define properties on this prototype, but we haven’t actually shown how these properties are eventually used.

Any property access, specified with the dot operator (obj.property) or dictionary syntax (obj[‘property’]), will begin by looking at the objects direct properties, and then begin crawling up the prototype chain.

This protoype chain is the hidden [[prototype]] property set on the object we instantiated when using the new keyword.

It is called a chain, because it will check the current object’s prototype, then any inherited prototypes, in the order they were inherited.

As an example suppose we redefined SubThing this way:

function SubThing(){
}

SubThing.prototype = new Thing();
SubThing.prototype.doSomethingElse = function(){
  console.log('I\'m doing something else!');
};

var subThing = new SubThing();

Calling subThing.doSomethingElse() will call the method above, as the instance has the hidden [[prototype]] property we talked about before, created using new.

What does calling subThing.doSomething() do? It first looks at subThing’s prototype. Finding no property with this name, it looks for inherited prototypes. It will find the inherited Thing protoype and call the appropriate method. This is the final step in JavaScript inheritance.

Of course, inheritance of properties is only one aspect of OOP. Following is methods for implementing other common patterns.

Instance Properties


This section only exists to distinguish between static and instance properties in JavaScript. Inheriting instance properties works in exactly the same way as inheriting methods. Anything placed on the prototype essentially becomes treated as a direct property of any instances.

Static Properties


To create a static property, you simply add a property to the function definition itself. This property will be the same for all instances. This works because everything, even functions, are objects in JavaScript.

function Thing(){
}

Thing.property = 'STATIC! :D';

console.log(Thing.property); // logs 'STATIC! :D'

Unlike some OOP languages, however, the property must always be accessed and set on the function (class) itself. It’s instances do not have access to the property.

Private Data


Private variables are implemented as variables which are initialized in the constructor of the function (class definition).

These variables are scoped to the constructor and can only be accessed within the constructor.

Methods which will access private data are created inside the same constructor.

function Thing(){
  var private = "private";
  // this refers to the instance in this case
  this.setPrivate = function(value){
    private = value;
  };
  this.getPrivate = function(){
    return private;
  };
}

var thing = new Thing(); // calls constructor
console.log(thing.getPrivate()); // logs "private"
thing.setPrivate("exposed!");
console.log(thing.getPrivate()); // logs "exposed!";

Public Data


Public data is any data either declared as part of the prototype, or added to the instance during the constructor call.

function Thing(){
  this.public = "I'm public!";
}

var thing = new Thing();
console.log(thing.public); // Logs "I'm public!"

function Thing(){
}

Thing.prototype.public = "Me too!";

var thing = new Thing();
console.log(thing.public); // Logs "Me too!"

Bonus: Static Inheritance


Here’s something you can’t do in most classical OOP languages: static inheritance.

function Thing(){
}

Thing.static = "I'm static!";

function SubThing(){
}

SubThing.static = Thing.static;

It’s really that simple!

For methods, you can use the following pattern:

function Thing(){
}

Thing.static = "hi";

Thing.staticMethod = function(){
  // 'this' refers to the caller
  console.log(this.static);
};

Thing.staticMethod(); // logs "hi"

function SubThing(){
}

SubThing.static = "hi again!";

SubThing.staticMethod = Thing.staticMethod;

SubThing.staticMethod(); // logs "hi again!"

The reason this works is that “this” refers to the caller in JavaScript, so it uses the “static” property of the current caller, which is Thing, then SubThing, respectively.

Conclusion


Thanks for reading! Hope this helps anyone interested in writing maintainable code in JavaScript, and even more so that it helps people get rid of the mindset that JavaScript isn’t a “real” language and finally start treating it like one instead of writing spaghetti code!

I tried to write this all to work as-is, but please let me know if you find any errors.