A TEXT POST

What if return was callback()?

In JavaScript, you have the return statement which synchronously returns a value for a function. Asynchronous functions usually has a callback that it calls when it has a value to return. Some async functions call that callback more than once (streams).

What if JavaScript had a return statement that was asynchronous? At first this doesn’t if make sense; that would block execution. No, what I’m saying is, what if JavaScript was smart enough to know which code depended on a returned value from a function. Then instead of this:

fs.readFile('foo.txt', function(err, file){
  console.log(file);
});
console.log("reading file");

You would write code like this:

console.log(fs.readFile('foo.txt'));
console.log("reading file");

JavaScript would just need to be smart enough to know that the first console.log statement depended on the output of fs.readFile whether it returns synchronously or not.

A TEXT POST

How JavaScript Inheritance could have been

JavaScript could have been so much more simpler if it had just one extra thing, and got rid of the new operator, and here’s why.

function Animal(name){
    return {
        parent:: Animal.blueprint,
        name: name
    };
}

Animal.blueprint = {
    name: 'unknown',
    speak: function(){
        alert("Grrrrrrrrrrr!");
    }
};


var instance = Animal('bob');

instance.speak(); // "Grrrrrrrrrr!"
instance.name === 'bob'; // true


function Human(){
    return {
        parent:: Human.blueprint,
        name: name
    };
}

// Human blueprine
Human.blueprint = {
    // Inherit from Animal
    parent:: Animal.blueprint,
    speak: function(){
        alert("Hi, I'm " + Human.blueprint.name); // Notice that Human.blueprint.name isn't defined, but inherited from Animal.blueprint
    }
}


// Or you could have used a syntactic surgary method to extend

Human.blueprint = extend(Animal.blueprint, {
    speak: function(){
        alert("Hi, I'm " + Human.blueprint.name);
    }
});


function extend(parent, child){
    child..parent = parent;
    return child;
}


var instance = Human('bob');

instance.speak(); // "Hi, I'm bob!"
instance.name === 'bob'; // true

Above you’ll notice this weird object literal syntax where you have two colons instead of one. And you’ll also notice two dots for property accessing instead of one. What is this? Well, first let’s talk about the infamous prototype in JavaScript.

The prototype of an object is another object that the JavaScript engine keeps track of for each object. It’s stored in what the ECMAScript standard calls “slots”. Whenever a property isn’t found in an object, the JavaScript engine looks at the object’s prototype for the property, and if it’s found returns the value, otherwise it looks at the prototype’s prototype, and repeats the process on and on up the prototype “chain” until it finds a defined property or doesn’t find one at all.

These slots are hidden from the programmer, however some non-standard implementations of a __proto__ property for each object have made the prototype slot accessible. This is bad for one reason which I’ll get to later. But, there is a reason why I think being able to explicitly access and define a slot is a good idea.

Which brings me back around to the double colons and dots. If you could define object “slots” or “meta properties” on an object, then we’d have the power of __proto__ without the bad part, which is: the properties for an object would be clear of any implementation details, therefore you could still use obj.__proto__ for your own uses without effecting the object’s meta data.

Great, so let’s talk about naming conventions. The whole purpose of the prototype is so objects can inherit properties from other objects. So why call it prototype? Well, it fits the definition, but I say it doesn’t have to be a technical word the newcomers have to learn and understand (I believe the name itself acts in part of the confusion to learning JavaScript). I would purpose that the object’s prototype be called it’s parent. So instead of obj..prototype = otherObject, it would be obj..parent = otherObject. “parent” is easier to type and feels cleaner.

So what about the new operator, why get rid of it? Well, all it does is call a function with this bound to the function’s prototype property and returns this. I bet that if you’re struggling with JavaScript, you didn’t understand a lick of what i just said, or at least it took you a while to wrap your head around. I say we don’t need all this confusion. I say you give access to the meta properties (slots) of an object to the programmer and let them define what the parent meta property should be of an object for inheritance. Done.

Now we could add sugar and conventions to our code that would mimic whatever new operator pattern that was trying to be mimic from Java in the first place. All we’d need is a function that returns an object with a defined parent.

function newMyObject(prop) {
  return {
    parent:: newMyObject.blueprint, 
    property: prop
  }
}

