Posts belonging to Category Programming



Why do I use Emacs

About a year ago, when we were having knowledge transfer about one interesting Java component, the dude, who was showing me what the code was doing, suggested that I should use Eclipse instead of Emacs, because it is so much better editor. I can argue with people who claim that Vim is better than Emacs, but I just kept mouth shut this time.

My first contact with Emacs was in University, but I didn’t immediately see the power of Emacs. I got a job as a Windows programmer, and I started using Visual Studio like every Windows programmer. However, I was surrounded by these UNIX gurus, and watching them do their work in Emacs and in a shell, I realized that I could be much more productive, if I learned to use those same tools.

Visual Studio wasn’t that bad. I liked intellisense, but simple text manipulation was not on the same level as it was in Emacs for those gurus. Other Windows developers where also moving towards Emacs and I decided that I will also do that. The first year was though. First I tried to make my Emacs a full-blown IDE with all different views, but at some point I ended up having two editor frames side by side without any extra stuff.

Slowly, but steadily, I started to learn new things about Emacs and then I realized that I will never stop learning new things about it. At the same time I was reading Pragmatic Programmer, which is one of the best books ever. In Pragmatic Programmer there is one advice called : “Use a Single Editor Well”. I decided I will try to learn Emacs as well as possible and forget all the other editors and IDEs, because life is too short to learn two editors well.

I started to pick up really cool stuff for my Emacs. iswitchb-mode was one of my early favorites. It makes switching between open buffers a breeze. I always get a warm feeling, when I see people using their editors or IDEs to switch between open files. A lot of mouse movement or typing is required to get the job done. I do the same thing in Emacs with only a few key presses.

I was kind of missing “go to declaration” from Visual Studio, but when I discovered tags or especially xgtags, my worries were gone and I could easily jump to definitions and declarations without having to move my hand from the keyboard.

I knew about keyboard macros and thought they were really cool, but when I realized what rectangle operations could do, I was blown away. Manipulating text on multiple lines is a feature that should be in every single editor. Most editors nowadays have it, but I never see anyone else using the feature, but then again, I am surrounded by Visual Studio, Eclipse and Vim guys.

I loved iswitchb-mode, but I needed something similar to open new files. Currently I am using file-cache to do this and it’s brilliant. Just like with iswitchb-mode, I can type any part of the file name and open the correct file with only a few key presses. I know that anything.el could do the job of both iswitchb-mode and file-cache, but when I tried it just didn’t seem as smooth as the tools I was already familiar with.

Unfortunately I have to do some C++ coding, and when I discovered flymake, I almost crapped my pants. Now I would never have to fix compiler errors after trying to compile the code. I would fix them on the fly while writing the code. I am, of course, writing this using Emacs and have turned on flyspell-mode, which does the same thing for English language. This feature is, of course, in all the modern word processors and browsers, but not in many editors.

One last feature I would like to mention is yank-pop. When you learn to use, you can pretty much cut any piece of code or text, without having to worry about overwriting the clipboard with something else. This is a really powerful feature and I don’t understand, why it is not everywhere.

Most of these features are available in other editors also, but like I said, Emacs was the editor I decided to learn and I am sticking with it. You can use whatever editor you want, but don’t tell me that editor X is better than Emacs, because it probably isn’t.

I always try to be more productive and the editor plays a big role in this. Fortunately, Emacs allows me to this as good as any other editor or probably even better. Learning to use Emacs is a life long project, but I knew that it was the right choice for me when I made the decision. You might not want to spend so much time with your editor, but when I have my own company, I don’t have to hire you either.

  • Share/Bookmark

My Beef with C++

Bjarne Stroustrup is giving two speeches in Finland this week. Stroustrup’s topic is the trends and future of C++. I have been seriously contemplating protesting his speeches. I have thinking about what kind of signs should I make for the event. (These are all jokes, of course, I am not actually going to do this)

“Thanks Bjarne, for ruining the lives of millions of coders”

“Because of you, Bjarne, I hate my job”

“I hope C++ dies as soon as possible”

“You look almost as ugly as C++”

“What where you using, when C++ was designed?”

