Showing posts with label killa. Show all posts
Showing posts with label killa. Show all posts

Saturday, July 27, 2013

Killa: the case for mandatory braces

Killa was created following the Perl/Ruby philosophy of freedom of choice. So you must be wondering why on earth I decided to add the rule of mandatory braces for blocks. Its a valid question, one that I would try to answer in this post. But first a bit of history.

My first approach to programming was at the university. The career I was following (electrical engineering) was not centered about programming, so programming was for us a mere exercise of getting additional credits. I don't remember much about my time at the university, but what I can not forget is our "code" and by that I mean the spaghetti-like thing that most of us produced for code: horrendous single file programs without proper naming conventions neither formatting with piles and piles of commented sections that for some miraculous reason worked enough to pass the tests at hand. I suspect that the pain of working in that kind of environment was the main reason behind me starting to use my own set of code conventions, and even when my programming style has changed a lot through the years, the first rule has always been the same: never ever forget to use braces for code blocks. No excuses.

So lets see some code. In many C-derived languages (like C++, C#, Java, JavaScript), braces are optional. So this code:

    if ( enemyIsNear() ) {
        launchTheMissiles();
    }

can be written like this:

    if ( enemyIsNear() )
        launchTheMissiles();

And this it's perfectly legal and used a lot on industrial-grade software.


You could be wondering (with reason) What is wrong with this? And the answer is nothing... for the time being. The missiles are launched only when enemies are near. But as Joel Spolsky would say, this code just smells a bit bad. There is nothing preventing another programmer to add a line of code to the conditional and forgetting to add the required braces. Imagine we need to speed up before launching the missiles, we could do this:

    if ( enemyIsNear() )
        speedUp();
        launchTheMissiles();

but now the missiles are launched even if we are not near an enemy! Because the above snippet is equivalent to:

    if ( enemyIsNear() ) {
        speedUp();
    }
    launchTheMissiles();

A total waste of missiles just because we were saving a pair of braces! Clearly this is not good, but lets see some arguments that are used against mandatory braces.

The code compressors

Some professional programmers could favor optional braces under the argument that forcing braces adds one or two more lines of code in blocks like the one presented at the beginning. After all, under some code conventions the original snippet ends like this:

    if ( enemyIsNear() )
    {
        launchTheMissiles();
    }

Four lines instead of two! A total waste of space! Considering all the cases where additional new lines are introduced we obviously get more lengthy programs.

Less code is better, they'll say. OK, sure! But if programming were a simple matter of removing new lines this would be even better:

    if ( enemyIsNear() ) speedUp();

You could be wondering: What is wrong now with this line of code?
And I'd say ...again nothing! Until you want to test your program and check if the conditional is working in all the cases that it must work. Some kind of code coverage. The program hitting that line doesn't give you any indication about the conditional being passed or not. For this example we could check if the function was called, but that wouldn't be the case if the code were like this:

    if ( enemyIsNear() ) speed = 2 * speed;

it is not clear how can we validate if the speed is being doubled or not. Adding a breakpoint to this line for debugging is going to stop the program always, so you'll need to break the line anyways for debugging purposes.

So the argument of using less lines of code is moot, less code is better code but only if the resulting code does the same, has the same number of errors and maintains the same quality. If this were not the case, the code minifiers would be the best coders ever. However, still we need to probe that using mandatory braces produces code of better quality.

The indentation believers

Some professional programmers would believe that correct indentation is good enough to indicate the beginning and end of code blocks. Indeed, there are some languages that go one step ahead and remove the need for block delimiters, indentation is used for block scoping. In Python the original snippet looks like this:

    if enemyIsNear():
        launchTheMissiles()

No need to argue about mandatory braces here, there are not even braces now. Cool. Everything is good and well but someday you realize that you need to check the engine heat after launching the missiles, so you do:

    if enemyIsNear():
        launchTheMissiles()
        checkEngineHeat()

The engine check is a time wasting process but it's fine because it's done only after we launched the missiles. And then someday another engineer realizes that for this jet model in particular the check is always required, doing:

    if enemyIsNear():
        launchTheMissiles()
    checkEngineHeat()

Just looking at this change, I tell you, I'll freak out. What if for some reason the guy accidentally deleted my precious tab?. Nope, we don't use tabs here. But What if he thought I was wrong and I did the original change wrong and now he fixed it. I won't rest happy until having a little chat with the cunning fellow. Of course if this where a industrial-grade software, this change alone would come with a lengthy and detailed description in the commit log, or even better with profuse comments on the program itself. But my point stands, format alone is not enough to clearly state program intention. Indentation is a decoration, it's a luxury, and you must be free to decorate your programs the way you like. Just leave my block delimiters alone. The other problem with using indentation as block delimiters is that indentation is done using  withespace. And whitespace is by definition not visible. Yes, you could force whitespace to be visible in your editor, but that is forcing and it is at the very least discussable. I mean, if it were good enough we all must be programming in Whitespace for the fun. A side benefit of not using indentation for block delimiters is that you can safely ignore any formatting change in code reviews: just ignore whitespace. I won't talk about the issues of copy pasting code in Python, copy pasting code is bad anyways and you deserve to be toasted.

That said, I don't think I'll convert many believers with my arguments here: they are believers for some reason and I'm just a non believer. For them code like this:

    if ( enemyIsNear() ) {
        launchTheMissiles();
        checkEngineHeat();
    }

it's just tiresome and bloated source code.

The C pitfall

C is a great language, but it could have been even greater. One of it's design fails came when it allowed optional block delimiters. Consider this classical example:

    if ( enemyIsNear() )
        if ( isWeakEnemy() )
            launchTheMissiles();
    else
        watchTV();


You could be thinking that it's safe to watch TV if there are not enemies near. But what this code really is doing is:

    if ( enemyIsNear() ) {
        if ( isWeakEnemy() ) {
            launchTheMissiles();
        } else {
            watchTV();

        }
    }

Yeah, you would be watching TV with a mighty enemy on your tail. Scary, isn't? C doesn't use indentation for block scope, but it allows optional block delimiters. Bad things could happen, and now you are falling on your parachute looking the ground under your feet approach.

About the possible bug with which we started this post, to be honest, I have rarely seen it in production code, even less in committed code. I can't introduce it because I use mandatory braces, my team can't introduce it, because I established the company guidelines with mandatory braces on it and most of the projects I have worked on use a code convention that forces mandatory braces or are careful enough to avoid this class of blunder even if they are not using mandatory braces. Or that I though. But upgrading Killa with the fixes in the Lua 5.2.2 release (Killa used the Lua 5.2 version) show me some remarkable fix in the line 824 of lapi.c:



Looks familiar? Yes. The scary thing is that this bug was able to hide itself for more than one year in a project reviewed by hundreds of savvy programmers (me included) but we totally missed it. When working in Killa I had two options: reformat all the source code to use my code standard (mandatory braces), or leave it like it was. I was in a hurry and decided for the second option, also reformatting the source code would imply a lot more of work back-porting upstream changes. The sad thing is that manual reformatting would have surely made me question the code in mention, the indentation was wrong at the very least.

For the sake of redemption, The Go language developed by Ken Thompson (the father of the B language from which C was derived) uses now mandatory braces.

Conclusion

I argued against two camps that oppose mandatory braces and showed some pitfalls about allowing optional braces in legacy languages, but at the end, I failed on giving you hard evidence about this, I don't have the statistical numbers at hand, just some anecdotal evidence and you are free to think it's not enough.

The reason I implemented mandatory braces in Killa is that I believe this has the benefit of making clearly evident the structure and intention of the underlying programs. It's not fool safe but a lot better than leaving free choice in this regard.

Freedom, there is still plenty: you can use tabs if you prefer them, 2 spaces or 8 spaces? it's for you to decide, the Lisp style is your thing? be my guest. Just leave my braces alone.

Sunday, November 4, 2012

Bitwise operators in C, JavaScript, Lua and Killa

So I thought that porting a Game Boy Advance (GBA) console emulator written in JavaScript to Killa would be fun, boy I was wrong... All because I wanted to play with this:


Tuesday, October 2, 2012

Ruby and the joy of programming

Years ago I used to solve many mathematical problems in Ruby. Looking backwards, I find difficult to explain my decision, because if I remember correctly Ruby was slow compared with C++ or Perl, and since most of the time I ended using a brute force approach to solve what my imagination could not solve efficiently I often ended awaiting longer times before obtaining my answers.

However, I can clearly remember that for the first time in my conscious programming life, I was happy and I was enjoying my time with some programming language. So I didn't worry too much about some additional time awaiting a stupid brute force solution. I was solving mathematical puzzles for fun and with Ruby I could quickly test some crazy ideas, leave the process running and go to do other things. Ruby was powerful, concise, elegant, and more importantly it didn't force over me its formatting policies or push me to do things in some way I didn't like to. I had finally found a language where everything fitted in place and seemed natural. I thought: this language must have been created by someone who really likes having fun while programming.

And indeed it was. Ruby was created by Yukihiro Matsumoto (aka Matz), who is one of my heroes actually. I found an interview he gave about Ruby and there he said something that really touched a fiber inside me, I have always used his words as an inspiration:

Fun to use. Freedom to choose. This man taught me all.

Sunday, September 23, 2012

Killa: my scripting language based in Lua and JavaScript

So I have been working these past months on my own programming language. It has been something that I've always wanted to do so I'm very happy that I can announce it here. Without further ado: Killa. I finished the 0.1 version months ago but real life just got busy on my end and I have been slacking this post for ages.

Killa (moon in the native tongue of my country) brings no new paradigm, neither disrupting ideas to the world of programming languages, to be honest I just stole some ideas from this book JavaScript: The Good Parts added some new ones from the top of my head and made it all work using the Lua 5.2 virtual machine, so... Why to bother? could you ask. Why indeed, with so many new and wonderful and exciting languages like Clojure, D, Haskell, Haxe, and trusted powerhorses like Python, Ruby and your favorite one here, creating a new half baked one could be just me following the new craze of "everybody can make his own programming language" (in 21 days).

Something of that was of course present, as I said before, I have always wanted to create a programming language, but even with that idea on mind, investing my time in a horrible language just for the sake of creating "my very own programming language" just doesn't click with me. If I'm going to create a programming language it better must be one that I'd really like to use, and I'm picky, programming after all has been my bread and butter for years. So I started saying that Killa just stole some parts of JavaScript and Lua, looking now backwards it's not surprise that I created Killa. I was not happy with any of them.

JavaScript. It had so many ugly parts that make me feel nervous every time I tried to do some fancy HTML5 stuff, at the end I did nothing (but that is not JavaScript fault, it was just me being lazy). Anyway, I could clearly notice that there were some beautiful gems hidden inside that jungle of errors and blunders. For starters, it was C-like, and C is one of my favorite languages. But, at difference of C, JavaScript had that "plastic" nature that made it powerful for solving problems in a dynamic way. First class functions, closures, that was cool.

Then it was Lua. I found Lua due to my work as a game programmer. Lua is kind of mainstream in the game industry for scripting, and it's a good little language, at least that was my first impression: it's pretty solid, it has a permissive license, an active community, it's very small and easy to embed inside your game engine, it doesn't take much memory and it's quite fast... but man: Why on earth have the array indexes to start from 1 instead of 0? and Why global by default variables? and Why the Pascal-like syntaxis? and Why not ternary operator? and Why not this and this and that? There were so many little annoyances that irked me daily. Somebody could think that I created Killa just because of external appearances, I don't think so. For me Lua was broken by the myriad of its little annoyances, but it's core was very useful and it was a waste not to use it.

I also believe that every programming language is by definition broken because none can do every task optimally. Lua was broken for me because I was a programmer working most of the time in a C-like world, having to change languages was a pain. By this definition, Killa is broken too, but it's broken for different people and for different reasons than Lua.

So I suppose that Killa has a place to fill and stay. I'm happy with the current status, but of course it needs lots of work to be stable. For now let me show you how the language looks, the little program below solves the Project Euler 393 problem under 9 seconds on my computer:

Not as fast as Python for this problem, but Python has the advantage of having immutable tuples that can be used as dictionary keys, I suspect that makes the above algorithm run faster in Python, because in Killa I had to use string keys and additional data handling was required. Also this problem needed support of big numbers that I added to Killa as an extension just now. It's just the port of lbc from Lua to Killa, but because the original library is under the GPL license I can not add it by default to Killa. I plan to maintain Killa under a permissive license for the sake of my fellow game developer peers. GPL-like licenses are very cumbersome for game development.

So, Who are the potential users of Killa? I think that anybody who likes the embeddable features that Lua has to offer but wants a JavaScript-like experience with many of its ugly parts removed. I could see Killa being used in the videogame industry or the embedded industry. To start things running (and for testing) I have already integrated Killa into two popular game engines: Love2D and cocos2d-x and I have made some small projects with them.

That's it. I need to explain with more detail the features of Killa in a future post, until then: happy coding!

UPDATE: I used bitwise operators to get the time down to 1.12 seconds, faster than Python (1.8 seconds)!

Sunday, September 16, 2012

Combinatorial explosion and Project Euler 393

Last week I found a nice video about algorithmic combinatorial explosion. It was very interesting but it's a bit sad to see the big sister throwing away her life in order to teach her little students the perils of trying to compute combinatorial problems that grow very fast. The problem they studied didn't seem to be hard, just enumerate all the ways you can go from one corner to the opposite corner in a rectangular grid without passing the same node twice. Deceptively simple, for a 1x1 grid there are only 2 ways, for a 2x2 grid there are 12 ways: