Don't ask me, ask the code

How many times did you find yourself in an argument about whether or not a certain detail in some programming language or framework was implemented in a certain way? I’m talking about questions like these ones:

I find myself in short discussions about similar things quite a lot. And the thing is that I can look up anything I want in the docs, I can explain it later to my colleagues or friends, but often they’ll ask me “Are you sure?” or try to counter my point with something from their prior experience.

Such discussions are great for learning for both sides. But not always there should be a discussion at the first place. Can a JS promise be rejected after resolution? This is not up to me to decide. But it’s up to me to check it.

I found a way to resolve such arguments in a very quick way that doesn’t leave much for interpretation. I implement the situations in such questions and let the code find the answer.

Below is a short piece of code I wrote to demonstrate that a promise can be only settled once:

// you can copy the code into browser's console
const p = new Promise((fulfill, reject) => {
	setTimeout(reject, 1000);
	fulfill();
});

p.then(() => console.log('fulfilled!'))
	.catch(() => console.log('rejected!'));

It prints fulfilled! and nothing more. It is not a theory, it is not my ability to remember things from documentation, not an assumption. It is code that works in a certain way, and you cannot argue with that.

Another example of a similar discussion happened to me while working on a project written in Go. I saw a potential issue with some floating point related code, brought it up, and instead of trying to explain why floating point operations are hard, I wrote a very short piece of code that did so for me:

package main

import (
	"fmt"
)

func main() {
	fmt.Println(0.3 - 0.2)
	fmt.Println(0.3-0.2 == 0.1)
}

// prints
// 0.1
// false

It was very easy to prove my point by demonstrating it in action. It could be very hard to explain the logic behind it.

My point is that it is very easy to write short pieces of code. You don’t even have to open up an editor! I can’t recall even a single time where I needed an actual file. JS question? Let me open Chrome’s developer console. Python? Wait, here is my bpython binary. Some old PHP related problem? psysh is right here in my shell. Go? There is an online playground for that.

Once you have your proof, it’s very easy to build on top of that to explore the problem further. You can play around with the code you just wrote, and turn it into a great learning opportunity. Whatever it is you will find out, you’ll probably remember it better than if you’ll read it somewhere or hear from someone.

So, don’t ask me, ask the code itself.