“Seriously, was that [C++] the best you could come up with?”

Anyway, I have a serious beef with C++. The more I have to use the more I despise it. Biggest problem is that everyone has their own idea of what C++ should be. So basically one code base could be using 15 different programming languages, except they are all called C++.

Don’t try to sell me the crap that you can write bad code in any language. That is true, but no other language, which I know of, allows you to write so complex stuff in so many different ways that it requires multiple PhDs to understand what is happening. Bad programmers will write bad code in any language, but at least I might understand it. I have been coding C++ (or C with classes) for too long and I am still baffled every time I see templates mixed with operator overloading.

Why do people have the need to do complex things, when a simple solution would do the job? Are they trying to prove their superiority as C++ coders? Maybe they are making themselves irreplaceable, because no one else will understand their code. “He must be good coder, because no else will understand his code”. I think that is bullshit. Good coder is someone who writes code that others can follow easily. I don’t respect people who write so complicated code that my head starts to hurt when I see the code.

There are way too many features in C++. You can get a decent language out of it, if you keep most of the features away. I assume Google is doing a pretty good job with this. They have a pretty clear style guide that dictates what features are allowed and what are not. However, unfortunately everybody has their own idea of what features should be used and what shouldn’t be used.

The hell breaks loose when there is no common agreement what features in C++ are allowed. The result is a complete mess, and this is where my beef with C++ is. It’s like talking the same language, but not understanding what the other guy is saying. The language provides so many different ways of doing things that nobody could ever learn them all. This is C++’s fault and companies’ fault. If there is no agreed way of writing C++, people will write it as they like, and everybody likes to do it a bit differently. No other language makes this possible. C++ is basically a language with as many sub-languages as there are programmers.

  • Share/Bookmark

Master of Blocks Preview

I am getting ready to publish my second application that uses the Lua framework I have created for iPhone. You can check out the Lua source code for the game : here.

The game is a 2 player Tetris clone inspired by the awesome Tetris God video.

I hope to get game finished and submitted to App Store later this week. After that, I will work on the framework to get it open sourced.

  • Share/Bookmark

The Next Big Language will have to wait

Steve Yegge talks about The Next Big Language in his classic blog. The blog is already three years old, and there has not been that many changes in the world of programming languages in recent years.

According to TIOBE, the ten most popular programming languages have stayed the same in the last four years, and no language in the top ten has moved more than two positions in either direction.

In the last 12 moths, Objective-C has jumped from 32. to 12. on the list. There is an obvious reason for this; any software submitted to Apple’s App Store must be written in Objective-C. The popularity of iPhone and iPod touch has made Objective-C main stream language in a year, but it is still not even close to being a big language.

Another site that collects information about the programming language popularity, is lang.pop. Their results are collected from different web sites, and are very similar to TIOBE’s findings.

In his blog, Steve says that the NBL should arrive in 18-24 months. It has already been 37 months and nothing significant has happened. Instead, almost every one of the top 10 programming languages have found their niche and solidified their position in their respective areas. Let’s take a look.

  • Java : Dominating enterprise server business
  • C : Dominating low-level and embedded software
  • C++ : Strong in many different fields, especially games
  • PHP : Unfortunately still really popular on the web
  • Visual Basic and C# : Strong in Windows software
  • Python and Perl : Most popular scripting languages and doing well on the web
  • Javascript : The language for web applications

If we consider C, C++ and Java to be the biggest languages, I don’t see any language currently in the top 20 taking their place. C++ might be the one that could lose the most popularity in the near future, because it is not really strong in any particular area, except maybe gaming, but I don’t see a single language taking its place. Most probably, different languages get some parts of its popularity in different areas.

PHP is a mess, Visual Basic and C# are too Windows oriented, Python is too slow, Perl is Perl, Javascript is stuck to its niche, Ruby is slow as hell. Honestly from a technical point of view, Go could be the next big language. It would require some serious brainwashing from Google. If Google starts shipping computers and mobile phones to people all over the world, and the only language you can use to develop software for those platforms is Go, then it might become the Next Big Language.