newMyObject.blueprint = {
  property: "Default value"
}

var instance = newMyObject();

Remember that :: means define a meta property, in this case the parent meta property.

We call it newMyObject as a convention for “constructor functions” like this. We could follow another convention where we just make the first letter of the identifier uppercase, i.e. “MyObject”.

What’s newMyObject.blueprint? Another convention. It’s just a property of newMyObject that’s used to define the parent object of each instance that newMyObject returns. We could have called it newMyObject.prototype or newMyObject.parent, but I feel like either of those would have been confusing. The identifier blueprint seems to convey what it’s trying to accomplish, which is to be the blueprint for each instance.

In classical OO programming we have these “classes” that act as blueprints to instances. In a similar way, we have an object that acts as a blueprint to instances. There are no classes in JavaScript, just objects. So this convention makes more since to a classical OO programmer. However, the coder is not limited to using these conventions.

So. All this makes it simpler, because now when you teach JavaScript to people, all they need to “get” is the meta properties and specifically the parent meta property. Once they understand this concept, they can go ahead a recklessly create any objects and patterns to their hearts content. However, you might want to teach them some good practices and patterns.

Look at the above code at the beginning of this post for another pattern that people could use, the extend function. Go a head and see if you could figure it out on your own because I already taught you about the parent meta property. The extend function isn’t needed though, it’s just some syntactic sugar.

Final note: Whether meta properties should be constant or not is subject to good discussion. I personally think that meta properties should be variable, but there may be good reason to making your script error out if you attempt to define an already defined meta property. Let me know what the argument for constants is.

A PHOTO

Lesson I should learn: Use MySQL as little as possible.

Too much time has been wasting trying to “figure out how to do it in MySQL”, under the assumption that this would make my application better/faster. No! I shouldn’t think like this anymore. Do everything in the application land (business logic); just ask query as simply as possible, get in get out. MySQL, move out the way BITCH!

A PHOTO

comics0026:

sam-holmes:

comics0026:

A riddle I came up with. It can be a bit of a stumper. I’ll post the answer later today.

The answer, I would presume, is any number, so long as you add a negative.

Let me know if I am correct, comics0026.

While technically correct, it’s not the answer I’m looking for. :)

What is the answer you’re looking for?

A QUOTE

I find that nodemon is faster than supervisor for me.

A PHOTO

comics0026:

A riddle I came up with. It can be a bit of a stumper. I’ll post the answer later today.

The answer, I would presume, is any number, so long as you add a negative.

Let me know if I am correct, comics0026.

A QUOTE

eta oin shr

A TEXT POST

A Happy, Bitcoin Birthday!

So my birthday is coming up next month on May 5th, and I had this idea to publish a bitcoin address that would act as a birthday fund. I will use the funds to throw a little party with friends and family for my 22nd birthday!

So feel free to wish me a happy birthday! I appreciate your generosity, and I look forward to seeing how this goes. Thanks! :)

1PtieW8G2KA1CoENFayk1JxJEwBSpxi4p2

Balance

A TEXT POST

Are you selfish?

Why not challenge the status quo?

Are you selfish? Most wouldn’t like to answer yes to this question, but that’s only because it’s not desirable to have this quality. But here’s the definition:

Adjective.
(of a person, action, or motive) Lacking consideration for others; concerned chiefly with one’s own personal profit or pleasure.

I think if we really were to evaluate ourselves and determine whether we fall under this definition, we would find that we are at least somewhat selfish, but we would be okay with it. Relatively speaking, if most people are selfish to a common extent, then it wouldn’t be a bad thing; you would be normal (of the norm), at least not for simply being abnormal.

To be selfish is to be lacking consideration for others. Are we not doing this all of the time? Say we go to a Starbucks to buy a cup of coffee and a lunch item. A lot of the time (at least where I live), you’ll come across a homeless person. This homeless person would probably want a cup of coffee and a lunch item too. So, why not ask him if he does. If he says yes, then the selfless thing to do would be to get him one. In fact, you could even explain to the person behind the Starbucks register that this homeless person would like something but doesn’t have the money for it. The selfless thing to do for the barista would be to give the homeless person something(s) at no charge.

