Inadequacies of typed JavaScript
Some things can’t really be fixed :-(

The last week I have been playing extensively with both flow and TypeScript. And I have noticed two things that I consider to be bugs in both of them. So is there something wrong with my expectations maybe? Lets analyze both of the cases.

non-nullable class members

TypeScript (TS) introduces non-nullable types with version 2, and flow has had them for quite a while I think. There have been tons of stories about how bad the null type/value is. Some call it the worst mistake in computer science. And indeed, most of the errors we have at runtime are related to null. Accessing properties of null, or calling null. Having to check values for null all the time is tedious and as the runtime errors prove, null can slip through at all kinds of places.

It is even worse in JavaScript because it does not have one null type but actually two: null and undefined. To make things worse typeof null === "object" and typeof undefined === "undefined, so you can’t even check for both cases at the same time; well actually you can use value == null since that also works for undefined. Go figure.

To make more worse still, JS also has boolean coercion. Which itself can be convenient, but you can very easily trip up. If you have a value that has the type number | null, using a simple if (value) will fail for the value 0. Probably not the thing you intended. And you will get it wrong at some point. I have done so over and over again.

So, to come back to the topic at hand. Both flow and TS now prevent you from tripping up on most of the null issues, except for the boolean coercion. But both of them get one case wrong:

1
2
3
4
5
class A {
prop: string;
}
const a = new A();
a.prop.length; // typechecks just fine, fails at runtime

This simple code will typecheck just fine in both flow and TS, but will fail at runtime with a TypeError because you are accessing a property on null. I have reported this on the TS issue tracker but it was closed as a duplicate of a wontfixed issue. Apparently it is too difficult to correctly cover all the different ways in which constructors can behave.

As far as I see it, the root of the problem is twofold. First, JS objects were never meant to have a guaranteed shape, its only these type checkers that kind of try to enforce those things. And the second problem is that JS constructors work by assigning/creating properties on this, which can be aliased or delegated to other functions, etc…

In other languages with stricter guarantees, such as Rust, you do not have this or constructor functions at all. The language itself guarantees that creating an object of a certain type is atomic via an object literal that is guaranteed to include all properties. (You can still use object spread for convenience)

Ideas to solve the Problem

Both flow and TS can hold up the typesystem guarantees if you are using object literals instead of classes. Use plain functions and object instead of classes. I have heard that one before. The whole functional programming crowd advocates this. Maybe they have a point? But I do like having methods on objects/prototypes. So maybe we can combine object literals that are correctly checked for null properties with methods somehow. Well there is this special __proto__ property that was specified for ES2015. I tried using it with TS, but failed. The method works perfectly in JS, but typechecking in TS fails. Well unless I want to copy every method into the object, which completely defeats the purpose of shared prototype methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type A = {
a: string,
};

function A(a: string): A {
return {
__proto__: AProto, // can’t assign to unknown property
a,
};
}

const AProto = {
method(this: A) {
return this.a.length;
}
};

const a = A("a");
a.method(); // can’t call unknown method

So no luck here :-(

Aliasing literal / union types

Both flow and TS have the notion of literal types and union types. Union types are really simple. The type A | B can either be A or B. But since those are not native to JS, you have to have some way to actually assert the type at runtime. For primitives its easy, since you can just check via typeof. But discriminating objects needs to be done manually with a property used to tag the object. In the following example, U is such a union type and it can be discriminated by looking at the type property. And here we are actually using strings as types: literal types. So in this case U.type has the type "a" | "b", so it can either be the string "a" or "b", but nothing else.

1
2
3
type A = {type: "a", propA: string};
type B = {type: "b", propB: number};
type U = A | B;

Both flow and TS handle these things quite well. If you use .type in a switch or if statement, you can match for the exact type. But both typecheckers fail if you want to alias that property, for example via destructuring: const {type} = X;. Here, the type of type is widened to string and it can no longer be used to discriminate the union type. I also reported this in the TS issue tracker and got the answer that is would be two complicated to implement this, because it would involve tracking the dependency between the two variables, increasing the depth of the dependency as more aliases are added.

Well at least this can be easily fixed by just always using the property instead of extracting it into a local.

Closing remarks

I wish one of the compile-to-js languages would actually support real union types and has a real match expression. Automatically tagging variants or even supporting null-pointer optimization so you don’t have to have unnecessary indirections if a simple typeof check would be enough.

There are already compile-to-js languages that support things like this. For Example Elm and PureScript (both based on Haskell). And possibly ClojureScript, even though I know too little about that language. With the recently released BuckleScript, you can also compile OCaml to JS, with quite readable code, although I don’t quite like that it encodes structures as arrays and thus misses out on hidden class optimizations of JS engines (I could be wrong though). With Reason you can even write readable OCaml.

And of cause, I am very excited to see steady, although very slow progress towards compiling Rust to WebAssembly. Although I’m unsure about the FFI between WebAssembly/asm.js and real JS. It relies on a preallocated ArrayBuffer as a kind of heap, which might be good for low level performance but does not play well with consuming and outputting plain JS objects.

So the future is still very much open. I really hope there will be a readable, convenient, fast and safe compile-to-js language that can solve all these problems and integrates seamlessly into existing JS projects. One can dream though.

Individualismus
Über Diversität und ein friedliches Zusammenleben

Aus gegebenem Anlass möchte ich gerne meine Meinung zu verschieden Themen erläutern die mir am Herzen liegen. Da ich schriftlich meine Gedanken besser ordnen kann ziehe ich das einer wörtlichen Diskussion vorerst vor.

Mich stört

Ich sehe oft Verhaltensmuster in Individuen und in der Gesellschaft die mich durchaus stören und die ich für gefährlich erachte. Hier einige Beispiel, manche aktuell, manche alt.

  • Person A schließt Personen aus ihrem Freundeskreis aus weil diese Partei X wählen.
  • Person B würde am liebsten Menschen verprügeln die Partei X wählen.
  • Person C geht zu einer Demostration mit der Absicht Menschen zu beschimpfen.
  • Personen D und E verarschen mich weil ich nicht gegen Organisation Y bin.
  • Personen boykottieren und hetzen gegen eine IT Konferenz weil auf dieser Person F einen Vortrag hält.
  • Personen hetzen gegen Person G weil diese Jahre zuvor Geld für einen politischen Zweck gespendet hat.
  • Person H will am liebsten Partei X verbieten.
  • Person G bezeichner alle Wähler von Partei X als dumm.
  • Website W löscht und zensiert Kommentare mit gewissen Inhalten.

Wenn man etwas verallgemeinert könnte man dieses Verhalten als Mobbing bezeichnen. Und glaubt mir, ich kenne mich mit Mobbing aus. Ich war mein Leben lang Außenseiter und wurde mein Leben lang gemobbt. Genau aus dem Grund will ich vor den Gefahren dieser Verhaltensmuster warnen.

Die demokratische Grundordnung in Gefahr

Auf den ersten Blick scheint es sehr weit hergeholt, aber ich finde das dieses Verhalten im Zusammenhang mit Politik die gesamte Grundordnung auf den Kopf stellt.

Mal angenommen Person H bekommt ihren wunsch und Partei X wird verboten. Vielleicht weil Partei X zu rechts ist. Als nächstes verbieten wir dann noch Partei Y weil sie zu kommunistisch ist. Dann Partei Z weil sie zu öko ist. Partei W verbieten wir auch aus irgendeinem anderen Grund. Und ehe wir uns versehen haben wir Scheinwahlen auf deren Stimmzettel nur eine Auswahlmöglichkeit ist.

Und wie sieht es mit Überwachung und Zensur aus? Es wird tatsächlich zunehmend zensiert im Internet. Unter dem vorbehalt rechte oder hass verbreitende Kommentare zu löschen. Aber es geht auch schon einen Schritt weiter. Ein Freund hat mir neulich geschildert wie er zum lösches seines Facebook Kontos getrieben wurde. Nachdem er einen Beitrag einer politischen Partei kommentiert hat wollte Facebook urplötzlich seine Identität durch eine Passkopie feststellen. Ich selbst nenne es einen meiner Lebensgrundsätze niemals bei Facebook zu sein und nenne schon seit Jahren Facebook als eine der größten Gefahren für das freie Internet.

Die Frage ist auch wo wir die Grenzen ziehen. Wir haben heute schon Person C die absichtlich Menschen wegen ihrer politischen Meinung beschimpft, wir haben schon Hetzkampagnen gegen Einzelpersonen, Parteien oder sogar IT Konferenzen. Wo ist die Grenze? Was ist wenn Person B tatsächlich anfängt Anhänger von Partei X zu verprügeln? Irgendwann sind wir so weit das wir deren Häuser anzünden, und sie schlussendlich ermorden.

Ist das alles so weit hergeholt? Vor 70-80 Jahren hat es sicherlich auch mit Mobbing angefangen. Mit dem ausschließen aus dem Freundeskreis. Mit Beschimpfungen und dem Boykott von Veranstaltungen. Wie es geendet hat steht in den Geschichtsbüchern.

Mobbing ist tatsächlich eine starke Waffe. Es kann dem Menschen den Gedanken in den Kopf setzen er müsse sich für seinen Körper schämen. Oder für seine sexuelle Orientierung. Und jetzt sogar für die politische Meinung? Wenn durch Mobbing dies auch noch manipuliert wird sehe ich auch deswegen die demokratischen Grundsätze in Gefahr. Noch gut das es ein Wahlgeheimnis gibt. Oder sollen wir dieses auch bald abschaffen?

Ein Apell für ein friedliches Zusammenleben

Ich habe zwar selbst viele Vorurteile. Aber ich versuche dennoch jeden Menschen mit Respekt und Würde zu behandeln, ungeachtet dessen Hautfarbe, Geschlecht, Religion und politischer Meinung. Sofern sie mir den selben Respekt entgegen bringen :-)

Ich finde es sehr schade dass viele Leute die ich kenne, und die sich selbst als ach so tolerant bezeichnen dessen nicht fähig sind und stattdessen Menschen mit anderer politischer Meinung beschimpfen oder am liebsten verprügeln würden. Eben von den Leuten erwarte ich das sie es besser wissen sollten.

Ich würde die Menschen in meiner Umgebung eher als links einordnen, falls ihr mir das Schubladendenken verzeiht. Aber das Maß an Hass den diese Menschen gegen rechte versprühen übersteigt meine Toleranz etwas. Und nicht nur das. Auch Menschen die nicht gegen rechts sind kriegen diesen Hass teilweise ab. So wie ich.

Ich bin nicht gegen rechts. Ich bin auch nicht für rechts. Ich bin dafür das jeder Mensch ein Recht darauf hat sich frei zu entfalten und mit Würde behandelt zu werden. Und ein Recht auf freie Meinungsäußerung usw, auch wenn die Meinung vielen Leuten nicht gefällt.

Dennoch muss man sich im Kopf behalten dass die eigene Freiheit dort aufhört wo sie die Freiheit anderer Menschen einschränkt. In diesem Sinne: Seid lieb zueinander :-)