Usually when a new programming language had gained some popularity, it’s because there was a new opportunity and a big company behind it. The current market is taken. At the moment, I don’t see any holes where a new language could go and overtake the segment, because the other languages could not fill the hole.

It will require new type of hardware or a completely new need for software before the Next Big Language will have a chance to appear from nowhere. There must be huge financial support for the language, because companies will not want to waste their money experimenting with new and unproven programming languages.

The Next Big Language must be advanced, but I don’t think that it is the deciding factor. I would like that the Next Big Language would do everything that Steve has listed, but I think we will have to settle for less. There will be languages that will fulfill all Steve’s requirements for NBL, but the actual NBL won’t probably be chosen on technical merits.

People talk a lot about high-level languages like Haskell, Erlang, and OCaml, but not very many people actually get to write code for living in those languages. Young people need to decide what languages they need to learn to get a job in programming, and unfortunately, they start learning Java and PHP to get a job. I can’t blame them that most programming positions require Java, PHP, C# or Visual Basic skills.

I hope that before I retire I could see a new language rise and take over most of the programming world. Currently there are too many programming languages that I don’t want to write for living. I would like to see C++, Java, PHP, and Visual Basic disappear from this planet and be replaced by something awesome, but I don’t know, if that will happen in the next 30 years. Let’s hope Steve is right, and the Next Big Language is right around the corner.

  • Share/Bookmark

Better looking code has fewer bugs in it

The most important thing for me about code is its looks. I might sound crazy, but bad looking code makes me cringe. Whitespace is the single biggest factor defining the looks for the code. Variable naming is also important, but as long as it is consistent, it doesn’t matter nearly as much as whitespace usage.

There is actually a reason why I rave about the importance of looks in code. Better looking code has fewer bugs. Let me say it again with all caps: BETTER LOOKING CODE HAS FEWER BUGS.

There are many reasons for it and I will try to prove it to the best of my abilities.

Whitespace should be used to separate things. By writing

    variable_x+variable_y-variable_z*variable_y

it takes a while to see what is actually happening in the code. If the whole thing is written without any whitespace, it is hard to know where a variable begins or ends. By writing

    variable_x + variable_y - variable_z * variable_y

it is immediately clear what is happening. It takes less time for the brain to visually gather all the needed information from the line above. All of this was achieved by pressing the biggest key on the keyboard six times. The space key is so huge that I don’t understand, why many programmers have hard time finding it.

Because the second example is more clear, the bugs in it are more obvious. Let’s say that instead of using a ‘-’, there should be a ‘+’. This might go unnoticed in the first example, but the operators are more visible in the second one, and the problem can be caught more easily.

Whitespace doesn’t only limit to space characters; newlines are also really important. Code should be structured by modules, functions and blocks of code inside the function. If the function is one big block of code without any newlines, it is impossible to quickly get a clear picture of what is happening in the function. The return key is also quite big, but still many programmers are able to avoid touching it for long periods of time. Some programmers claim that if code has too many empty lines, enough information cannot fit one screen. I have one advice for you: Buy a bigger monitor. If you still want more lines, turn it 90 degrees. Now you have so many lines visible that even the most verbose Java code with plenty of empty lines manages to provide a lot information in your Eclipse.

Example 1:

    lines_of_code;
    another_line_of_longer_coder=xyz;
    for(i=0;i<12;i++)
    {
        print("ILIKEDENSECODEBECAUSEIAMARETARD")
        another_print("NOTHING");
    }
    long_calculation=1262+3222-3423^32424>>1233?1:0;
    //comment hidden here so you won't see it
    another_useless_line_of_code_that_does_absolutely_nothing();
    move_along_nothing_to_see_here();

Example 2:

    lines_of_code;
    another_line_of_longer_coder = xyz;

    for (i = 0; i < 12; i++)
    {
        print("I DON'T LIKE DENSE CODE BECAUSE I AM NOT A RETARD")
        another_print("NOTHING");
    }

    long_calculation = 1262 + 3222 - 3423 ^ 32424 >> 1233 ? 1 : 0;

    // comment not hidden anymore
    another_useless_line_of_code_that_does_absolutely_nothing();
    move_along_nothing_to_see_here();