Yet, this rarely (if at all) happens because everyone is looking out for their own self interest (they’re technically selfish). The barista wouldn’t want to lose their job. You probably wouldn’t want to give your money away to every person in need (you couldn’t physically handle the demand). If we all take care of ourselves, then that requires us to be focused on the self, and focused on selfish things.

Looking at the the word “selfish” in this way, makes us realize that it isn’t such a bad word after all. Maybe next time when someone calls you selfish, you’re immediate thought or response could be “Aren’t we all?” But maybe they’re calling you more selfish or selfish to an extreme extent from the norm. In this case, ask whether you’re extension from the norm is bad. Challenge the status quo as to why it’s bad to be more selfish than usual. Maybe you’re being selfish for a good reason (i.e. there is valid rationale behind your decisions).

In no way am I suggesting that it is never bad to be overly selfish. The purpose of this post is to explain how it’s not always bad, nor is it always good. Things aren’t black and white, yet this is how we all tend to believe because of how we’re influenced. Think differently; we discover more this way. Thanks!

A TEXT POST

Natural Async Programming (cont’d) – Signal-Oriented Programming

This is a follow up post to Natural Async Programming

Giving my thoughts more thought, I realized a concept that could change everything. Something that OOP did for the Macintosh era, could do for our era–the async revolution. I looked into some things such as Flapjax and Elm, and I discovered an idea that I’d like to define in this post, signals. Not signals in the Elm sense specifically, but signals in my own definition.

First, let’s talk about event emitters. Event emitters can emitter any number of events, and handlers can be attached to these events and be invoked when the events are emitted. This is very powerful, but in JS, this is all done with callbacks:

emitter.on('event', callback);
...

Now, I’d like to define a signal as a lower level form of event emitter, but rather than a collection of events, it is a single event, a single signal. Signals, however, are not done with callbacks. They’re handled automatically by the interpreter:

var signal = createSignal();
data = signal;

createSignal is just an example of a function that would create a new signal; signals are more ubiquitous that having a single interface for creating signals, i.e. an async function could return a signal.

The idea is that a signal is a value that changes over time. The value is used as you would any value, but the code is re-evaluated when the signal changes. This is analogous to an event being emitted.

In fact, data is a signal too; everything is a signal! Just like in OOP, everything is an object, in SOP (signal oriented programming) everything is a signal!

But if everything is a signal, then wouldn’t this get confusing when everything is changing? No, because some signals are static, and don’t change. If I create a function that just returns the number 23, that’s a static signal.

Back to the comparison to signals and event emitters. Event emitters in a signal-based language would just be a collection of signals:

emitter.event1;
emitter.event2;
...

These signals can change, reacting to these signals is as simple as just using them. But, sometimes you’ll want to be able to just do something when a signal changes. Well, you just use the signal, and that code will be evaluated on signal changes. So you could just do an if statement:

if (signal)
{
...
}

Though, sometimes in JS, you might have callbacks that don’t have values passed to them (like setTimeout/Interval). In these cases, if (signal) would evaluate to false because the value would be undefined in the signal. To solve this, there should be a statement just for handing signal changes:

when (signal)
{
...
}

It doesn’t have to be named when, it could be named on or change even.

Signal-oriented programming allows us to use all the power that functions give us but without the functions! Instead you just declare what happens in your program and when your program has signal changes, it responds. It’s a very enticing idea, isn’t it?

But, sometimes you don’t want to respond to a signal any longer. Take setInterval for example. If you had a similar function, interval that takes an integer for milliseconds as input and returns an undefined value for every signal change on that interval, you wouldn’t be able to clear this interval because there is no ID number to use to clear it. However, there is the signal itself, so all you need is a function that could kill the signal:

var intervalSignal = interval(1000);
when (intervalSignal)
{
  var num = Math.random();
  if (num*100 < 23)
    kill(intervalSignal);
}

The kill function will deallocate/garbage collect anything that is envolved with a signal. This function is probably unnecessary, because you could just use delete to delete the variable itself, but maybe kill() can do something more that delete doesn’t do (i.e. stop all variables that reference the signal from receiving changes, or maybe keeping the value of the signal without allowing it to change further).

