Nick Desaulniers

The enemy's gate is down

8 Months in Mozilla

| Comments

Besides 3 months interrupted to finish degree requirements, and including an internship, I’ve been at Mozilla for about 8 months now. After reading a blog post of another software engineer’s experience at Microsoft, I count my blessings. Reading that article set off too many alarms in my head. It was well written, and I sugguest you go read it, but my takeaway was that that any big name corporation people dream about working at is actually quite dystopian, and I do not feel that that is the case here.


Expect no documentation in corporations

Expect documentation to be sparse or bit rotted

When developers are coding at an unhindered pace, writing documentation does suck. But once a project reaches a certain size, it cannot sustain growth without additional support from additional developers. When a project reaches this point, it’s worthwhile to step back from unbridled coding to write some docs for your new devs. This is really important for open source projects, to get help from volunteers. I’ve heard roughly 50% of Mozilla’s code comes from volunteers; so making their lives easier is a must. Also, writing documentation is a great way to start contributing to an open source code base. Documentation is a gift that keeps on giving. By keeping information to yourself, you have power over others, but that doesn’t help your organization move forward as a whole. Depending on the pace of code development, documentation tends to bit rot. I’m all for code that’s clear enough to be self documenting, but sometimes comment blocks that describe high level overviews of the code base’s architecture can really help newbies. When you update code, you should update the relevant tests and documentation.


It is not what you do, it is what you sell

It’s all about maintainability

I’ve had nightmare code reviews. Literally reviews so long I’ve had to print them out and cross them out one by one as I fixed them to help me keep track of what I had left to fix. But by working through them, I learned an awful lot about professional code development. It literally taught me to write some bulletproof code. While it was embarrassing for me at the time, and even a little now to admit, I’m glad because it helped me grow professionally at an accelerated pace and I can appreciate that. People come and go, but their code lives on. Think about this, some day you will die, but code you’ve written will probably outlast you. You wont be around to defend your coding decisions, so commit it right while you can. Imagine the poor bastard who has to maintain your code, why not try and make their life a little easier? As an engineer, ethics and morality are the Hippocratic Oath you answer to, not someone with a business title. If you think this is wrong, if you’re not allowed to offer feedback or criticize the decisions made by those above you, then you work for the wrong company.


Not everbody is passionate for engineering

Everyone here is super passionate about what they do

While a lot of people here have active family lives, they are all active Mozillians. I’ve yet to meet anyone who didn’t have a common ground in web based software (back end, front end, browser, OS, graphics, etc.) to speak the same language as me, but also acute knowledge in his or her specialty. By being surrounded be so many smart, enthusiastic people I can tell you all about JavaScript performance, about compiler front ends and back ends, about codecs, about layout and rendering, about handling billions of hits a day, etc. If you’re the smartest in the group, the group is dragging you down. I frequently feel like I’m not the smartest when surrounded by most of my peers, and I’m cool with that. I am young and naïve and have so much to learn, and Mozilla is an awesome place to grow.


2-3 hours of coding a day is great

Contribute at your pace

There’s no pressure here about time spent coding. Time spent or number of lines written is not a benchmark to live by, code quality is. I’m a five o’clock developer, but when I go home I’m reading up on various software topics and expanding my range of knowledge. I have a big bookshelf I pride myself in filling with various programming and hardware design related books. Mozilla provides all kinds of distractions (tech talks, food, pool table, video games), because comfortable developers are better developers. I went to a talk today where the senior employee talking told me that we should not waste our time in meetings if we feel they are meaningless. “Just walk out!”


Not giving back to the public domain is the norm

Giving back to the public domain is the norm

My very first week as an intern, I had just finished my first project. I approached my manager and said “Hey I’m going to publish this now on Github. That’s cool right?” There was an uncomfortably long pause from my manager, then “yeah man go for!” Literally everything I’ve ever worked on here has been published as open source. Writing software is about expression. To be able to publish my code freely, literally the reason the World Wide Web was created, allows me to be a part of someone else’s professional development; my expressions and code mannerisms living on in theirs. Probably the coolest story I have about working here on open source software happened a few weeks ago. It was a Friday afternoon and I was assessing issues in our issue tracker, deciding which I was going to tackle first on Monday. Monday morning I came in to a pull request with my name on it. Literally some person who had never spoken to me, nor any other core devs. Someone who didn’t live in the same country as me or possibly speak my language natively, they just picked up an issue and wrote a patch in a mutually common language: code. It didn’t matter that the volunteer was or wasn’t employed by Mozilla; they understood the problem they faced enough to fix it for themselves and everyone else. Anyone can partake in the development process and earn the priviledge and trust to become a core volunteer.


The world outside is not known here a lot

Everyone here is aware of the outside world

Seeing as we tend to wind up on HN et al almost daily, many of us frequent HN, Reddit, Twitter, and /.. It’s always interesting to see coworkers show up in comment threads. When you say something hurtful about Mozilla or Mozilla products in these forums, more than a few people here are going to see this and get their feelings hurt. It’s really unfortunate especially since our issue tracker is public, and it takes a few minutes to fill out a simple bug (and a few more for steps to reproduce) where we actually look for issues (and not on Twitter, for instance). Anyways, being aware of the new hotness has benefits again in terms of expression. So much of Rust is based on ideas from various languages. So much of ECMAScript 6 comes from CoffeeScript. So many libraries have interesting and useful abstractions. Saying “bah humbug new hotness bullshit” is naïve; new languages and frameworks became popular because people found that they made software development marginally better, and by closing your mind to them you loose out on being able to take those ideas and incorporate them in your current or favorite language/framework/project. If anything, being more informed about your enemy makes your argument stronger. I can’t tell you how many times I’ve heard someone talk shit about Ruby, yet when pressed didn’t have the slightest knowledge of the language. Yet I’ve had truly great debates with those well versed in Ruby. Try to only remark on positives, and lay off negatives unless they have actually bitten you.


Copy-pasting code can be okay

Measure once, cut twice [is wrong!]

Stack overflow is great. There’s no way to know every little bit of C or C++. JavaScript has some bad parts. But by copying and pasting code that was written from another context, you’re probably introducing bugs into your code. Don’t repeat yourself, and don’t cut corners just to get shit done.


Code reviews can be skipped

Code reviews are nothing but beneficial

If they are taking too long to the point where you’re considering cutting them out, your team is probably understaffed and overworked. Code reviews allow others to spot bugs that you may have overlooked. Seeing as they didn’t write the code, they can look at the code objectively without the same assumptions you made that may or may not actually be there. It also allows you to grow as a developer, assuming you take the lessons learned to heart. The reviewer may learn a thing or two. This should obviously occur less frequently (otherwise you have the lesser experienced coder reviewing the more experienced coder’s code), but you can still teach an old dog new tricks. If you get to a point where you’re getting too bogged down in code reviews, you probably haven’t been delegating enough or haven’t communicated well enough with your manager or the rest of the team.


Latest software, meh

Latest software, duh