The one killer feature icon fonts have over svg
OR: why github icons look like shit now

The reason I write about this now is githubs icons started to look like shit on my screen/system since a week or so. I asked myself why and looked at the source to find out they switched from using an icon font to inline svgs. There is quite some controversy about whether to use an icon font or svgs for icons. Just google for it to find some articles about that topic.

What neither of those articles mentions is the one killer feature that icon fonts have over svg. Actually its two features, but they are a bit related. It is this: hinting and subpixel anti-aliasing.

In english, hinting means that the font rendering will snap straight lines to device pixels, to make sure that fonts always look crisp. And subpixel AA means that the font rendering can boost the horizontal resolution by 3 due to the fact how lcd hardware actually works.

Both of these features are unique to fonts, they do not apply to svg. Hinting can actually distort the proportions somewhat to make sure straight lines snap to pixels, you clearly do not want that for svg. And although subpixel AA may be possible for svg, I have never seen that been done so far.

There is quite some hoops you have to just through to make svg, and especially <canvas> look good and crisp. If you want a line that is 1px wide to look good, you have to place it at a 0.5px coordinate, so when you add the width, it ends up at [0, 1] and therefore looks crisp. You do not want to do that for a 2px line though, because you end up with [-0.5, 1.5] which looks like shit again. It’s hard. Believe me, I’ve been through that already.