Who can honestly say that the first example is better than the second one in any aspect?

Not only does elegant code make the bugs more visible when looking at the code, but bugs are also more visible when looking somewhere else. There have been many situations where I have found bugs in code, when doing something completely else. Beautiful code leaves an imprint in my mind, and sometimes I know exactly where the bug is. I cannot do that with ugly code. I cannot bend my mind around ugly code and walk through it with my eyes closed.

Too long lines and too long functions also prevent me from seeing the code in my head. If the function is short enough, you know everything that is happening in the function and in what order, but if the function is too long, you get lost and don’t know what is happening in the function without looking at it. Long lines, which I already complained in another blog, also hide bugs and prevent me from visualizing the code in my head.

There is never a good reason to write bad looking code or deviate from coding standards. It takes only about 2% more time to write proper code, but most the time should already be spent on thinking. If the 2% is too big for you, maybe you should switch your editor to a proper one or get a new profession, because I don’t want to work with people, who cannot follow simple agreements.

  • Share/Bookmark

What happened in Vegas '08

I am sorry to disappoint you, dear reader, but nothing that you might expect, happened. I was there to attend a programming competition. The venue was the Mirage Hotel and I was there to take part in TopCoder Open ’08 Marathon Match finals. But first, let’s see how I actually got there.

I started participating in TopCoder competitions in the summer of 2007. The first two competitions were a learning experience for me, but in the third competition I was doing pretty well, but my final submission had a bug in it, which dropped me from sixth place to 79. I was really pissed, and started testing my solutions more thoroughly after that.

2008 TopCoder Open started in February and had three qualification rounds, before the 12 best competitors would meet in Las Vegas for the final round. 617 competitors participated in round 1. 300 best made it to the second round, and I actually had the best solution in the first round. 100 best from the second round made it to the third round, and I placed 20. in the second. Third round was probably the most grueling two weeks of my life. My usual day looked like this: 8 hours or work, 2 hours of basketball practice and 8 hours of coding at home. I didn’t sleep much, but in the end, I placed 5. in the third round and made it to Las Vegas.

TopCoder paid for my trip to Las Vegas, and they also paid the five nights I stayed at the Mirage. My competition was on the first day. It started at 9 am and lasted for 8 hours. In the beginning, I was struggling a bit, but after lunch I started rolling and went to the top of the leader board. However, I didn’t stay there for very long, because Psyho overtook me by a clear margin, and I kind of new that I had given everything that I had. Fortunately nobody else scored more points that I did, so I placed second in the competition.

The prize money for second place was $5000, which was kind of nice considering that I got a completely free trip to Las Vegas to do some coding. It was a really nice reward for months of hard work in the qualification rounds.

I spent the rest of the week mostly at the hotel watching NBA playoffs, because I got a fever and a cold. It was bit disappointing to go all the way to Las Vegas and become ill, but at least I saved some money that I probably would have spent at the famous Las Vegas activities.

Last year I didn’t quite make it to Las Vegas; I was 21. in the final qualification round and 10 best made it to Las Vegas, but this year I will go for it again. I haven’t participated in that many TopCoder competitions anymore, because they are really time-consuming, especially when working normal hours.

I am currently ranked #3 in the Marathon Match competitions, but there are some competitors that are not currently ranked, because they have not participated in any competitions for a while. I bet that all the top competitors will come out from hiding for TopCoder Open 2010, and the final qualification round will drain everything out of everyone, who tries to make it to Las Vegas.

Source code for my solution

Problem description (Must be a TopCoder member to see the description)

  • Share/Bookmark

Why Lua truly rocks

For the uninformed, I am of course talking about the programming language Lua.

Recently I have been working on my Lua-based framework, for creating games and applications for iPhone. Yesterday I submitted my first application which uses the framework to App store. The whole application is written in Lua. You can check the Lua source code for the application here.

I have been working on the framework for weeks, but I wrote the Lua code for the application in just one day. The application is not very complicated, but Lua shows its potential compared to Objective-C, when you need to get iPhone apps done quickly. The more I improve the framework, the easier it is for me to write those application in Lua, because writing the application logic and adding a user interface is quite simple compared to writing everything from scratch with Objective-C.