In conclusion, I think the idea of Signal-Oriented Programming should be the next hot topic for programming language semantics. I personally think, signals, or something like it, could change the way we program, and the way we think about how computers work, forever.

A TEXT POST

Natural Async Programming

JavaScript has really taken asynchronous programming mainstream, but some of the lessons we’ve learned along the way is that async is different. Rather than the usual linear program flow, you have these callbacks which can be nested or managed by a control flow lib. However, what if we dreamt something more natural for async programming, because async is awesome and it deserves it.

Promises is the idea that an async function returns an object which handles the outcome of an async action. I like this concept because you’re using the return statement where it should be used (output). Inversely, callbacks seem backwards: you use the input to handle the output of a function (how backwards). However, promises are still callbacks, just nicer.

I wondered then, what would it be like if we had async built into a language? How could this work? Could it even work? Let’s hypothesize.

Say the return statement was asynchronous in that the function would wait until it is used before it returns output:

function af(){
  return setTimeout(function(){
    return 'done';
  }, 1000)
}

Here, setTimeout returns what the callback returns, but it is async so it doesn’t return ‘done’ immediately. This is interesting, but the language would have to know which parts of the code depend on other async operations.

var foo = af();

if (foo === 'done')
{
   alert('second');
}

alert('first');

Sense the if-statement depends on foo, then the if statement is put on hold before, and the alert('first') statement is executed.

This will make parallel async and serial async almost invisible to the programmer:

// parallel invocation
var a = async();
var b = async();
doSomethingWith(a, b); // Final results

// Serial invocation
var a = async();
var b = doSomethingWith(a);
doSomethingWith(b); // Final results

Some more examples to get used to how this works:

var done = sleep(2000);
if (done) {
  alert('Done sleeping!');
}
alert('Sleeping');

var posts = db.query("select * from posts");
var comments = db.query("select * from comments");

// This next statement is using the pending variables
// so it will be queued until for later, automatically
res.render('template', {posts:posts, comments:comments});

// This will run before the above because it's not depending 
// on the async pending variables
Analytics.push(request);

Somehow, this could be possible with it being implemented at the interpreter level. Could it be done?

A TEXT POST

Mac OS X Mountain Lion Feedback

Here’s a compilation of the various things I suggest Apple fixes in Mac OS X. I’ll be adding to this list over time. (Warning, it gets very whiny)

  1. In a fullscreen app, the menu bar shouldn’t appear until you move your cursor past the top most pixels. This is how the dock works for the bottom most pixels. It’s so annoying to have the menu bar get in your way when you mean to click on a tab in Terminal.

  2. 1st Desktop should be closable/sortable.

  3. NO. That’s directed toward waiting for the close button on desktops or needing to hold Option to show the close. Make this easier to do.

  4. Trackpad gestures shouldn’t require that you lift your hands off the trackpad before you could initiate another gesture. For example, swipe up with three fingers to go into mission control, then swipe left and right to switch desktops, then pull back down to exit mission control.

  5. You don’t need to move your cursor in order to click on a window in Mission Control. Right now, swipe up with three fingers. Now click on the window directly under your cursor. Nothing will happen, because OS X is being stupid. You need to move your mouse until a blue highlight appears around the window before you can click on it. So stupid.

  6. Please squish bugs; I’m on a Mac right, not a PC? When I open mission control while an application is launching, the app will appear over mission control, not with it. And if I close an application while in mission control, well: http://cl.ly/image/0d2s2P3q1A1d

  7. I want my RAM back.

A TEXT POST

Error Handling in Async Programming – Help

How do I spend less time worrying about errors and more time focusing on what my functions actually do? I have these model files which are a collection of functions that accept an info object and a callback function. When something is missing, but required, in the info object, I error out calling the callback with new Error('missing info.something'). It’s not very DRY because I have to write the same if (!info.something) in my model functions whenever I choose to create a new function. But, I have to do it in order for my application to spit out meaningful error messages. This is the problem with async programming, at least for me.

Does anyone have any solutions to this? One where I wouldn’t have to worry about error handling; if something goes wrong, then my app will give a meaningful error (critical errors would crash the app, non-critical would just give a HTTP 500 status code).