Dunja Radulov wrote this on July 1, 2016

Rails Girls Novi Sad #4: Empowering Women Through Code

Last weekend, we co-hosted the fourth Rails Girls workshop, welcoming 20 women to our office to learn how to develop web applications.

Rails Girls is a global initiative with the aim of empowering women through teaching them how to code in Ruby on Rails.

The two-day workshop is quite challenging, but all the participants did a great job and successfully learned how to design, prototype and code their first web applications.

Rails Girls Novi Sad at Rendered Text

Our friends from the organizing team — Milana Ljubisavljević, Aleksandra Vukošić and Kristina Stojaković have been joined by Smiljana Mihajlović, who is now working on promoting the initiative. As always, they all did a great job organizing the workshop.

Rendered Text had two first-time volunteer mentors in this workshop - Ervin Barta and Jovan Ivanović. We’re proud that the majority of our developers have now participated as mentors in the workshops :)

Rails Girls Novi Sad Workshop

To make this blog post a more interesting read, this time around we decided to chase our beloved mentors around the office and ask them to write a few words about the workshop. Ervin enjoyed participating in the workshop:

Since the best way to learn is to teach, I decided to take part in the workshop as a mentor for the first time. I think it’s important to bring programming closer to people, because the majority is afraid of its complexity. However, with modern tools at hand, and after spending a little time behind the keyboard, they get amazed at how much they’ve accomplished in such a short amount of time. This Rails Girls event was a great opportunity to put this into practice, and I’m happy that I got the chance to take part in it. We had lots of fun, made new friends and learned something new along the way.

Rails Girls Novi Sad Workshop

Here are Jovan’s impressions about the workshop:

Rails Girls is an excellent opportunity to help reduce the underrepresentation of women in programming by showing the attendees how to take their first steps the Ruby world. This will hopefully serve as a starting point from which they will expand their knowledge, and continue creating their own applications. The importance of workshops like this one is in changing the way we see programming from an esoteric activity for the select few to an activity that is transparent and open to all.

We’re happy to support a great initiative like this one, and we’re looking forward to meeting more future girl programmers in the workshops to follow.

Rails Girls Novi Sad Workshop

Take a look at our Rails Girls Facebook album to see more photos from the workshop.

If you’d like to participate in the next workshop, you can follow @RailsGirlsNS and @RenderedText on Twitter, or subscribe to our events RSS feed.

Darko Fabijan wrote this on May 12, 2016

Welcome Sneha

We’re pleased to announce that Sneha Somwanshi has joined Rendered Text.

As our first remote employee, she will help us break new ground in how we work. She’s bringing valuable experience from both Ruby on Rails, and DevOps worlds. Prior to joining Rendered Text, she worked at ThoughtWorks.

Sneha loves traveling, conquering mountain tops, and shares our excitement in adopting Elixir and micro-services.

Welcome Sneha! Follow her on Twitter at @snehasomwanshi.

Igor Šarčević wrote this on April 7, 2016

Ecto for Rails developers — The basics

We at Rendered Text are huge fans of Ruby on Rails. As a proof, SemaphoreCI — our biggest product — is still mostly written in Ruby. Lately, however, we started migrating toward Elixir and the OTP platform. Erlang has an excellent platform for developing giant, scalable and fault tolerant systems. Elixir, on the other hand, is a Ruby-like language that helped us to swiftly transition parts of our infrastructure, and harness the power of OTP by using a familiar syntax.

We noticed two big differences right from the start.

  1. Elixir is a mostly pure functional programming language.

  2. Ecto — the de facto way to talk to databases in Elixir — has a vastly different approach than ActiveRecord.

The first issue was easy to overcome. We are huge fans of functional programming. Several of us has a working knowledge of Lisp or Haskell, and we even aim to keep our Ruby code immutable and functional. The differences in the database abstraction was a bit harder for us. We were used to Active Record quite a lot. This article is dedicated to this issue, and it is my best attempt to help you transition easier.

Ecto is NOT an ORM

The first big difference you will notice is that Ecto doesn’t convert your database rows into objects. Instead, it uses a database wrapper mechanism, called Repository, and pure Elixir data structures to return your data. Let’s see an example. In Rails, to fetch all the users who are older than 18 would probably look like the following:

users = User.where("age > ?", 18)

# users are instances of the User class
user = users.first

p user     # => #<User id: 1, age: 20>
p user.age # => 20

# we can update the object and save it back into the database
user.age = 25
user.save!

In Elixir, you don’t have objects, only pure data. All the communication must be passed through the Repo.

users = User |> where([u], u.age > 18) |> Repo.all

# users are hashes. `hd` is short for head of the list
user = hd(users)

IO.inspect user   # => %User{age: 20, id: 1}
IO.puts user.age  # => 20

# first we create a changeset
changeset = User.changeset(user, %{age: 25})

# then we send the changes into the repository
changeset |> Repo.update

As you can see, even though Ecto is not an ORM, it does resemble it.

The separation of the wrapper — the Repository — from the query interface was probably the most interesting thing when I was switching to Elixir.

Let’s start our Ecto journey with some basics. The rest of the article will teach you how to invoke CRUD operations on your repository.

Creating new entries

Creating new rows in the database is achieved by constructing a structure and sending it to the repository.

{:ok, user} = %User{name: "Igor", age: 25} |> Repo.insert

Like in Rails, we have two formats for the insert function. The regular version shown in the previous example that returns either :ok or :error, and a bang version Repo.insert! that raises an exception.

user = %User{name: "Igor", age: 25} |> Repo.insert!

Reading values from the database

To verify that our insert action succeeded, we will try to fetch it by using its id:

# id of the record created in the previous example
id = user.id

igor = User |> Repo.get(id)

The get actions can return either nil if the record is not present in the database, or a structure representing your record.

if igor |> is_nil do
  IO.puts "User with id: #{id} not found"
else
  IO.puts "User with id: #{id} is present"
end

Updating rows in the database

Unlike in Rails where we would modify the returned object, in Elixir, we will use changesets. A changeset represents some changes that we want to send to our repository. For example, let’s make our user a bit older than he is:

# first we record the changes
changeset = user |> User.changeset(%{age: 30, name: "shiroyasha"})

# then we send the changes into the repository
changeset |> Repo.update

When you get comfortable with Elixir you will most likely write the above in only one line:

user |> User.changeset(%{age: 30, name: "shiroyasha"}) |> Repo.update

The changesets are also pipable, so it is easy to make two changes separately.

user
|> User.changeset(%{age: 30})
|> User.changeset(%{name: "shiroyasha"})
|> Repo.update

Deleting records from the database

Finally, let’s delete the user from our database:

{:ok, _} = user |> Repo.delete

Final words

I hope that this article helped you to get started with Ecto. Here are some useful resources to continue your learning process:

Happy hacking in Elixir!

Marko Anastasov wrote this on April 7, 2016

Katarina Ugrinić joins Rendered Text

Today we’re reviving the custom of announcing new team members on the blog. These are exciting times for Rendered Text as we’ve been setting up various functions in the company that have not had dedicated people before. We’re very happy to see these fantastic people come and do great work. As a result, we’re collectively able to accomplish awesome things that were not possible before.

Katarina Ugrinić has joined us in our office in Novi Sad as our first recruiting manager. With her background in business finance and years of experience working in HR for tech companies in UK, she’ll be helping us find and onboard more amazing colleagues while keeping the team dynamics healthy. Katarina is a mom of three, likes roller skates and enjoys going out exploring the beauties of Serbia. In her own words:

Working with people is really stimulating and I really enjoy it. I am passionate about selecting the best person, who will not just fit the skills set, but most importantly shares our company’s values and personality traits. I like to see people growing and developing their full potential. I am excited to be joining Rendered Text through the expansion. I’m looking forward to see us growing and of course all the employees happy!

Welcome Katarina! Follow her on Twitter at @KatarinaUHR.

Igor Šarčević wrote this on February 18, 2016

Inject is a fundamental building block

Inject is one of the fundamental, and most versatile constructs available in functional languages. It can be used to implement map, select, max, all? and a bunch of other iteration related methods. Unfortunately, many programmers are not aware of its awesome powers. This article is here to improve this fact.

