joelwallis
joelwallis
joelwallis.com
58 posts
Full-stack Web developer. Working with/for the Web since 2005.
Don't wanna be here? Send us removal request.
joelwallis · 9 years ago
Photo
Tumblr media
“Can you check the database server for me? I think it’s a database problem.”
62 notes · View notes
joelwallis · 9 years ago
Photo
Tumblr media
Meu Carnaval 2016 tá sendo com rock e muito #JavaScript! \o/ #Spotify (em João Pessoa, Brazil)
1 note · View note
joelwallis · 9 years ago
Photo
Tumblr media
em João Pessoa, Brazil
0 notes
joelwallis · 9 years ago
Photo
Tumblr media
No more googling #gulp commands anymore! #nodejs (em João Pessoa, Brazil)
2 notes · View notes
joelwallis · 10 years ago
Photo
Tumblr media
Ensinando #Shell Scripting à @julliaaathayde (em João Pessoa, Brazil)
0 notes
joelwallis · 10 years ago
Photo
Tumblr media
0 notes
joelwallis · 10 years ago
Text
Good post from Isaac Z. Schlueter about making good API interfaces.
Designing APIs for Asynchrony
New 2014-06-30: You can contain Zalgo with the dezalgo module
Some people asked me to explain what I meant by “releasing Zalgo” in async APIs, so I thought I’d share the following guidelines.
Please follow all of these rules in your programs. If you deviate from them, you do so at the peril of your very sanity.
Get Over Your Provincial Boilerplate Preferences
Personally, I don’t actually care all that much about the whole promises/callbacks/coroutines/generators debate. It’s provably trivial to turn any callback-taking API into a promise-returning API or generator-yielding API or vice-versa.
I’m of the opinion that breaking functionality into small enough chunks that your boilerplate doesn’t matter is much more important than which boilerplate you decide tastes the yummiest. In JavaScript, we have first-class language support for passing functions around, so I tend to use callbacks, simply because it requires no extra “stuff”.
What’s important to me is that an API be useful, performant, and easy to reason about. When I’m writing JavaScript, I care a lot about how V8 is going to optimize it, and so try to choose patterns that it can optimize nicely. As of today, generators just aren’t first-class enough, and Promises require an extra abstraction. That may change someday, but these principles probably will not.
So, I’m going to say “callbacks” below, but you can mentally substitute whatever thing you like. The fundamental points are equally relevant if you’re using threads, or gotos, or any other abstraction or language for doing things asynchronously and controlling what the computer does next.
Note that all of this also applies if your asynchronous API “looks synchronous”. Even if you design a thing so that I do:
x = foo();
and it’s completely agnostic at authoring time whether foo() spins on CPU or yields while it awaits a network response, being able to reason about the program means that I need to be able to know whether other parts of the program will be running while I’m waiting for foo() to return a value to be put into x.
So, even if the syntax is the same (which has its benefits as well as its drawbacks, of course), the semantics must be crisply defined.
Or else Zalgo is released.
Do Not Release Zalgo
Warning: Before proceeding any further, go read this excellent essay by Havoc.
If you haven’t read Havoc’s post on callbacks, then you will perhaps be tempted to make silly arguments that make no sense, and demand justification for things that have been established beyond any reasonable doubt long ago, or tell me that I’m overstating the issue.
Have you read Havoc’s post on callbacks? Yes? Ok.
If you didn’t, shame on you. Go read it. If you still haven’t, I’ll sum up:
If you have an API which takes a callback, and sometimes that callback is called immediately, and other times that callback is called at some point in the future, then you will render any code using this API impossible to reason about, and cause the release of Zalgo.
Needless to say, releasing Zalgo onto unsuspecting users is extremely inappropriate.
It’s not the case that function-taking APIs must always call the function asynchronously. For example, Array.prototype.forEach calls the callback immediately, before returning. But then it never calls it again.
Nor is it the case that function-taking APIs must always call the function synchronously. For example, setTimeout and friends call the callback after the current run-to-completion. But they always return before calling the callback.
In other words, to avoid the release of Zalgo, exactly one of the following must be true:
var after = false; callbackTaker(function() { assert(after === true); }); after = true;
OR:
var after = false; callbackTaker(function() { assert(after === false); }); after = true;
and in no case can you ever have a function where exactly one of these assertions is not guaranteed.
What about internal functions in my library that are not exposed?
Well, ok, but you’re releasing Zalgo in your internal library. I don’t recommend it. Zalgo usually finds a way to sneak His Dark͝ Tend̴r̡i҉ls out into the world.
What if I suspect that a function might try to release Zalgo?
This is a great question. For example, perhaps you let users supply your library with a callback-taking function, and you worry that they might be incompetent or careless, but want to ensure that your library does its best to keep Th͏e Da҉rk Pońy Lo͘r͠d HE ́C͡OM̴E̸S contained appropriately.
Assuming that your platform has an event loop or some other kind of abstraction that you can hang stuff on, you can do something like this:
function zalgoContainer(cbTaker, cb) { var sync = true; cbTaker(cbWrap); sync = false; function cbWrap(er, data) { if (sync) process.nextTick(function() { cb(er, data); }); else cb(er, data); } }
This uses Node’s synthetic deferral function: process.nextTick, which runs the supplied callback at the end of the current run-to-completion. You can also use setImmediate, but that’s slightly slower. (Yes, yes, it’s named badly; setImmediate is slightly less “immediate” and more “next” than nextTick, but this is an accident of history we cannot correct without a time machine.)
But isn’t it faster to just call the callback right away?
Go read Havoc’s blog post.
Moving on.
Avoid Synthetic Deferrals
I know what you’re thinking: “But you just told me to use nextTick!”
And yes, it’s true, you should use synthetic deferrals when the only alternative is releasing Zalgo. However, these synthetic deferrals should be treated as a code smell. They are a sign that your API might not be optimally designed.
Ideally, you should know whether something is going to be immediately available, or not. Realistically, you should be able to take a pretty decent guess about whether the result is going to be immediately available most of the time, or not, and then follow this handy guide:
If the result is usually available right now, and performance matters a lot:
Check if the result is available.
If it is, return it.
If it is not, return an error code, set a flag, etc.
Provide some Zalgo-safe mechanism for handling the error case and awaiting future availability.
Here’s an silly example to illustrate the pattern:
var isAvailable = true; var i = 0; function usuallyAvailable() { i++; if (i === 10) { i = 0; isAvailable = false; setTimeout(function() { isAvailable = true; if (waiting.length) { for (var cb = waiting.shift(); cb; cb = waiting.shift()) { cb(); } } }); } return isAvailable ? i : new Error('not available'); } function waitForAvailability(cb) { // Could also defer this and just call it, // but it is avoidable, which is the point. if (isAvailable) throw new Error("hey, dummy, check first!"); waiting.push(cb); }
In this case, when the user calls usuallyAvailable() they’ll get a number between 0 and 9, 90% of the time. It’s on the caller to check the return value, see if it means that they have to wait, etc.
This makes the API a bit trickier to use, because the caller has to know to detect the error state. If it’s very rare, then there’s a chance that they might get surprised in production the first time it fails. This is a communication problem, like most API design concerns, but if performance is critical, it may be worth the hit to avoid artificial deferrals in the common cases.
Note that this is functionally equivalent to O_NONBLOCK/EWOULDBLOCK/poll pattern. You try to do a thing, and if it is not available right now, it raises an error, and you wait until it IS available, and then try again.
If the result is usually available right now, but performance doesn’t matter all that much
For example, the function might only be called a few times at startup, etc.
In this case, just follow the “result is usually not available right now” approach.
Note that performance actually does matter much more often than you probably realize.
If the result is usually not available right now
Take a callback.
Artificially defer the callback if the data is available right now.
Here’s an example:
var cachedValue; function usuallyAsync(cb) { if (cachedValue !== undefined) process.nextTick(function() { cb(cachedValue); }); else doSomeSlowThing(function(result) { cb(cachedValue = result); }); }
The basic point here is that “async” is not some magic mustard you smear all over your API to make it fast. Asynchronous APIs do not go faster. They go slower. However, they prevent other parts of the program from having to wait for them, so overall program performance can be improved.
Note that this applies to not just callbacks, but also to Promises and any other control-flow abstractions. If your API is frequently returning a Promise for a value that you know right now, then either you are leaving performance on the table, or your Promise implementation releases H̵͘͡e ̡wh́o͠ ̶Prom̀͟͝i̴s̀es̀ o҉̶nl̨͟y̧ ̛̛m̴͠͝a̡̛͢d̡n̴̡e͝s̸s͠, T̢҉̸h̴̷̸̢ȩ͡ ͘͠N͢͢e͏͏͢͠z̛͏͜p̸̀̕͠ȩ́͝͝r҉̛́͠d̴̀i̴̕҉͞a̴̡͝͠n̢͜͟͢͟ ̶̴̢͝h̷̕͠í̸̧̛͜v̶̢͢͡e̕͡-̸̀͝m̷͜i̛͘͞ņ̛͘͟҉d̶̶̡̧͜ ̷̛͞o̵̢͘͟͞f̶̢̀͢͢ ̶̧͟͡c̕͝h̶̀͘͘à͏o҉̴́͢s̸͘͘͝͞.̨͢͞.
So, don’t do that.
Pick a Pattern and Stick With It
This really cannot be overstated. Like the question of callbacks vs Promises vs whatever, the specific pattern that you choose doesn’t matter very much. What does matter very much is that you stick to that pattern with ruthless consistency. The pattern should cover how a user interacts with your API, and how errors are communicated.
In Node.js, the callback pattern is:
Async functions take a single callback function as their final argument.
That callback is called in the future with the first argument set to an Error object in the case of failure, and any additional results as the subsequent arguments.
Why have the callback as the last argument? Why make Error the first arg? It doesn’t really matter very much. Ostensibly, making the callback the last arg is because
doSomething(a, b, c, d, function(er) { ... })
scans a bit better than:
doSomething(function(er) { ... }, a, b, c)
and putting the error first is so that it’s always in the same place.
There were other choices that could have been made. But the important thing was just to pick one, and move forward with it. This consistency makes it much less difficult to convert Node APIs into other sorts of aync patterns, and greatly reduces the communication required to tell a user how to use a Node.js callback-taking API.
60 notes · View notes
joelwallis · 10 years ago
Text
Hour of Code shirts and more
With more than 70,000 Hour of Code events planned around the world, there are exciting things coming soon! We want to help schools host the best Hour of Code possible and often get requests for Hour of Code shirts to celebrate throughout your school, club, company or whole community. If you want Code.org hats, shirts, hoodies and stickers, get them here. 
You can also now customize Hour of Code shirts for your event. First, choose one of two designs. Choose either this design,
Tumblr media
or this one. 
Tumblr media
Then, customize your shirt. 
Click “Edit This Design” Step #1,  Click “Your School” on the Image to select the text Step #2,  Edit the text in the “add text” box on the left panel and click Update. If your school or organization name is long, you can resize the text or change the font on this tab. Step #3, Click “Save/Send” to send the design to yourself and order from there. Step #4, Shirts will be on their way to your Hour of Code! Please allow 2-3 weeks for production and delivery.  All orders will be handled directly through CustomInk.
Tumblr media
12 notes · View notes
joelwallis · 10 years ago
Photo
Tumblr media
<3 <3 <3
0 notes
joelwallis · 10 years ago
Text
20 dias de Node.js
TD;DR: estou em um desafio pessoal: estudar por uma hora um trecho da documentação do Node.js durante vinte dias, e escrever sobre isso no blog.
O quê?
Bem, eu precisava estudar Node.js (lê-se: estudar todo e cada módulo nativo, além de escrever códigos de exemplos para fixar bem o conhecimento), mas, cadê tempo livre para isso? E foi daí que veio a ideia de estudar uma hora por dia. Eu já fiz isso quando tinha uns 18~19 anos e estava aprendendo PHP. Havia ganho o livro PHP: a Bíblia de um amigo e decidi ler um capítulo por noite. Resultado? Aprendi PHP, definitivamente.
OK, mas você deve ter perguntado: "mas por que vinte dias?" Bem, é simples: a API do Node.js contém 38 tópicos. Considerando que eu posso ler até 2 tópicos por dia isso resulta em 19 dias. Arredondei pra cima, pois no final quero escrever no blog sobre os resultados do método de estudo.
Como?
Criei um evento no Google Agenda para hoje e configurei a recorrência para todos os dias da semana durante quatro semanas (cada semana tem cinco dias úteis), no horário de 22h às 22h50, com notificação de aviso às 21h. Dessa forma não terei como praticar autosabotagem mesmo! rs
Vamos ver o que vai rolar nessas quatro semanas de estudos! :-)
0 notes
joelwallis · 10 years ago
Link
Nessa matéria a galera do Instagram mostra uma ótima de otimização de uso de armazenamento de dados com Redis para armazenar 300 milhões de dados chave-valor do stack deles. Vale muito a pena ler! :D
0 notes
joelwallis · 10 years ago
Text
Open Source is the best Code Review
One of my colleagues was just about to start a new small project we needed to complete that is probably needed in a lot of companies. We just introduced better code reviews and I thought it would be great if this would be reviewed by a lot of people.
So I asked:
“Could we open source this?”
I believe writing code you know will end up in front of the entire world really keeps you from cutting corners. You follow best practices. You pay attention to the small details. It makes your code better. It makes you better.
He decided that it would be a good idea to do so and he did. The outcome was great and we all had fun creating it. We also learned a bunch of new things on the way.
So when in doubt, just open source it.
3 notes · View notes
joelwallis · 10 years ago
Text
PHP com suporte a PostgreSQL no Mac OS X
Desde sexta-feira que estava nessa luta: adicionar suporte ao PostgreSQL à minha instalação PHP powered by Homebrew no Mac OS X. Eu literalmente não queria mudar a forma como o PHP estava instalado pois a comodidade de instalar extensões via Homebrew vale o esforço em contornar esse problema.
Solução? Reinstalar o PHP com a flag --with-postgresql
Simples assim! :) Veja como:
brew reinstall php54 --with-postgresql
Caso você não tenha o PHP instalado, basta faer a instalação com a flag indicada:
brew install php54 --with-postgresql
0 notes
joelwallis · 10 years ago
Photo
Tumblr media
Fifteen minutes before the deployment
90 notes · View notes
joelwallis · 10 years ago
Photo
Tumblr media
Science proves that experiences are of higher value than material possessions. Read more about the study on our blog and get out there and Couchsurf! 
18 notes · View notes
joelwallis · 10 years ago
Photo
Tumblr media
O Rio da janela da barca Rio-Niterói. #nofilter
0 notes
joelwallis · 10 years ago
Photo
Tumblr media
Comprei meu meio de transporte :-) #galeriadorock #sp #longboard (em Galeria do Rock)
0 notes