The point im trying to make here though is that in order to make svgs look good, you actually have to give up on one key selling point of svgs: scalability! You have to author svgs, specifically for one size to make sure that lines snap to device pixels. Fonts will just do the work for you.

Caveats

All that I have written about here applies to my personal system, which has a device pixel density of 1. For low dpi screens, hinting matters a lot. The problems I described here are much less of a problem on high resolution screens.

The second thing to note is that content authors do not control font rendering all the way. Sure, there are css properties like font-rendering and friends, but for example the hinting behavior can not be controlled by the author, but is a system wide setting. On my system, I have hinting turned up quite high because I prefer light crisp fonts rather than thick blurry ones. One of the hits you find on google for that topic mentions that icon fonts look blurry compared to svgs. They might, depending on your font rendering settings. On the other hand though, svgs look blurry if lines do not line up with physical pixels, pun intended.

Fact is that font rendering settings also very much depend on your personal taste. Some people for example have font smoothing / anti-aliasing disabled altogether, most likely because they don’t know such settings exist. If I have to use someone elses system, turning on font AA is the first thing I do, because it really hurts my eyes.

I have a also recently seen a developer post a screenshot without font AA that also hurt my eyes really bad. Come on, it’s 2016 for fucks sake! There is absolutely no reason to not activate this single most important feature of a modern desktop!

Doing the impossible:
Choosing a Material Design Framework

The story starts like this: I am about to start developing a native-looking mobile App. And I would like to use Material Design for it. Since its awesome and I want a native look and feel.