Let’s dig in.

Simple array iteration

First, let’s start with an example problem — finding the sum of numbers in an array:

def sum(numbers)
  result = 0

  numbers.each do |number|
    sum += number
  end

  result
end

sum([1, 3, 5, 7, 9]) # => 25

Now, let’s try to solve the same problem with a simple limitation. Let’s calculate the result without changing the values of the variables. In other words, we will try to avoid explicit state changes like in the following example:

sum += number

This is a very important step to make our code more functional. Changing the values of variables, in other words making side effects, is preventing our code to run on multiple processors effortlessly. Side effects are also a common thing that can introduce hard to find bugs.

In the functional world, instead of a for-each iteration, programmers use recursion. Let’s rewrite the above code segment with a recursive implementation:

def sum(numbers)
  if numbers.empty?
    0
  else
    first, *rest = numbers

    first + sum(rest)
  end
end

sum([1, 3, 5, 7, 9]) # => 25

It can be a little hard to grasp the idea if this is the first time you are encountering recursion in your life. The idea behind it is, however, very simple. After several tries and errors it can be mastered easily.

Accumulators

In order to create a more general purpose algorithm, and to optimize it for tail calls we will allow our sum method to accept a starting value. We will call it accumulator.

def sum(accumulator, numbers)
  if numbers.empty?
    accumulator
  else
    first, *rest = numbers

    sum(accumulator + first, rest)
  end
end

sum(20, [1, 3, 5, 7, 9]) # => 45

The name ‘accumulator’ can be confusing, but you can think of it as a variable that accumulates the result. Its purpose is equivalent to the result variable in our original imperative implementation.

Introducing inject

Now it is safe to introduce the inject method — an abstraction for the above recursive construct. Let’s use it to sum numbers:

[1, 3, 5, 7, 9].inject(20) { |accumulator, number| accumulator + value } # => 45

By renaming the variables we can make the above line more straightforward:

[1, 3, 5, 7, 9].inject(20) { |result, number| result + value } # => 45

Let’s use it to calculate the product of an array:

[1, 3, 5, 7, 9].inject(2) { |result, number| result * number } # => 805

The above patters are very handy when we want to convert an array of values into one value. This is one of the main strengths of the inject method. In this example we are reducing the array into a single value. This is why the inject method is commonly also named reduce.

Less verbose injecting

If you think about it, the { |result, number| result + value } is repeated for both of the above examples. Luckily, Ruby is a powerful language that enables us to write the above lines even shorter. The :* is a shorthand value for a block that multiplies its arguments. Let’s use it:

[1, 3, 5, 7, 9].inject(1, :*) # => 945

This representation can give us a deeper insight into the name of the inject method. We can think of inject as a mechanism that injects a * operator between the elements of the array.

1 * 3 * 5 * 7 * 9

Implementing sum and product

Let’s implement the sum and product methods using inject:

def sum(elements, from = 0)
  elements.inject(from, :+)
end
def product(elements, from = 1)
  elements.inject(from, :*)
end

Implementing map

The above example is nice, but it is not nice enough to be called a fundamental iteration block for functional programmers. Luckily, inject can do much more. The map method can be tough about as a special kind of inject. The following two code block are equivalent:

[1, 2, 3].map { |el| el * el }
[1, 2, 3].inject([]) { |result, el| result + [el * el] }

We can even implement a map method by using inject:

def map(elements, &block)
  elements.inject([]) { |result, el| result + [block.call(el)] }
end

Implementing select

We can even implement a select method using inject:

def select(elements, &block)
  elements.inject([]) { |result, el| result + (block.call(el) ? [el] : []) }
end

We can reuse the previous definition of map and sum to make it shorter:

def select(elements, &block)
  sum(map(elements) { block.call(el) ? [el] : [] })
end

Even the reject method is simple:

def reject(elements, &block)
  elements - select(elements, &block)
end

Implementing min and max

We can implement a min method that returns the smallest element in the array. The trick is to store the current minimum as the accumulated value:

def min(elements, &block)
  elements.inject(Float::INFINITY) do |minimum, el|
    el < minimum ? el : minimum
  end