The reasons for choosing and using Lua for iPhone applications were pretty obvious for me. It is written in ANSI-C, which means that I can just take the Lua source code and compile it with rest of my framework. Lua’s licensing model, MIT license, allows me to do anything with Lua. Lua is also quite compact. The binary size will only grow by a couple of hundred kilobytes, which makes it really light. It is also quite fast compared to other scripting languages and the memory usage is not too bad. I haven’t done any heavy calculations in my applications yet, but if I ever need to that, I can move the heavy processing to the Objective-C side.

Where Lua really shines, and what is was actually designed for, is that it is probably the best language for embedding and extending other parts of the software written in C, C++ or Objective-C. Once you understand the Lua stack model, adding functionality to Lua is very easy. It is almost as easy as calling functions directly. Only thing that you need to do is to get the arguments from the stack, which is very easy.

Lua is actually a very powerful and flexible language, because it has metatables and support for closures. You can do a lot with these features. I am currently working on two-player Tetris clone, and I can forward function calls automatically to the other player with this piece of code:

function create_peer_opponent(page_name)
    local opponent = {}
    local mt = {__index =
                function(table, key)
                    function remote_call(...)
                        local str = page_name .. "." .. key .. "("
                        for k, v in pairs({...}) do
                            str = str .. tostring(v) .. ", "
                        end
                        str = str .. "nil)"
                        ui.rpc_call(head_to_head, str)
                    end
                    return remote_call
                end}
    setmetatable(opponent, mt)
    return opponent
end

After creating the peer opponent, the rest of the code does not need to know if the opponent is a local AI opponent or a remote human opponent. The function calls will end up in the correct place automatically.

Of course, everything I want to do from Lua needs to be wrapped in the framework. Fortunately Objective-C is actually quite dynamic language, and the reflection support is pretty good. I might be able to leverage the reflection mechanisms to automatically create and use Objective-C objects from Lua, but I don’t know yet if it actually is possible or does it make any sense.

Another nice thing about writing the game logic in a scripted language is that I can implement the framework on other platforms, e.g., on Android, and use the same Lua code for the game. The platforms are not limited to mobile platforms; basically anything that has support C supports Lua.

If anyone is interested in using the framework, just let me know, and I might actually open source it.

  • Share/Bookmark

My short visit to video game industry

Ever since I got my first computer, a Commodore 64, I decided that I want a job as a guy who writes computer games. Well, I got a job in video game industry when I was 28 years old. By that time, I had a Master’s degree in computer science and seven years of experience in traditional software industry.

It was like dream coming true. Finally I could live my dream and program cool games for the rest of my life. I was so excited about the opportunity that I did not even care about the open office. There were no doors. Not even cubicles. Programmers in one area, graphic designers in one, and game designers had their own area. You could easily hear the game designers talk from the programmers’ corner. Obviously the managers of that company had never heard of the book Peopleware, which should be mandatory reading for every single manager and programmer in every company that does software.

My title was Generalist Programmer, because I did not have any special game programming skills like graphics or AI. I thought I would write code for the game the company was developing, and pick up graphics and AI skills a long the way. What I did not know that a really big part of Generalist Programmer’s duties were related to version management. I would spend a week every month merging our changes to the latest version of the 3D engine. I probably should have asked what my tasks were going to be, but I was so excited about the job that I did not do that.

Actually my only interesting task during my time there was creating a plugin for 3D Max, but I could not really focus on the task, because of the environment; People were having loud design sessions 20 inches from my desk, which made concentrating a bit difficult. Of course, I could have used headphones and listen to music to block out the noise, but listening to music actually prevents people from coming up with creative solutions, because the brain is already occupied with the music. I read this in Peopleware, and I think it might actually be true for me.

The other, more experienced, game programmers were not doing that much coding either. They were mostly using the editor that came with 3D engine and putting pieces of the game together. No-one actually did heavy programming full-time in that company. I knew that if the other guys were not programming that much, I would never be able to just program all day long, which was the only thing I wanted to do.