And just as a precursor: Similar to Paul Lewis, I am also known to hate everything that looks and smells like a framework. Even though Material Design is just about styling, most of the Material Design Frameworks do come with some baggage in the form of JS and Framework lock-in. I am also extremely opinionated when it comes to JS Frameworks and Conventions. I kind of feel like I am chasing for perfection instead of getting shit done. But well that’s just how I roll :-(

So I was mainly looking at Materialize and Material-UI and the paper elements of Polymer. And then just during my research google released Material Design Lite. I also looked at some other smaller contestants, but those four came out top.

Before I start dissecting the choices, lets just say that every one of those is missing some things that I kind of need. It is kind of disappointing really. So many contestants, but all are lacking in some ways. :-(

So lets start.

Materialize

Seeing how materialize was a bunch of jquery plugins, I quickly removed it from the list of options. jQuery was nice ten years ago, but I think we can do without it by now.

I actually did try the other three, Material-UI, MDL and Polymer.

Material-UI

While I do like the concept and the composability of a react-like library, react itself is a bit too big for my taste. Putting material-ui into the mix, a simple page with just an AppBar comes to 1M of code. As opposed to all others, I actually talk unminified ungzipped code here. LOC would be a better measure but I don’t have exact numbers, except that it is HUGE.

It also has some kind of boilerplate:

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
import React from "react"
import injectTapEventPlugin from "react-tap-event-plugin"
import {Styles, AppBar, IconButton} from "material-ui"

injectTapEventPlugin()

const ThemeManager = new Styles.ThemeManager()

class App extends React.Component {
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme(),
}
}

render() {
return <AppBar
title="Foo"
iconElementLeft={<IconButton iconClassName="material-icons">arrow_back</IconButton>}
/>
}
}

App.childContextTypes = {
muiTheme: React.PropTypes.object,
}


React.render(<App />, document.body)

As far as I understand, this means that you can change the theme dynamically, which would be awesome. But the boilerplate is a bit annoying nonetheless.

On the plus side, Material-UI has some nice special elements like date and time pickers. It seems to be quite complete.

What I don’t like about React is that you can’t have arrays of elements, except for children. But you can only have one children array per element. So Material-UI passes some children as props, which just feels wrong to me. I know that a lot of React libraries use this pattern, but it still feels wrong to me.

Polymer

I started out with the full polymer starter. Maybe that was a problem, since its also HUGE. It was downloading 300M of npm packages, plus a lot of things from bower. It just generated hundreds of files and I have no idea for what purpose. I simply couldn’t understand all that code. And that’s not even library code. It’s supposed to be your own app code.

Also, I’m not really a friend of html imports. I would rather have ES6 modules and wire up as much through JS as possible, maybe even CSS. But having everything as HTML modules with code inside script tags just feels kind of backwards to me. Maybe I should start with an empty project so I wont be overwhelmed from the start.

I am also kind of ambivalent when it comes to web components in general. Sure, it is supposed to be implemented natively in the Browser. But you still have to pay high costs for it. The browser will have to (recursively) resolve the imports and load the things. HTTP2 Push will help a lot, but still. Also there is a lot of JS involved at app start. While it does not matter for the project at hand, I think think web components, depending on the way you use them might not be that great for SEO, serving static html and load times. But I might be mistaken completely. For now the whole machinery with html imports and the tools that are used to vulcanize them seem to be a little overkill for me.

I actually haven’t looked into how big the resulting code is, but I would probably have to use it in conjunction with a React-like library anyway so that would grow the size considerably as well.

Material Design Lite

MDL was actually released right the moment when I was starting my research. Being mainly about CSS, with just little JS involved (sadly you can’t quite do without), and directly from google, it felt like it might be the best contestant. But it is also quite new and incomplete. It has no list components as of yet. And the Appbar kind of has a menu button hardcoded, I’m not sure how to replace that menu button by a back button.

Also something that really annoys me is that it is not yet easily embeddable in a typical app based on CJS or ES6 modules. The JS code relies on being globally imported, which I don’t particularly like. Hopefully this will be fixed, but until then its just annoying.

The JS Code comes to roughly 110K unminified and it is not too bad to read. The CSS also amounts to roughly the same size.

Again, I would use it in conjunction with a React-like library so that would add some weight. All in all, it feels to be the simplest base if I happen to do a lot of custom things. And since it has no lists yet, I would have to do at least those myself.

Conclusion

I am still not happy with the choices I have to be honest. And I still feel like I’m standing in my own way. Since I want to use something that I actually like to use, as in feeling like I’m doing the right thing as opposed to getting things done but feeling like its all a big hack.

So I’m basically standing still for now. Maybe I will give a clean Polymer project another chance, maybe I will go with MDL and just implement certain things myself. Most likely I would have to implement quite some things myself anyways.

New Blog

I have decided to start over. This time instead of rolling my own static site generator or blogging system, I decided to try hexo with a slight modification of its default theme.

And from now on I think I will blog more about technical things rather than personal or philosophical ones. And also to do so in english.

So enjoy!