end

Symmetrically, the maximum value can be calculated:

def max(elements, &block)
  elements.inject(-Float::INFINITY) do |maximum, el|
    el > minimum ? el : maximum
  end
end

Implementing all?

This is my last example, and hopefully you will be convinced that almost every method in Ruby’s Enumerable module can be implemented as an special case of the inject function.

Let’s construct the all? method that checks if every element in the array satisfies a given check block:

def all?(elements, &block)
  elements.inject(true) { |result, el| result && block.call(el) }
end

Similarly, the any? method can be implemented:

def any?(elements, &block)
  elements.inject(false) { |result, el| result || block.call(el) }
end

Should I use inject to write code?

No.

Many programmers that learn the inject method start to use it all over the place. While I admit that inject is a truly powerful construct, it is not something that should be used everywhere, especially not in business level logic.

Instead of using inject everywhere, use it to construct new, domain level functions that you can use in you code. For example, instead of writing:

usernames = ["tim", "jake", "jennifer", "marcus"]

usernames.inject({}) do |result, username|
  result.merge(username => username.length)
end

# => { "tim" => 3, "jake" => 4, "jennifer" => 8, "marcus" => 6 }

I encourage you to write a specific method that creates a hash from the input and output array. Let’s call this method hashmap:

def hash_map(elements, &block)
  elements.inject({}) do |map, el|
    map.merge(el => block.call(el))
  end
end

Then use it to calculate the same value simpler:

usernames = ["tim", "jake", "jennifer", "marcus"]

hash_map(usernames) { |username| username.length }

# => { "tim" => 3, "jake" => 4, "jennifer" => 8, "marcus" => 6 }

Or even shorter:

hash_map(usernames, &:length)

If you feel ambitious, you can even add it as a method to Array:

def Array
  def hash_map(&block)
    self.inject({}) do |map, el|
      map.merge(el => block.call(el))
    end
  end
end

Final words

Inject is super awesome, and powerful enough to express most of the iteration logic in functional languages. However, never forget the Spiderman hypothesis:

With great power comes great responsibility.

Happy injecting!

Dunja Radulov wrote this on December 16, 2015

Rails Girls Novi Sad #3 at Rendered Text

On 5 and 6 December we had the pleasure of welcoming the third Rails Girls workshop at our office.

Rails Girls is a global volunteer community with the goal to give women the opportunity to learn how to code in Ruby on Rails, and use that knowledge to build their own applications.

Rails Girls Novi Sad at Rendered Text

The third Rails Girls workshop in Novi Sad was organised by Kristina Stojaković, Aleksandra Vukošić and Milana Ljubisavljević, who have done a wonderful job of getting together a great team of mentors, coordinating the workshop, and creating a perfect opportunity for women interested in programming to take their first steps in the world of Ruby on Rails.

Three of our colleagues participated as mentors in the workshop - Nemanja is an experienced mentor who has already taught at two workshops in Belgrade and Novi Sad, and Milana and Jelena were participants in previous workshops, and now they are Rails Girls mentors and our new colleagues at Rendered Text.

Rails Girls Novi Sad Workshop

We are proud to support Rails Girls Novi Sad in their mission to encourage more women to enter the world of technology, and are looking forward to supporting future Rails Girls workshops and seeing more women develop their first Ruby on Rails applications.

Rails Girls Novi Sad Workshop

If you’d like to see more photos from the workshop, you can take a peek at our Rails Girls Facebook album.

To keep up with news about future Rails Girls events, you can follow @RailsGirlsNS and @RenderedText on Twitter, or subscribe to our events RSS feed.

Igor Šarčević wrote this on December 11, 2015

Inheritance in the Database

In martial arts, fundamentals are everything. The basic kicks, rolls and jumps are far more important that any fancy technique you will learn during the years of practice. When you improve your basic rolls even a little bit, all the body throws that depend on your ability to roll on the floor will improve tenfold.

Software engineering is almost like training martial arts. We should practice every day, and focus on improving our fundamentals instead of running for the next big shinny thing that we read on Hacker News. Of course, this is easier said that done. It is always easier to learn the basics of a new programming language, than to get better at designing classes and polymorphism.