Old, unpatched versions of popular software are susceptible to security flaws. Java especially. It may involve work to update your code for new environments, but it’s easier to bite the bullet in small increments frequently than it is to wait until it’s too late.


Your specialties usually do not matter

You were hired because of the need for someone on your team to have a certain expertise

If this is not the case, what the hell is your recruiting department doing? You know the part where start-ups say speed is everything? It’s because of the big established players not optimally allocating resources. Even if you’re not happy when you get here, you’re able to move or at least work on something else. I’ve had the freedom to work on Rust compiler, something I never would have dreamed of doing before and not something I’m an expert in but something that is mentally fulfilling and thought provoking. Many of the people here are famous for one thing or another and many of them work on things similar to what they’re known for, while others are free to start new or tackle existing projects. We frequently borrow people from other teams who are able to lend a hand in various aspects they specialize in.

Besides these responses, there’s just so much about my job that I love. The Mozilla Manifesto is my holy book. It makes me so happy to be a part of such an incredible organization. We have the transparency and accountability the government could only dream of. Instead of running from wrongdoing, we fight! We have so many interesting projects that anyone can get involved with! We have so many employees well known for their contributions. We have so much competition that keeps us humble. We have so many experienced and friendly senior software engineers who make great mentors to the new guard. We have so many people dedicated to users, who don’t compromise privacy for security (as those who do deserve neither). We have such an amazing community of staff, volunteers, reps, advocates, evangelists, users, localizers, testers, etc. who understand that they have the power to affect the trajectory of their favorite open source browser, mobile operating system, service, or library.

Again, I’m not making any of these points with your experiences in mind. I’m talking about what’s the norm here at my place of employment.

I’ve been told that working at Mozilla out of college spoils you. If that’s the case, if life at M$ is the norm, then my next job will have to be one of my own creation. I can only hope that a company I [will] create be in the image of Mozilla. Even then, I’ll still be a Mozillian; once a Mozillian, always a Mozillian. When people complain about their jobs, it’s completely foreign to me. You always have the power to change your situation, and I view disagreement to that point as self-doubt. I love the work that I do and if your company does something that you don’t agree with, then I challenge you to change your situation. Be that speaking out or moving on.


At the end

It’s about expressing your legacy; that will have repercussions that will shape our world. Chasing paychecks and enduring crappy working conditions is not a way to live. So what do you think, world traveler?

Rust: Pattern Matching and the Option Type

| Comments

The other day I was thinking about the function for performing dynamic memory allocation in the C standard library, malloc. From the manual pages, If successful, the malloc() function returns a pointer to allocated memory. If there is an error, it returns a NULL pointer and sets errno to ENOMEM. One of the most common errors when using malloc is not checking for allocation failure. The allocation is not guaranteed to succeed and trying to use a NULL reference can lead to program crashes.

So a common pattern we’ll see is:

C
1
2
3
4
5
6
7
8
9
int* nums = (int*) malloc(sizeof(int));
if (nums == NULL) {
  // handle error
} else {
  *nums = 7;
  // operate on nums
  free(nums);
  nums = NULL;
}

Here we allocated space for an integer, cast the void* returned from malloc to an int*, compared it against the NULL pointer, then freed the allocated memory and removed the reference.

One of the big problems with the null pointer has to do with safely dereferencing it. In C, dereferencing the null pointer is undefined and usually leads to a segfault and program crash.

It can be so unsafe to work with null pointers that C. A. R. Hoare refers to them as his billion-dollar mistake:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

So how do we represent the value of nothing? With an integer, for example, your first instinct might be to use 0 to refer to no value. But 0 is a value, so how do we represent the range of integer values but also whether there is a value or not?

Rust, a systems programming language with a focus on safety and concurrency, does not have the concept of a null pointer. Instead, it has a different construct to represent the absence of value, a whole other structure called an Option. It is an enumerated type that can either be None (no value) or Some(T) (a specialization of type T).

So what the heck is an option type and how do we use it? The option type is a polymorphic type (generic type that can be specialized) that encapsulates either an empty constructor or the constructor of the original data type. Let’s take a trip down the rabbit hole to see how we use one. First, let’s look at some C++ code, and then translate it to Rust.

option.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream> // cout, endl
#include <stdlib.h> // rand
#include <time.h> // time
using namespace std;

// If there is a 'random error' returns NULL
const int* const may_return_null () {
  srand(time(NULL));
  return rand() % 2 == 1 ? new int(666) : NULL;
}

int main () {
  // if else
  const int* const x = may_return_null();
  if (x) {
    // switch
    switch (*x) {
      case 777: cout << "Lucky Sevens"        << endl; break;
      case 666: cout << "Number of the Beast" << endl; break;
      case 42: cout  << "Meaning of Life"     << endl; break;
      default: cout  << "Nothing special"     << endl; break;
    }
  } else {
    cout << "No value" << endl;
  }

  // single if
  if (*x == 666) {
    cout << "Did I mention that Iron Maiden is my favorite band?" << endl;
  }
}

Let’s step through this program line by line, starting in main.

Line 14
1
const int* const x = may_return_null();

Here we’re calling a function that may return null, just like malloc!

Lines 8-9
1
2
srand(time(NULL));
return rand() % 2 == 1 ? new int(666) : NULL;

In the body of may_return_null we seed the random number generator, generate a random number, mod it by 2 (so it can either be 0 or 1, 50-50 chance, hopefully), then either return a pointer pointing to memory allocated on the heap or the null pointer. We also use the succinct ternary operator, which gives us the power of a conditional statement in the form of a concise expression.