The situation was not as bad as it might sound, but it was such a big shock for me, because I had created these illusions in my head that game programming would be the coolest job ever. I came crashing down from my dreams. It was not at all what I imagined it to be. The pay was also pretty bad compared to regular programming jobs. After three weeks I felt so bad that I had to leave. One evening I came back to work after everybody had left and left my key on my desk. My boss and his boss were out of town, so I just sent an email explaining the situation. My boss called me the next day and I explained the reasons why I left.

Looking back at situation, I probably should have talked about these things immediately with my boss, but I didn’t. I just wanted out. My dream was crushed. I just wanted to write software. I am really happy that I tried to pursuit my dream. It did not work out for me, but at least I gave it a shot, albeit a short one.

  • Share/Bookmark

Why code lines still should not exceed 79 characters

I hate long code lines. I hate them with passion.

You might think that in the modern era of programming everybody has a big ass monitor with loads of horizontal space for the editor. Unfortunately you are wrong. What is the point of having a big monitor if you have to make the editor cover the whole screen? I have two 24-inch monitors, but I have one of them rotated 90 degrees, which makes the resolution 1200×1920. 1200 pixels is enough for a pretty wide editor window, but I always have two editor windows open side by side, which makes the editor windows 600×1920 pixels and that is about 2x79x120 in visible characters.

I am also old school and use terminal windows, which, as you can guess, are about 80 characters wide. It helps a lot if the code, does not wrap inside the terminal window when using version control commands from the terminal.

OK, so far the reasons have been pretty much about the environment and a lot of people have environments that support long lines easily. However, something that is universally bad about long lines is the way they affect the readability of code. Long lines make the code harder to read. If you have to turn your head when reading code, digesting the code will be much harder.

Code is read more often than it is written, so writing elegant code should be the goal of every single programmer. It is much easier to get a complete picture of the code, when the lines do not run forever. There is also a reason why books are shaped the way they are. Who would like to read a book that has lines over 150 characters long?

People post questions to stackoverflow.com and sometimes include source code related to their questions, which is really useful. However, the code window is only 79 characters wide and there will be a horizontal scroll bar, when the code does not fit in the window. That is really annoying. Trying to figure out what is happening in the code when you cannot see full lines of the code is really hard. I am not blaming stackoverflow.com, but I am blaming the programmers, who post sample code that have long lines.

Sometimes code needs to be printed. Not that often, but there are good reasons to do that. If code looks like crap on screen, it will look even worse on paper especially with those long lines wrapped in the printed version.

Every time I see long lines, my respect for the author of the code drops a little. I do not think there are any excuses for writing long lines. Every programming language I have used supports splitting code to multiple lines. Some languages do it better than others, but the language is not the problem.

The problem might be the editors that most people use to write code. Usually when I see long lines, the code has been written in either Visual Studio, Eclipse or Xcode. People that use those IDEs have their environment full-screen, which makes the editor window quite wide. The template code that IDE will generate is usually terrible and people just copy ‘n paste that crap. Editors also indent lines differently when you split them, or do not have automatic indentation support for lines that where split. This might cause the writer of the code to avoid splitting, because it will require pressing the tab 6 times to get to the correct indentation point. Configure your editor to do this for you. (Or even better, use a real editor)

  • Share/Bookmark

What's with the DWORDs

If don’t know what a DWORD is, good. This is quite geeky so don’t read any further, unless you want to know what wrong with DWORDs.

If you have ever taken a look at windows.h, you know what I am talking about. For some reason Microsoft decided that they need to define every single type themselves, because the original types did not shout enough. VOID is clearly a lot better than void, but what the hell is the reasoning behind LPCSTR? It looks like vomit. I don’t want that my code looks like shouting vomit. What the hell is wrong with ‘const char *’?

The big problem is not that Microsoft re-invented types with this stupid system, but it is a big problem that some so-called professional programmers actually use those wonderful types in code that should be cross-platform. When they realize that their code needs to work on something else than their beloved Windows, they make nice typedefs for linux and others. Only problem here is that everybody has their own idea what DWORD should be defined. This is where the fun starts. There are situations where you might need to include to different headers files, but both of those header files define DWORD differently. Nice.

  • Share/Bookmark