The rest of this article describes one of the fields that I tried to improve recently — Inheritance design in relational databases.

Administrators

Let’s start with a simple problem. Imagine, that we have a web application and we store information about our users in a database table called users. We keep only the basic information about our users: their first name, last name, and a username that they use to log in to our app.

We, the developers, are also users in our application and we have the corresponding table rows in the users table. But we want to have greater permissions on our system than the rest of our users. We want to be admins — users that can manage the rest of the users, and even tweak the web application’s features.

This can be achieved easily. We can simply create a new database table called admins that will contain information about our admin users. But when we start to write out our SQL CREATE TABLE statements, something feels very odd. All the columns from the users table need to be created in the admins table too. This, of course, feels very wrong. We should take a different route.

Instead of creating an admins table, we can also add an existing column to our users table and use it to distinguish between regular users and administrators. We will call this column type, and will allow two values in its fields: regular for our regular users, and admin for our administrators.

Corresponding to these values we can construct three SQL queries.

To fetch all the users we can write:

SELECT * FROM users;

To fetch regular users, we can write:

SELECT * FROM users WHERE users.type = 'regular';

Finally, to fetch all the admins, we would write:

SELECT * FROM users WHERE users.type = 'admin';

Adding moderators

As our web application grows bigger, we find it increasingly difficult to manage the user interactions on our website. Our company decided that we should allow some of the outstanding users registered on our application to gain additional privileges. We shall call these users moderators.

Let’s add support for moderators in our database. It is easy. We just follow the design for our administrators and allow the moderator value in the type column.

The moderator lookup is simple and follows the example from our previous queries:

SELECT * FROM users WHERE users.type = 'moderator';

Banning users

One of the privileges that our moderators need is the ability to ban misbehaving users from our application. However, we also want to prevent overly eager moderators, that would ban too much of our users.

There is a simple solution. Every time a moderator bans another user, a counter will be increased. Let’s call this counter banned_users, and add it as a column to our users table. But wait, this is very strange. For a regular user, a banned_users column doesn’t make sense. They can’t ban other users.

Well, there is no nice solution to this issue if we want to store moderators in the same table as our regular users. We will simply need to accept this fact and save a default null or 0 as banned_users value for regular users.

Vehicles

I have talked so much about our little imaginary web application, but I haven’t introduced the main concern it solves. Our imaginary application sells vehicles. Cars, trucks, bicycles, ships, boats… basically everything that can move you or your cargo. Our database also needs to reflect this fact.

Let’s use the previous idea to implement a table for all our vehicles. First, we should list all the information about our vehicles. Price, color, weight and brand name are just some of the things we want to store. Also it would be nice to store some more specific data, for example, number of wheels on a truck.

After tinkering with the column names a little bit, we can see that there are a lot of fields that can not be shared between boats and bicycles. We could fill those fields with null values, but that decision feels a little weird. That could mean that a good portion of the table will be filled with nothing but null values. What can we do?

Using OOP-like inheritance in our databases

How would we design such a structure in an OOP inspired programming language? We would probably create an abstract class called Vehicle and create several subclasses for each type of vehicle. Let’s try to reflect this design into our database.

First, let’s create a vehicles table, that will contain the shared fields for all our vehicles. Price, color, weight and speed come to the mind. Following this step, we would create a table for every kind of vehicle. A table for cars, for example, would only contain the fields relevant to cars that are not present in the vehicles table and a foreign key that points to the rest of the data in the vehicles table.

After a bit of SQL hackery, our database contains all the necessary tables, and our application is ready to consume it. Let’s try some simple queries.

To count the number of vehicles in our database, we can execute the following query:

SELECT COUNT(*) FROM vehicles;

To select every car that has only two seats, we can use the following query:

SELECT COUNT(*) FROM cars WHERE number_of_seats = 2;

Now, let’s try something trickier. List all the cars that are cheaper than $10,000. Don’t forget, the price is saved in the parent vehicle table. We need to use JOIN:

SELECT * FROM cars
INNER JOIN vehicles ON cars.vehicles_id = vehicles.id
WHERE vehicles.price < 10000;