Line 15
1
if (x) {

We check if the pointer is valid, that is that it is safe to use, as NULL is falsy in a C++ conditional. If it is, then we can safely dereference it. Let’s switch on the (dereferenced) value. Notice how we need to break to explicitly prevent fall through, though 97% of the time that’s what you intend.

Lines 17-22
1
2
3
4
5
6
switch (*x) {
  case 777: cout << "Lucky Sevens"        << endl; break;
  case 666: cout << "Number of the Beast" << endl; break;
  case 42: cout  << "Meaning of Life"     << endl; break;
  default: cout  << "Nothing special"     << endl; break;
}

If the pointer was null, the else branch of the conditional would execute printing a different result.

Line 24
1
cout << "No value" << endl;

Finally in we check the value pointed to. Did I forget something here? Save that thought, we’ll come back to it.

Lines 28-30
1
2
3
if (*x == 666) {
  cout << "Did I mention that Iron Maiden is my favorite band?" << endl;
}

Let’s see my rough translation of this program into Rust.

option.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use core::rand;

fn may_return_none () -> Option<int> {
  if rand::Rng().next() % 2 == 1 { Some(666) } else { None }
}

fn main () {
  let x: Option<int> = may_return_none();

  io::println(match x {
    Some(777) => "Lucky Sevens",
    Some(666) => "Number of the Beast",
    Some(422) => "Meaning of Life",
    Some(_) => "Nothing special",
    None => "No value"
  });

  match x {
    Some(666) => {
      io::println("Did I mention that Iron Maiden is my favorite Band?")
    },
    _ => {}
  };
}

Both programs, when compiled should randomly print either:

option.rs
1
2
3
4
No Value
// or
Number of the Beast
Did I mention that Iron Maiden is my favorite Band?

Now let’s walk through the Rust code, starting at main and compare it to the equivalent C++ code.

option.rs Line 8
1
let x: Option<int> = may_return_none();
option.cpp Line 14
1
const int* const x = may_return_null();

I read this Rust code as ‘let x be type Option, specialized to type int initialized to the return value of may_return_none.’ I read the C++ as ‘x is a const pointer to a const integer initialized to the return value of may_return_none.’ It’s important to note that values and pointers in Rust default to being immutable, where as in c++ they default to being mutable, which is why we need to be explicit about their const’ness. In Rust, we could declare x as being explicitly mutable: let mut x: ... = ...;. In both, we can also leave the explicit types to be inferred by the compiler.

option.rs Line 4
1
if rand::Rng().next() % 2 == 1 { Some(666) } else { None }
option.cpp Lines 8-9
1
2
srand(time(NULL));
return rand() % 2 == 1 ? new int(666) : NULL;

Now for the body of may_return_none. Rust does not have a ternary operator, so a single line if {} else {} block will have to do. We also don’t need parentheses around the predicate in the conditional statement. If we add them, no harm is done, as we’d just be being redundant about order of operations. There are no semicolons in this expression, nor a return statement in this function. Rust will return the last expression in a function or method if the semicolon is left off. Also there is no such thing as a conditional statement, only conditional expressions; the if is itself something that can be evaluated and assigned to a variable! We see this later in the code where we pass the evaluation of a match expression directly into a call of io::println. Rust returns the evaluation of the if expression, which is the evaluation of the branch’s block specified by the predicate, which will randomly be one of the two enumerated types of Option<int>, either an encapsulation of a int whose literal value is 666, Some<666>, or the representation of no value, None. I believe the RNG code has changed in 0.7, this code was written in 0.6.

In Rust, to get the value out of an option type, we pattern match on it. Pattern matching is something I became familiar with through the Haskell programming language. Pattern matching is a powerful language construct that can entirely replace conditionals. In fact, the one line if expression could have been written using a match expression:

1
2
3
if rand::Rng().next() % 2 == 1 { Some(666) } else { None }
// or
match rand::Rng().next() % 2 { 1 => Some(666), _ => None }

The basic design pattern for accessing the value of an option type in Rust looks like:

1
2
3
4
match x { // x: Option<T>
  Some(y) => { *y },
  None => {}
}

The curly braces are optional for one liners (no block needed). Pattern matches have to be exhaustive. That means I have to exhaust all possibilities for what the deconstructed value could be. You can use a branch that looks like:

1
_ => 'everything else'

to catch everything else. The underscore here means “every other possible case.” So by having to use a match expression (also not a statement, as opposed to C++’s switch statement), which itself must be exhaustive, Rust forces us to handle the case where the optional type is None! This will help us again in the future. We also don’t need parentheses around the predicate for the match expression, which in this case is just a single variable, x.

In the value Some(_), the underscore has an additional meaning here that we would not use a variable in the corresponding arm’s block. If we declared it as Some(y) we would get the warning:

1
2
3
option.rs:14:9: 14:11 warning: unused variable: `y`
option.rs:14     Some(y) => "Nothing special",
                      ^~

I hope back in my C++ code you spotted the fatal flaw. On line 28, I just dereferenced a raw pointer without checking its validity. This is a violation of memory safety.

option.cpp Line 28
1
if (*x == 666) {

When running the C++ code, instead of seeing No value printed to stdout in the case of no value, a segfault occurs.

option.cpp Line 28
1
2
No value
[1]    80265 segmentation fault  ./option

What I should have done is something more like:

Line 28 corrected
1
if (x && *x == 666) {

But, the C++ compiler let me get away with not handling the case where the pointer was invalid (even if doing nothing in the case of “handling” it). By leaving out the check for a valid pointer, I have instructed the machine to behave the same or follow the same code path with and without a reference to a valid memory location. Let’s see what happens when I don’t handle the None case by deleting line 15 or option.rs, None => "No value":

Line 28 corrected
1
2
3
4
5
6
option.rs:10:14: 16:3 error: non-exhaustive patterns: None not covered
option.rs:10   io::println(match x {
option.rs:11     Some(777) => "Lucky Sevens",
option.rs:12     Some(666) => "Number of the Beast",
option.rs:13     Some(42) => "Meaning of Life",
option.rs:14     Some(_) => "Nothing special"

Not only did the compiler prevent me from generating an executable, it told me that a pattern was not exhaustive, explicitly which one, and what case that was not covered.

Coming back to encoding a lack of value for an int, we had left off that 0 is a valid value. For instance, how should we represent any other integer divided by 0, as an integer? Signed integers use a single bit to store whether their value is positive or negative, the tradeoff being the signed integers represent up to one less power of two than unsigned integers. Maybe we could use an additional bit to represent valid or invalid, but this would again cost us in terms of representable values. The IEEE 754 floating point representation has encodings for plus and minus Infinity, plus and minus 0, and two kinds of NaN. To solve the validity problem, we can use enumerated types, which in Rust occur as specializations of the Option type. It’s up to the compiler to implement either additional information for the type, or use raw null pointers. And to get the value back out of the Option type, we must handle the case where there is no valid value.

The key takeaways that I wish to convey are:

  1. In C and C++, I can use NULL to refer to a pointer that has no value.
  2. A C/C++ compiler, such as clang, will allow me to compile code that violates memory safety, such as dereferencing NULL pointers.
  3. Rust instead uses Option types, an enumeration of a specialized type or None.
  4. Rust forces me to use a match statement to access the possible value of an Option type.
  5. Pattern matching in Rust must be exhaustive.
  6. The Rust compiler, rustc, forces me to handle the case where the pointer has no value, whereas the C++ compiler, clang++, did not.
  7. All conditional and switch statements can be replaced with pattern matching.

The Persistence of Memory

| Comments

I would like to die on Mars…

Well, isn’t that forward thinking? Granted, the full quote I would like to die on Mars, just not on impact is meant to sound hopeful of his company, SpaceX. I agree that some day, humans will be buried on Mars. But is it forward thinking, enough? Does it push the needle to where it needs to be pushed? Does it strive for innovation and push our imagination like Star Trek did? Or is it just a realistic goal for SpaceX?

The person with big dreams is more powerful than one with all the facts.

Albert Einstein

While Elon would like to die on Mars, I think it would be neat to transfer my “soul” into a computer. We refer to data persistence within a computer as memory, using transistors and capacitors to store charges, effectively “remembering” a particular state. While neurons, dendrites, and synapses within the human brain don’t quite work the same as RAM, I believe we will find a way to interface them some day. If one could transfer to a computer, maybe they could transfer back, or swap even. One could theoretically trade entire bodies. The jury is still out for me as far my opinion of Google’s Glass, but I see wearable computing as a step in the right direction towards interfacing with the human body. I guess it reminds me of the Heads in Jars from Futurama. I recognize that the old guard must give way for the new guard, lest the new be held in place, bound socially by the old.

In database systems, there is this notion of Atomicity, where a set of operations is guaranteed to either complete as a group, or all fail should at least one fail. One of the most popular examples is a bank transfer. Say you’re transferring $100 from Bank A to Bank B. Bank A’s database should not dock your account $100 until Bank B has added $100, and vice versa. Imagine if the power went out after Bank A docked your account, but before Bank B added to your account; that money could just disappear. Bank B may have received it but not credited your account, or Bank A may have it, just not a record that it’s yours. You may have just doubled your money, or lost all of it. The notion of Atomicity provides for “transactions,” or sets of instructions that are guaranteed to all pass or all fail.

Atomicity would be important for a memory transference device. Once you were transferred into a machine, would it still be “you” if you remained in your body? A physical clone, is as much you as an identical twin, but will never have the same memories and experiences that shape their mind. If you merely copied your mind to a machine rather than transferred it, then you would still remained trapped in your rotting piece of meat.

This is what I mean by transfer my “soul.” An actual atomic transaction moving all of your memories and experiences from body to machine, all at once, or not at all. I probably wouldn’t want to be the first volunteer for such a machine, because if the machine failed at the atomic transaction, your soul would either be as lost as the $100 from the earlier example, or you’d just be copied, not moved.

In a world where diseases are too profitable to cure, I can imagine a world where the richest 1% live forever while the poor are forced to die. Frozen Walt Disney just sat up. An abuse of the technology, not too different a world from the one in Surrogates.

Have you not done tormenting me with your accursed time! It’s Abominable! When! When! One day, is that not enough for you, one day he went dumb, one day I went blind, one day we’ll go deaf, one day we were born, one day we shall die, the same day, the same second, is that not enough for you? They give birth astride a grave, the light gleams an instant, then it’s night once more.

Pozzo Waiting for Godot by Samuel Becket

They say that it is fear of death and what comes after death that makes men turn to religion.

Mustafa Mond Brave New World by Alduos Huxley

Ever since my father passed away, I’ve occasionally suffered from existential anxiety attacks. It usually starts with me thinking about those Discovery Channel shows about how the old the universe is, and how old it will become. Then my mind starts to think of all of the really cool technological advancements that have occurred in my lifetime, and how I wont be around to experience all future advancements, like a game that others get to play while I have to sit on the sidelines and watch. Of course, if I’m dead then I guess I won’t care. Currently, I calm myself down my telling myself that such an event is a long time away and I will live a long and happy life with many descendants, though I have no guarantees. My father only lived to be 48.

‘That’s such a weak excuse,’ said Valentine. ‘Everyone dies. Everyone leaves. What matters is the things you build together before they go. What matters is the part of them that continues in you when they’re gone.’

Valentine Children of the Mind by Orson Scott Card

Where before they would bloom and wither in the space of a single day, now they hold their blooms for three and four days at a time. Moistened by the dew of night, bathed in the light of the sun, the white flowers strive to live their lives to the fullest, beautifying the town as if striving to live out the portion of life denied to those whose “tomorrows” were snatched away from them forever.

White Flowers Lost Odyssey

Human beings, who cannot live forever, daring to take a journey without end. This might be the ultimate tragedy, but it could just as well be the ultimate comedy. Kaim knows one thing, however: one cannot simply dismiss it as an exercise in futility.

The Upstreamers Lost Odyssey

Randy Pausch’s The Last Lecture taught me that legacy is the greatest thing you can leave behind. While I haven’t yet started the business I’ve always wanted, my first legacy I will leave my kiddos is my collection of Iron Maiden vinyl records. They and their children will probably think I was nuts, but there is the slim chance they might really appreciate my taste in music. I also want to write a book someday, that way I can marvel at how my ideas will outlast me.

I like to think that something survives after you die, it’s strange to think that you accumulate all this experience, and maybe a little wisdom, and it just goes away. So I really want to believe that something survives, that maybe your consciousness endures. But on the other hand, perhaps it’s like an on-off switch. “Click!” And you’re gone.

Steve Jobs Steve Jobs by Walter Isaacson

It terrifies me to no end to think what could possibly drive someone to suicide. What doom a person would have to be surrounded with to honestly believe that no matter what they did, that they could not change their current situation. I believe the journey is ultimately worth it. It terrifies me to think of all of the amazing minds this world has seen, among so many who choose not to develop their own, that have come and gone. Those who could change the world yet are snatched away.

This body holding me reminds me of my own mortality. Embrace this moment. Remember. We are eternal. All this pain is an illusion.

Parabola Tool

I’m sorry this post turned a little dark. By talking about my fears, I hope to not let them control me. I believe publishing this will be a relief. I think I’ll join Elon on Mars, but unlike Elon, I believe I will transcend my physical being. It’s important therefor, to treasure your body while it lasts.

‘But it [life] won’t have amounted to anything,’ said Grego. ‘If your children die, then it was all a waste.’ ‘No’ said Olhado quietly. Grego shook his head. ‘Yes it does, Olhado. Death undoes everything.’ Olhado shrugged. ‘Then why do you bother doing everything, Grego? Because someday you will die. Why should anyone ever have children? Someday they will die, their children will die, all children will die. Someday stars will wind down or blow up. Someday death will cover us all like the water of a lake and perhaps nothing will ever come to the surface to show that we were there. But we were there, and during the time we lived, we were alive. That’s the truth-what is, what was, what will be-not what could be, what should have been, what never can be. If we die, then our death has meaning to the rest of the universe. Even if our lives are unknown, the fact that someone lived here, and died, that will have repercussions, that will shape the universe.’

Children of the Mind Orson Scott Card

There will allways be hope, wherever you are, until you yourself abondon it.

Old Revolutionary Lost Odyssey

Basic JIT

| Comments

Ever since I learned about Just In Time Compilation from the various Ruby VMs and JavaScript VMs, I’ve been inspired. I could tell you all about how just in time (JIT) compilation worked, and how it could give your interpreted language a speed boost. It was so cool. Well, it still is! There’s a ton of research going on around JIT compilation. But the problem for me is that I could never figure out, let alone guess, how it was being done. How could you compile code at runtime, and then execute it? I asked Benjamin Peterson about how he had learned so much about JITs, and he referred me to pypy (a Python JIT)’s source. But digging through source was too much; I just wanted a simple example I could grok quickly. So I’ve always been left wondering.

Luckily, I have an awesome job where I can meet face to face with the people who are doing the work on making awesome production JIT compilers. I spent part of last week at GDC demoing Unreal Engine 3 running in the browser. The demo was actually the hard work of many, and I’ll dive into it more in another post following up the events, but Luke Wagner, a Mozillian working on the JavaScript engine, added OdinMonkey to SpiderMonkey to allow optimizations of asm.js.

Luke is super friendly, and just listening to him talk with Dave Herman and Alon Zakai is a treat. I asked Luke the basics of JIT’ing at tonight’s Mozilla Research Party and he explained clearly. Compile a simple object file, use objdump to get the resulting platform specific assembly, use the mmap system call to allocate some memory that you can write to AND execute, copy the instructions into that buffer, typecast it to a function pointer and finally call that.

So my goal was to at runtime, create a function that for simplicity’s sake multiplied two integers. The first thing I did was write up a simple .c file, then compile that to an object file with the -c flag.

1
2
3
4
// Compile me with: clang -c mul.c -o mul.o
int mul (int a, int b) {
  return a * b;
}

As a heads up, I’m on 64bit OSX. So the generated assembly may differ on your platform. Obviously, the production JIT maintainers have abstracted away the platform dependency, taking into account what platform you’re on. My example doesn’t, but that why I’m walking you through the steps I took to find out the x86_64 instructions. The next step is to grab binutils, which is not installed by default in OSX. I used homebrew to install it: brew install binutils. Homebrew installs gobjdump but it works with the same flags.

Once you have binutils and [g]objdump, the next step is to read out the machine code from your object file, which is represented in hexadecimal. By running gobjdump -j .text -d mul.o -M intel you should get something similar (remember, architecture dependent).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ gobjdump -j .text -d mul.o -M intel

Disassembly of section .text:

0000000000000000 <_mul>:
0: 55 push rbp
1: 48 89 e5 mov rbp,rsp
4: 89 7d fc mov DWORD PTR [rbp-0x4],edi
7: 89 75 f8 mov DWORD PTR [rbp-0x8],esi
a: 8b 75 fc mov esi,DWORD PTR [rbp-0x4]
d: 0f af 75 f8 imul esi,DWORD PTR [rbp-0x8]
11: 89 f0 mov eax,esi
13: 5d pop rbp
14: c3 ret

Ok, so those instructions vary in size. I don’t know any x86 so I can’t comment too much on that particular Instruction Set Architecture but they’re obviously in pairs of hexadecimal digits. 162 == 28 meaning that each pair of hex digits can be represented by a single byte (or char of memory). So these can all be thrown in an unsigned char []. The man page for mmap explains all of the fun flags, but the important point is that this way of allocating memory makes it executable, so it can do bad things that memory allocated from malloc can’t. I’m sure the JavaScript engine guys have fun with that. Once memory is copied in, you can typecast the memory to a function pointer. Make sure to check out the syntax that reminds me of a function pointer in an argument list, but being used as an L-value. Of course, you could just put the cast right in front of the memory before you use it, but I find this as neat, not so common C syntax. I kind of have a thing for stuff like that. Then we can call it! The resulting code looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h> // printf
#include <string.h> // memcpy
#include <sys/mman.h> // mmap, munmap

int main () {
// Hexadecimal x86_64 machine code for: int mul (int a, int b) { return a * b; }
unsigned char code [] = {
  0x55, // push rbp
  0x48, 0x89, 0xe5, // mov rbp, rsp
  0x89, 0x7d, 0xfc, // mov DWORD PTR [rbp-0x4],edi
  0x89, 0x75, 0xf8, // mov DWORD PTR [rbp-0x8],esi
  0x8b, 0x75, 0xfc, // mov esi,DWORD PTR [rbp-04x]
  0x0f, 0xaf, 0x75, 0xf8, // imul esi,DWORD PTR [rbp-0x8]
  0x89, 0xf0, // mov eax,esi
  0x5d, // pop rbp
  0xc3 // ret
};

  // allocate executable memory via sys call
  void* mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC,
                   MAP_ANON | MAP_PRIVATE, -1, 0);

  // copy runtime code into allocated memory
  memcpy(mem, code, sizeof(code));

  // typecast allocated memory to a function pointer
  int (*func) () = mem;

  // call function pointer
  printf("%d * %d = %d\n", 5, 11, func(5, 11));

  // Free up allocated memory
  munmap(mem, sizeof(code));
}

Voila! How neat is that! It works! Luke’s directions, an hour of working on this, and this article in particular, and we have a simple JIT working. Again, this simple example is super non-portable and dealing with memory in this fashion is generally unsafe. But now I know the basics of JIT’ing code, and now so do you!

Thanks Luke!

Commandments of a Mobile Web

| Comments

Over the past few years, there’s been certain paradigm shifts in web development. When you think of milestones that really changed how development on the web was done, the two biggest were Ajax and HTML5. Development was identifiably different before and after such technological advancements. There were some who initially doubted the technologies, but I’m sure such doubters eventually saw the light. After spending time working on applications for Mozilla’s upcoming mobile operating system, Firefox OS, and talking with my fellow employees, I feel that the mobile web is another one of those shifts in how we approach web development that looking back will be an identifiable point in time where we can say that we did things differently before and after. So in that sense, I want to share some of the insights I’ve found to help other developers wrap their heads around how developing for the mobile web isn’t their traditional cup of tea.

Internet connectivity is not guaranteed

This is a fundamental divorce from the World Wide Web and the Internet. I feel that a lot of people having trouble differentiating the Web from the Internet; where you’ve had one, you’ve always had the other. Don’t assume your application will always have a valid connection. When a user is on a wifi connection, or hardwired, it’s so obvious that if they’re on your website, then they must be connected to the Internet. Right? But what happens now when one of your users loads up your site or app on a mobile device, then enters a tunnel? What does it do when offline? Does it work? Maybe it doesn’t make sense if you’re offering a service that requires data from the back end, but does that mean that the front end should totally look like crap or break when the back end can’t be reached? Do your Ajax requests have error callbacks? Do you try and reconnect your WebSocket connections after they’ve failed? Do you cache previous requests or use one of the many forms of offline storage to show something to the user? Developing on the loopback is literally the best case for connectivity, but it gives the developer a false sense of how latency and connectivity issues affect their application. It’s literally shocking the first time you encounter your site/application offline if you didn’t think about the user experience up front.

Bandwidth is not free

The advent of broadband made it acceptable for sites to utilize massive amounts of assets. Seeing sites that load up so much stuff makes my heart sink when I wonder about viewing such a site on my mobile device. I only pay for so much mobile data per month, then I’m billed ridiculous amounts as a “Data Overage”. Users in other countries frequently have a more pay as you go style plan, so they’re being billed for each bit across the wire. In countries without the infrastructure necessary to get broadband Internet to every household, mobile is more prolific in getting users connected.

Things like minification and gzip certainly help, but deferred loading of assets until they’re necessary is frequently overlooked. Massive libraries are nice for devs, but may end up giving mobile users more problems than they are worth. There exist more advanced techniques such as WebSocket compression.

How much does your site weigh?

An expensive website does not make an awesome app

Why doesn’t my million dollar website make a kick ass web app?

This point is brought to you by Matt Basta. The point is that there is something fundamentally different between a web “site” and a web “app”. In a web site the usual flow involves loading up a page and maybe navigating between pages. An app more often than not will be a single page that loads data asynchronously and dynamically modifies the content displayed to the user. Some web sites make great use of things like Ajax, and are great example of single page sites. But not all are. Some still haven’t come around to loading all data asynchronously on request. And it’s not that they necessarily even have to, they can be a website and never have to be anything more. But you’ll find that some sites make better apps than others.

No chrome

Not the browser made by Google, Google Chrome; the actual controls on the top of your browser such as the back and reload buttons, and the url bar. This point comes from Chris Van Wiemeersch. One of the things you’ll find when evaluating whether a site makes a good app is whether it relies on chrome to navigate. If it does, then it’s not really going to cut it as an app. If you’re going to make a single page app, try making it fullscreen in your browser and try navigating around. Are you hindered without the chrome? One thing I found recently was an error condition where I notified the user that they had to be online to check for an update. But when I was developing, I would just refresh the page to clear the error message and try again. On a device, as an app, where there was no chrome, this meant closing and restarting the app. That sucked, so I made it so the user could click/touch, after figuring out their connectivity issues, to retry the fetch. Even better may have been to listen for online events!

Traditional forms of input are not fun

Here’s some tips from Matthew “Potch” Claypotch.

Fingers aren’t as precise as cursors

Having tiny click targets is really frustrating. How many times have you clicked the wrong thing on a mobile device? Tiny buttons are not the easiest thing for users to specify, especially when groups of them are clustered nearby. Custom buttons enabled by a little CSS can go a long way.

Typing on little keyboards in tedious

This is an effect of tiny buttons, but requiring the user to type in large strings gets annoying fast. Sometimes this can’t be avoided, but it should be when it can. Just as typing in a long, complex url to a mobile browser is not enjoyable, neither is doing so in an app.

Detect features not browser engine (User agent sniffing is a sin)

Print this and staple it to your wall above your workspace. This should be old news at this point.

Vendor prefixes are meant for browser vendors to test, not production code

I place a majority of the blame for this on vendors; prefixes should never see the light of day in release builds. It’s ridiculous to have to write four copies of the same rule, when you’re trying to express one thing. I should rewrite this sentence four different ways to prove a point. -o-Do you understand what I’m getting at? -ms-It’s almost like rambling. -moz-Repetitive department of repetition. -webkit-This is ridiculous.

But developers need to recognize the habit as an addiction, and not feed it. If you have, I forgive you. Now stop doing it.

These two particular articles are just so good, it wouldn’t do them justice to try and summarize them. Please go read them, I’ll wait. this and this

Developing towards WebKit and not HTML5 is a sin

I understand that Google Chrome is your favorite browser, and I am so happy for you; but it is not mine. I’ll be the first to admit that Google caught all of the other browser vendors with their pants down, but when I see pages that look flawless in Chrome and not so hot in others, it reminds me of days when sites only worked in IE6. Surely you remember those days. I hate when content publishers try and dictate which browser I should use to view their content. I understand WebKit based browsers dominant in mobile, but so did IE6 in desktop share at one point. It’s not unreasonable to expect users to use the most updated version of their browser, but empower your users to choose their browser. Don’t take that choice away from them.

A neat point by Robert Nyman is that WebKit itself already has forks. Can you imagine if there were eventually vendor prefixes for forks of WebKit? Continuing with vendor prefixes means that we’ll now have seven vendor prefixes: unprefixed, -moz-, -o-, -ms-, -webkit-o-, -webkit-chrome-, -webkit-safari-. Awesome! Maybe I should rewrite this sentence seven different ways to make a point!

I’m also curious if Google, Apple, and the WebKit maintainers are turning a blind eye to this, or what their opinions are? Being a vendor and wanting an open web are almost conflicts of interest; you want your browser to “win” or dominate in marketshare, but at the same time you don’t want any one browser having too much marketshare.

Design Responsively

What is responsive design? Responsive design is making a site look great on any size screen, without duplicating assets or sniffing a user agent string. Firefox has a neat web dev tool called “Responsive Design View”. It’s great for testing out your site on various screen sizes. Twitter Bootstrap is an excellent example of a framework for developing a single app that looks great on any screen size. Even if you don’t want to use a whole big framework, simple things like using CSS rules in terms of percentages instead of hard coded pixels can go a long way.

Sites that are trying to become more app like have trouble with conforming to responsive design. Instead of starting with a site and trying to figure out how to hide or not display information as the screen gets smaller, you’ll find it much easier to start small, and dynamically add content as the screen gets bigger.

High performance code respects battery life

In the end of the day, all of the code you write that runs in the browser is a set of instructions the processor can decode, not necessarily the high level JavaScript you wrote. While it’s important to avoid premature optimizations, having a few rules of thumb up front will help you write better, faster code. If the same overall action can be expressed in one instruction or one hundred, which do you think will use less power? Keep in mind that transistors leak current while switching.

Native methods over library methods, CSS over JS

What do I mean by “native methods?” Like C++? Well, yes. You see under the hood the DOM bindings that you’re calling are probably written in C++. Call toSource() on document.getElementById(). The [native code] statement in the returned string refers to the implementation. While type specialized code emitted by the JIT can match or even beat native code, you can only count on that for hot loops. In the same vein, library code is going to be slower than any code written natively. I’m not saying that you shouldn’t use libraries, just know that the use of libraries can incur some overhead. Things like animations will also be faster when handled by natively implemented CSS over JS. You can use JS to dynamically add classes to elements to get finer resolution over events, but then get the performance of CSS.

Avoid JIT bailout

The Just In Time (JIT) interpreter is a new breed of VM that most browser vendors are now using. The JIT can analyze running code, and emit native code that is faster than reinterpreting code again, and even higher-optimized code for type stable JavaScript, as long as certain “guard” conditions are met. When a guard fails, the JIT has to bailout the emitted native code and start reinterpreting code again.

Keep up to date on new APIs

HTML5 is a big spec, and is getting bigger. So big that some recommendations are being spun off from the original HTML5 spec. As an engineer, I’m painfully aware that you need to keep up in whatever industry you work in in order to stay relevant. The complacent are the most vulnerable. There’s a lot to keep track of with HTML5 and CSS3, but many new features offer higher performance methods of skinning the cat.

requestAnimationFrame

window.requestAnimation frame is a godsend for animation. Not too long ago, I wrote up a quick example of various ways of implementing animation loops and their issues; you should check it out.

indexedDB over localstorage

The indexedDB api might not be as simple as localstorage’s is, but localstorage is synchronous and is noticeably slow on mobile. If you can bite the bullet and use indexedDB, you’ll find you’re JS isn’t blocking on serializing/deserializing objects for storage. Fabrice Desré shared this with me.

WebWorkers

Webworkers can’t modify the DOM, but they can do heavy lifting without blocking the main thread.

CSS translate over absolute top and left rules

Harald Kirschner recommends CSS translates over top and left rules for absolutely positioning some elements.

Gradients are expensive

Dan Buchner notes that without beefy graphics processing units of their desktop counterparts to enable hardware acceleration, things like gradients will give you noticeable performance hits.

createDocumentFragment

Dan also suggests queuing up DOM changes. Whenever you manipulate items in the DOM, you’re going to trigger a reflow, which may consist of an update to the layout and/or a repaint. Minimizing these makes for a faster update to the DOM. For example, it can be faster to use document.createDocumentFragment and append child nodes to it, and then append that to the DOM, instead of appending lots of child nodes in between timer calls. Surprise, this isn’t actually a new DOM binding from HTML5.

Conclusion

These are just some tips I have for application developers. I am by no means an expert; I’m sure if you dig deep enough, you can find plenty of examples of my past work that contradicts some of my recommendations from this article. But I’m a little smarter today than I was yesterday, and now so are you! What are some tips that you have to share that you’ve found helpful developing for the mobile web?

C Function Pointers Alternate Syntax

| Comments

On an interview with Square, I made the mistake of stating that one of the benefits of working with JavaScript over C is that functions are first class in JavaScript, therefore they may be passed around. To which the interviewer replied, “Well, C can do that, what about function pointers?” What? Luckily, I was able to get out of that jam by guessing that JavaScript had a nicer syntax.

While I was taught some C in university, we had never gone over function pointers or more in depth topics such as static or dynamic linkage. I was so embarrassed that my expensive (read overpriced) degree had not taught me more about the C programming language, especially from the Computer Engineering department that focuses on software AND hardware. On my exit interview with the dean, I was very opinionated on the amount of C that was (or wasn’t) taught at my university. His argument was that there are only so much of so many languages you can cover in a university, which to some extent is valid. My problem has been that I’ve enjoyed learning many different programming languages, though I didn’t really get it the first time around (with Java). I think knowing many different languages and their respective paradigms makes you a better programmer in other languages, since you can bring a Ruby Way to Rust or a JavaScript functional style into C.

I had read two books in the meantime that really flushed out more of the C language to me and I would definitely recommend them to those who want to learn more about the language. They are Head First C by Dave and Dawn Griffiths and 21st Century C by Ben Klemens. I’m also aware that The C Programming Language by Brian Kernighan and Dennis Ritchie is also known as the canonical text. The book is often referred to as ‘K&R’ after the authors’ initials, and Dennis Ritchie was the original creators of the C language and co-developer of Unix. I’d love to get a chance to read it someday.

This article appeared on Hacker News and really piqued my interest. Defenitely a great read. What really stuck out to me was one of the comments though. The author of the comment mentioned a less ugly syntax for function pointers, with a link to an example. Now I’m not sure what the commenter meant by “these params decay naturally to function pointers” but I was skeptical about this different syntax. Even the Wikipedia article used the syntax that I was familiar with. So I wrote up a quick example to try it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// compiled with:
// clang -Wall -Wextra function_pointers.c -o function_pointers
#include "stdio.h"

void usual_syntax (void (*fn) (int x)) {
  puts("usual syntax start");
  fn(1);
  puts("usual syntax end");
}

void other_syntax (void fn (int x)) {
  puts("other syntax start");
  fn(2);
  puts("other syntax end");
}

void hello (int x) {
  printf("hello %d\n", x);
}

int main () {
  puts("hello world");
  usual_syntax(hello);
  other_syntax(hello);
}

Sure enough we get:

1
2
3
4
5
6
7
hello world
usual syntax start
hello 1
usual syntax end
other syntax start
hello 2
other syntax end

So the moral to the story I guess is that there’s always more to your favorite language. From using variadic macros with compound literals to enable a more functional style in C to reflecting upon a function’s number of arguments or name or adding attributes to a function or the y-combinator in JavaScript, I learn something new every day. And I hope that you did too! Thanks for reading! If you have some other recommendations on good programming books, or design patterns, please leave a comment or write a reply blog post!

[Internet] Freedom Is Not Free

| Comments

Last week, the Internet community lost a member in the on going war against the copyright industry. While I’ve never met the deceased, or even heard of the deceased before his suicide, I’m horrified. I’m horrified that the government we are asked to put so much faith in, would give someone, not that different from myself, such a ridiculous sentence. That I could be thrown away, locked away from the things that I love for 35 years, for freeing information that should have been free, and was later made free.

That my government would strike such fear into someone’s life that they would prefer death by their own hands to punishment. Why do we put up with this?

The Internet, and the technology sector evolves so quickly. It’s amazing that the law the deceased was being prosecuted under, pertaining to computers, is from 1986. Can you even remember what computers were like in 1986? I didn’t even exist! My first family computer ran Windows 95. I can only imagine how archaic laws would be that were based on such rapidly evolving tech.

The limiting of information is problematic to me. How do the people of China, Iran, and others feel about their government? I assume they are aware that the government is limiting their body of knowledge. Even the US television news agencies can’t get the story straight. It reminds me of George Orwell’s 1984, where the language is limited to curtail expression. If the free world uses the Internet as Transactive Memory, does the oppressed world know what they’re missing? Can you know what you’re missing, before you’ve lost it?

The media and copyright lobby disgust me. I’m disgusted that my former state senator is now the Chairman and CEO of the MPAA. Remember learning in high school civics the term “Revolving Door”? Case in point.

America was constitutionalized as a republic, but through amendment has evolved into a democratic republic. The idea of a republic was important to an agrarian society, and we still feel the effects every first Tuesday in November; the least convenient day of the week. Voting for someone just to represent you was convenient when your form of long-range communication was a man on a pony. With the rise of the Internet, and representatives who work for their lobbies and not the people, why do we still elect officials? Why are we a republic? Why not just a democracy? Allow voters to authenticate and cast their vote online. Everyone. No computer or internet? I’m sure your local library offers both free for public use. “But people don’t always know what’s right.” Sure, I think some people aren’t too bright. But then I see the deadlock in congress, fiscal cliff after fiscal cliff, and I can’t help but think we could do better if we just fired all of these assholes.

Why can’t the difference in viewpoints be celebrated? A good leader recognizes both sides of the coin. I love having a diverse team of people with varying backgrounds, because they come up with solutions I never could have. And if you want to beat your enemy, you have to know your enemy. That means empathizing, understanding where they come from.

If you give orders and explain nothing, you might get obedience, but
you’ll get no creativity. If you tell them your purpose, then when your
original plan is shown to be faulty, they’ll find another way to achieve
your goal. Explaining to your men doesn’t weaken their respect for you,
it proves your respect for them.

Han Tzu Shadow of the Giant Pg. 303 by Orson Scott Card

I don’t hate anyone for what they believe, nor do I try to persuade them otherwise. I just feel like the technologically minded are under represented in Washington. I wish we had a technological party. We need a party that strives to protect the internet, the ideals behind the freedom and preservation of information, the technical investment in sovereign energy and our failing infrastructure, and internet access speeds that are unrivaled in the world, not stagnated by corporations who are relatively regional monopolies. One where social issues are open to debate, but also where protecting our greatest asset and achievement is top priority. One where the media industry is invited to the table, unlike the back door policies they would try to slip in under our noses. My dad advocated a turn the other cheek policy. That’s called acting like an adult.

My belief of good vs. evil is that there is no good or evil, but that people are inherently selfish. They do things that are perceived by others as evil. But they don’t do things because those actions are evil, they do them because they gain some form of personal utility from the action; they perceive the action as good. And it is good…to them. It’s easy to be evil. It’s the easy way out. It’s harder to think about other people. It’s tougher to do the right thing. Being good is so recognizably hard; it’s impressive.

The president of MIT, L. Rafael Reif, had this to say regarding the deceased: “It pains me to think that MIT played any role in a series of events that have ended in tragedy…” Fuck you. Maybe if MIT’s bottom line wasn’t their acceptance rate, they might be able to look out for more than just their own.

All that is necessary for the triumph of evil is that good men do
nothing.

Edmund Burke Thoughts on the Cause of Present Discontents

Suicide is never the answer. No matter how shitty your current situation is, no matter if things will never go back to the way they were, you will always be able to change your situation. Maybe not immediately, but that’s what goals are for. Anyone who ever committed suicide to prove a point could have done more for their cause dedicating the rest of their life to it. If you’re feeling depressed, talk to someone. It will make you feel so much better to talk to someone about what’s upsetting you. As much as people like to shit on the Catholic Church, I feel like the Catholic practice of penance (confession), provides a cathartic placebo effect. If you are depressed or hurting, and you need someone to talk to, even a complete stranger, feel free to contact me. I will always provide an ear and a shoulder.

It seems strange that my life should end in such a terrible place, but
for three years I had roses and apologized to no one. I shall die here.
Every inch of me shall perish. Every inch, but one. An inch. It is small
and it is fragile and it is the only thing in the world worth having. We
must never lose it or give it away. We must NEVER let them take it from
us. I hope that whoever you are, you escape this place. I hope that the
world turns, and that things get better. But what I hope most of all is
that you understand what I mean when I tell you that, even though I do
not know you, and even though I may never meet you, laugh with you, cry
with you, or kiss you, I love you. With all my heart, I love you.

Valerie V for Vendetta

The next time the media industry tries to limit what you have access to on the Internet, make a big ruckus. Inform everyone you know about the facts. Pushing for an increase in media piracy activities is not the right answer. Instead we should push to boycott working for organizations like the RIAA and MPAA and their ilk. Think about how much better off we would be in the United States if teachers were paid like rock stars and rock stars were paid like teachers? Instead, everyone in the media industry needs a fat paycheck. Celebrity is the case in point of the blind leading the blind. Did you know that EMI owns the copyright to the footage of Martin Luther King’s “I have a dream” speech? If you can find it, I bet it wont be up long. Frankly, I’m surprised EMI doesn’t also own the Declaration of Independence and Constitution, charging admission.

Revolutions are a continuation of the battle between sword and shield. Something new is created and shows potential, then doubters pop up seeking to curtail that which upsets their competitive edge. In the case of information, many make money and become powerful off limiting the access to knowledge. I think all knowledge that is beneficial to mankind should be open, and that the Internet is the ultimate utility for the sharing of our collective knowledge. Where do you draw the line, you might ask? I think the knowledge required to make atomic weapons and 3D-print receivers is decidedly unbefitting of society, for instance. And in the end, you can’t take any of the knowledge you protect with you. If everyone shared what they knew, then you’d have a more improved life, since then the right people would be in the know to advance our being. Technology would advance even faster than it does currently if we weren’t limited to tick-tock product cycles and business secrets.

So what does a rant about government, antiquated laws, corrupt representatives, celebrating diversity, hypothetical political parties, inaction, and established industries have to do with anything? They’re all anchored to a suicide. They’re all that’s been running through my mind lately. What I see in the deceased, I see in myself. Standing amongst my peers, celebrating Internet Freedom Day , listening to Peter Eckersley of the EFF talk, I realized ‘The power is yours!’. So now I add my voice to the or so 20 Internet activists that will continue to spring up as one falls.

What will you do to shape the world you live in? What are you going to do to fix it? If you don’t, I will. Because if you want something done right, you have to do it yourself.

It has to start somewhere It has to start sometime
What better place than here, what better time than now?

Rage Against the Machine Guerrilla Radio

Closures: JavaScript, Ruby, and Rust

| Comments

It’s all about closures. Understanding scope is paramount to coding. What can you access and what can’t you access. Closures allow us to access variables that otherwise might be awkward to pass into a function. Closures can help us out of tricky situations, but can confuse those from backgrounds with (typically) statically typed languages that may not support closing over variables.

Rust is an up and coming systems level programming language being developed at Mozilla. Let’s take a look at the syntax of closures in Rust, but first let’s see how closures are implemented in some other, more popular languages.

In JavaScript, closures are super common. Here’s a simple example.

1
2
3
4
5
6
7
var x = 5;

function myClosure (y) {
  return x + 1;
};

console.log(myClosure(10)); // 6

JavaScript has function scope; the definition of a new function creates a new scope. But if a reference to an identifier is not found within the local scope, the next outer scope is consulted and so on until it is either found, or a ReferenceError is raised. We could prevent this for example by shadowing the variable name by naming it in the parameter list:

1
2
3
4
5
6
7
var x = 5;

function myClosure (x) {
  return x + 1;
};

console.log(myClosure(10)); // 11

Notice how in the above snippet, we cannot close over the outer x? This is called variable shadowing. In JavaScript, no matter if you use a function definition or function expression to define a function, as long as you do not shadow a particular variable, then you may close over it.

Let’s see how Ruby handles closures.

1
2
3
4
5
6
7
x = 5

def my_closure y
  x + 1
end

puts my_closure 10 # NameError: undefined local variable or method `x' for main:Object

Oops. Looks like Ruby doesn’t support closures! But I thought it was supposed to be easier to write than Java! Well, it turns out Ruby does support closures, it just has an alternate syntax for functions that close over references to variables in the outer scope. This alternate syntax actually creates a new object containing the captured scope. Lets take advantage of Ruby’s lambdas to close over variables:

1
2
3
4
5
6
7
x = 5

my_closure = -> x do
  x + 1
end

puts my_closure.call 10 # 6

Note, we could have also used the older lambda syntax, or even a Proc object. I won’t cover the difference between the two here; there are better blog posts on the differences. My point is that not all languages support closures with their default function declaration syntax (like in JavaScript). This provides a nice syntax into closures in Rust.

1
2
3
4
5
6
7
8
9
fn main () {
  let x: int = 5;

  let my_closure = |_: int| -> int {
    x + 1
  };

  io::println(fmt!("%d",my_closure(10))); // 6
}

Note: Rust has some really nice type inference. We can write the previous snippet more succinctly:

1
2
3
4
5
6
7
8
9
10
11
fn main () {
  //let x: int = 5;
  let x = 5;

  //let my_closure = |_: int| -> int {
  let my_closure = |_| {
    x + 1
  };

  io::println(fmt!("%?",my_closure(10))); // 6
}

It might seem obvious that my point about different languages having different syntaxes. I guess a better stating of that point is that closure definitions in Rust differ from vanilla function definitions like Ruby and as opposed to JavaScript.

Rust aims to be a systems level programming language to replace C and C++. With closures, type inference, and a syntax that faintly reminds me of Ruby’s block lambda syntax, I’ll take it!