This last query was harder than what we are used to. If the cars table contained the price column, we could write it easier:

SELECT * FROM cars WHERE cars.price < 10000;

Can we design our database schema, to help us to achieve easier lookups?

Design patterns for database inheritance

Before we continue with an improved design, let’s review what we used until now.

In the first example, where we used a single table to store our administrators, moderators and regular users is called single table inheritance. This design pattern is usable when the inherited entities (in our example admins and moderators) have little or no additional fields in comparison to the super entity (in our case user).

In the second example, we designed our vehicles table using class table inheritance design pattern. It is useful for representing a structure in our database that resembles our application level design. However, databases are not well suited for this kind of inheritance, and this design can lead to more complicated database queries and even degraded performance.

The third design pattern for designing inheritance in the database is called concrete table inheritance. It is the design pattern we will use to redesign our database schema and simplify our vehicle related queries.

Simplifying vehicle related queries

To simplify our queries, we will remove the table that represents the abstract entity vehicle and store all the shared fields in every concrete table. This means that our cars table will contain all the data about a car, even its price and color. The trucks table will also have a price column.

Let’s try our lookup for cheaper than $10.000 cars with this new schema:

SELECT * FROM cars WHERE cars.price < 10000;

Much simpler!

Downsides of concrete table inheritance

In the above example, it looks like the last design pattern is the winner. However, life is just not so simple :)

Consider the request to rename the price column, or to add a new age column to vehicles. It is achievable, but we need to remember to rename/add the column in every vehicle like table. With the previous design this was much simpler.

One other common pitfall when using concrete table inheritance is that we can’t mix various types of vehicles in our code if we want to have unique IDs on our objects. Remember, every entity has its own table, that means that the primary keys are only unique on one type of entity.

Final words

I hope you have enjoyed this little trip through various database inheritance schemes. Keep in mind that this was not an exhaustive list, but only a friendly introduction to the topic. Here are some excelent resources that can help you further:

Happy database hacking!

Igor Šarčević wrote this on November 18, 2015

Closures are not magic

Several years ago, while I was still a high school student, a friend of mine introduced me the concept of closures. I didn’t understand even a bit of what he wanted to show me, but he looked really hyped when he talked about them. To me, it all looked like some kind of deep magic. Even Google didn’t help. All I could find were scientific papers, that were incomprehensible for a high school student.

I giggle a bit when I think back at my high school programming struggles. This article is an attempt to explain closures in simple terms, that would help my old high school self to easily grasp their power.

Counting events

We’ll start with a simple problem, that can be easily solved by introducing closures in our program.

Let’s say that we want to create a mechanisms for counting events. Such a mechanism would help us to keep track of our code’s execution, or even while trying to debug some issues. For example, we could use it like in the following example:

increment();  // Number of events: 1
increment();  // Number of events: 2
increment();  // Number of events: 3

As you can see in the above example, our desired code would display a message “Number of events: x” every time we execute the increment() function. Here is a simple attempt to write such a function:

var counter = 0;

function increment() {
  counter = counter + 1;

  console.log("Number of events: " + counter);
}

Multiple counters

The above code is pretty straightforward. However, we quickly run into an issue if we want to introduce a second counter. Of course, we can implement two separate counter mechanisms, like in the following example, but it is obvious that something can be improved:

var counter1 = 0;

function incrementCounter1() {
  counter1 = counter1 + 1;

  console.log("Number of events: " + counter1);
}

var counter2 = 0;

function incrementCounter2() {
  counter2 = counter2 + 1;

  console.log("Number of events: " + counter2);
}

incrementCounter1();  // Number of events: 1
incrementCounter2();  // Number of events: 1
incrementCounter1();  // Number of events: 2

The above code screams of unnecessary duplication. Obviously, this solution won’t scale to more than two or three counters. We need to figure out something better.

Introducing our first closure

What we would really like in the above example, is to somehow introduce new counters, bundled with a function that can increase them without duplicating lots of code. Here is such an attempt using closures:

function createCounter() {
  var counter = 0;

  function increment() {
    counter = counter + 1;

    console.log("Number of events: " + counter);
  }

  return increment;
}

Let’s see how this works. We will create two counters, and use them to track two independent events:

var counter1 = createCounter();
var counter2 = createCounter();

counter1(); // Number of events: 1
counter1(); // Number of events: 2

counter2(); // Number of events: 1

counter1(); // Number of events: 3

Ugh, that looks complicated… However, it is actually really simple. We just need to separate the implementation logic into small, easily digestible chunks. Let’s see what our implementation does:

  • First, it creates a local variable named counter.

  • Secondly, it creates a local function named increment that can increment the counter variable. This can be pretty strange, if you have never worked with functional languages that treat functions as data. However, it is perfectly normal, and it only takes a little practice to get used to this idea.

Please notice that at this point, the implementation of createCounter() looks almost exactly like our original implementation of a counter. The only difference is the fact that it is wrapped, or enclosed, in a function’s body. Hence, these constructs are called closures.

Now comes the tricky part:

  • The last step in createCounter() returns the local increment function. Please notice, that it does not return the result of calling the function, but the function itself.

That means, when we create new counters with the snippet bellow, we are actually generating new functions.

// fancyNewCounter is a function in this scope

var fancyNewCounter = createCounter();

This is were the power of closures lie. Every function generated with createCounter() keeps track of their own generated counter value. In a sense, the returned function remembers the environment that it was created in.

An important thing should be observed. The internal counter variables are independent of each other! For example, if we create two counters, each of them will allocate a new counter variable in the body of the closure. We can observe two things:

Each counter will start counting from number 1:

var counter1 = createCounter();
counter1(); // Number of events: 1
counter1(); // Number of events: 2

var counter2 = createCounter();
counter2(); // Number of events: 1

The second counter does not interfere with the value of the first counter:

counter1(); // Number of events: 3

Naming our counters

The message “Number of events: x” is OK, but it would be more helpful if the message could describe the type of the event we are counting. For example, it would be nice if we could add a name to our counters, like in the following example:

var catCounter = createCounter("cats");
var dogCounter = createCounter("dogs");

catCounter(); // Number of cats: 1
catCounter(); // Number of cats: 2
dogCounter(); // Number of dogs: 1

We can achieve this simply by passing an argument to our closures.

function createCounter(counterName) {
  var counter = 0;

  function increment() {
    counter = counter + 1;

    console.log("Number of " + counterName + ": " + counter);
  }

  return increment;
}

Nice! Please notice an interesting behavior in the above createCounter() implementation. Not only does it remembers the value of the local counter variable, but also the value of the passed arguments.

Improving the public interface

When I say public interface, I mean how we use the counters. It is not intuitive that the created counter is a function that will increment its value when we execute it. The following would be much simpler:

var dogCounter = createCounter("dogs");

dogCounter.increment(); // Number of dogs: 1

Let’s create such an implementation:

function createCounter(counterName) {
  var counter = 0;

  function increment() {
    counter = counter + 1;

    console.log("Number of " + counterName + ": " + counter);
  };


  return { increment : increment };
}

In the above code snippet, we simply return an object that contains all the functions in our closure. In a sense, we are defining a set of messages that our closure can respond to.

Adding a decrement

Now, we can very simply introduce a decrement function to our counter.

function createCounter(counterName) {
  var counter = 0;

  function increment() {
    counter = counter + 1;

    console.log("Number of " + counterName + ": " + counter);
  };

  function decrement() {
    counter = counter - 1;

    console.log("Number of " + counterName + ": " + counter);
  };

  return {
    increment : increment,
    decrement : decrement
  };
}

var dogsCounter = createCounter("dogs");

dogsCounter.increment(); // Number of dogs: 1
dogsCounter.increment(); // Number of dogs: 2
dogsCounter.decrement(); // Number of dogs: 1

Hidden counter actions

The above code has two redundant lines. Yes, the ones with the console.log. It would be nice to create a function explicitly for displaying the value of the counter. Let’s call such a function display.

function createCounter(counterName) {
  var counter = 0;

  function display() {
    console.log("Number of " + counterName + ": " + counter);
  }

  function increment() {
    counter = counter + 1;

    display();
  };

  function decrement() {
    counter = counter - 1;

    display();
  };

  return {
    increment : increment,
    decrement : decrement
  };
}

var dogsCounter = createCounter("dogs");

dogsCounter.increment(); // Number of dogs: 1
dogsCounter.increment(); // Number of dogs: 2
dogsCounter.decrement(); // Number of dogs: 1

It looks very similar to the increment() and decrement() functions, yet it is very different. We didn’t return it in the resulting object! That means that the following will fail:

var dogsCounter = createCounter("dogs");

dogsCounter.display(); // ERROR !!!

We made the display() function hidden from the outside world. It is only available from inside of createCounter().

Abstract data types

As you can see, we can very easily introduce abstract data types with closures. For example, let’s create an implementation for a stack using closures.

function createStack() {
  var elements = [];

  return {
    push: function(el) { elements.unshift(el); },
    pop: function() { return elements.shift(); }
  };
}

var stack = createStack();

stack.push(3);
stack.push(4);
stack.pop(); // 4

Note: Closures are probably not the best implementation for a stack data type in JavaScript. Prototypes are probably more memory friendly.

Closures and OOP

If you have done any object oriented programming in your life, you will probably notice that the above constructs look very similar to classes, objects, instance variables and private/public methods.

A closure, similarly like a class, associates some data with a couple of functions that operate on them. Consequently, you can use a closure anywhere that you might normally use an object.

Final words

Closures are an awesome property of a programming language. They can come very handy in situations when we want to create “true” hidden fields in JavaScript, or need to create very simple constructs, that would be considered an overkill for a class.

Marko Anastasov wrote this on November 13, 2015

Framing Risk

Risk has a bad reputation. In both everyday and business context, when we say that something is “risky”, we usually mean “dangerous”, “maybe you shouldn’t be doing that”, “you don’t know what you’re doing”, and so on. I’d like to reset that thinking in myself.

In fact, “a risky business move” is more of an oxymoron. A company puts its resources, means of production and employees' time and effort into use today for an expected return in the future. The future is unknown and unpredictable by definition. Therefore, risk is the basis of all economic activity. It’s just that we tend to forget that. But why?

Entrepreneurs out there hiring their first employee right now are, through that action, taking a risk. They don’t know what the outcome is going to be. Hiring that person might turn out to be a bad choice for all sorts of reasons, which is ultimately relatively easy to detect and fix. But the potential upside is much larger than the downside: together, the team may do things that are much larger than the sum of their individual efforts, and the hiring decision may be the moment a successful company is born. Entrepreneurs know this, as much as they know that taking that “risk” is the only way to move towards the goal they are trying to reach. No “risk”, no fulfillment.

We hear so often that big companies are “risk-averse”. This is exactly why a lot of them die. There is a quote that’s been passed around recently stating that “in 10 years, 40% of Fortune 500 companies will no longer exist.” Probably as much it is clear to an entrepreneur that making change (also known as “disruption” and “taking risk”) is necessary for success, to the people in a big company it is not. An entrepreneur’s antennae are tuned directly to signals of environment, while the people in an enterprise may not realize that the bigger the organization, the thicker are the layers of isolation from the outside world and its constant changes.

So I’d say the next time you find yourself pondering doing something risky, go ahead. Just make sure you’re picking the good kind of risk and prefer the action with a much bigger upside than downside.

Dunja Radulov wrote this on October 22, 2015

Meet the New Rendered Text

Behind every great product is a great group of people that make it all happen. Rendered Text has welcomed several new team members over the past few months (including myself!). Check out our refreshed About page to meet the people who make up our growing team dedicated to optimizing Semaphore for the happiness of our users.

The folks pictured above are fun, friendly, and they (usually) don’t bite. If you’re clever, creative and you’d like to work in a great atmosphere developing an awesome product head to our Jobs page and drop us a line.

Browse Archive

If you like what you are reading, subscribe to our RSS. You can also follow us on @renderedtext for updates.

Contact

Rendered Text is a software company. For questions regarding Semaphore, please visit semaphoreci.com. Otherwise, feel free to get in touch any time by sending us an email.

Rendered Text
Svetozara Miletica 10
21000 Novi Sad
Serbia