Archive for the ‘Programming’ Category.

A quick rant(s)

I have a software pet peeve. Have you ever seen something like this:

1 update(s)

or, even worse, this?

1 updates

Well, I think this is ridiculous. Do you know why I think this is ridiculous? Because it’s 2012, and programmers have really good “if” statements available to them! :P

Haiku Programming: Saving Settings

I think one of the biggest differences between Linux and Haiku is that of having a standard way of doing things. I probably be talking about this difference a lot in the future.

Disclaimer: I’m very new to Haiku programming, so I may make mistakes or not do something the Haiku way. Please correct me if you see any errors. Thank you!

I worked on my RSS feed aggregator a bit over the weekend. I began implementing saved settings.


There are many ways to save settings in Linux. You can save settings by using GConf (which I just found out is being deprecated in favor of Gsettings). You can use a text file (please make sure to ask xdg where to save it, and not just throw it into the home directory!). Text files can be XML or Lua or old-timey-X-style (whatever that’s called) or made up just for your application. This is probably an over simplified representation of settings files in Linux, but my point is that there’s no single standard way of doing it.


The Haiku Human Interface Guidelines explain the standard way of saving settings in Haiku. It involved saving data into a BMessage and then flattening the BMessage into a file. Later, the file can loaded (unflattened) into a BMessage and the settings can be taken out of it.

The Haiku API includes a simple way to get the user’s settings directory:

BPath settingsPath;
find_directory(B_USER_SETTINGS_DIRECTORY, &settingsPath);

The current default user settings directory is “/boot/home/config/settings”. Use the Append method to add a nice name for your settings file:


This will make your settings file “/boot/home/config/settings/MyHaikuApplication”.


BMessage objects are integral to the Haiku API. Here’s a concrete example of what a BMessage looks like. For a BMessage object named “msg”, it has a “what” type (an integer) that can be used to determine the type of BMessage:


I don’t use this for saving settings. It has another (very important) purpose that I’ll talk about some other time.

The other thing it has is a whole mess of named data. Here’s a quick example. I’ll save a number into a BMessage:

msg->AddFloat("Pi", 3.141592654);

I can also retrieve it:

float value;
msg->FindFloat("Pi", &value);

As you can see from the documentation, a BMessage can store all sorts of data, include any object or structure. It can even store more that one copy of named data. For example, all of these values will get stored:

msg->AddString("Address", "123 Business Drive");
msg->AddString("Address", "386 Computer Street");
msg->AddString("Address", "7 Internet Superhighway");

They can likewise be pulled out again by using the FindString method. BMessage objects can also store other BMessages. In summary, BMessage objects can allow you to easily store and retrieve data.

Flatten It

To save a BMessage object to file, “flatten” it using the Flatten method. Just send it a pointer to a BFile:

BFile file(settingsPath.Path(), B_CREATE_FILE | B_ERASE_FILE | B_WRITE_ONLY);
if (file.InitCheck() == B_OK)

Unflattening a file is just as easy:

BFile file(settingsPath.Path(), B_READ_ONLY);
if (file.InitCheck() == B_OK)


Java has a way of serializing objects. This allows you to save an object to a file and then open it again. It sure can be handy, but if you make a change to the class then you can’t open the saved object anymore (as far as I know). The Haiku way of using a BMessage with named values in it doesn’t have this problem. You can always open it and try to read values from it. If the name of a value has changed or is new, then the find will fail and you can simply use a default value. Then, when application quits, you can overwrite the old settings file with the new one.


I’m a Linux user, and I know the benefits of having settings saved in a plain text file. I don’t know of an easy way to extract information from a flattened BMessage besides loading it in an application. Even so, the benefit is that it makes the application responsible for controlling the settings file, even if it means creating a GUI that allows the user to change some settings. Haiku is a desktop operating system. It was designed to be used with a GUI and a mouse. It was also designed to be easy to use. A plain text settings file might be as easy to use as a GUI, but a GUI can allow settinsg to be more discoverable.

An Advanced Case

My RSS feed aggregator has some numerical settings, but it also has more advanced settings. I need to keep track of every “Feed” that the user wants to follow, and every news “Item” in that feed. That’s a list of Item objects inside a list of Feed objects.

I got advice from An Evil Yak, a nice Haiku developer. I decided to create one BMessage for every Feed and one BMessage for every Item. I’ll then add the Item message objects to their corresponding Feed message objects, and all of the Feed message objects to the main settings message object. I’ll then flatten that message to a file.

Software on Haiku

I’ve been spending a lot of time using Haiku recently. I had a particularly fun night recently.

I’ve been itching to contribute some nice software to Haiku for a while. Last year I made my first piece of Haiku software: a screensaver of pretty falling leaves. It seemed like a good place to start for me since I like making video games, and screensavers are pretty much just video games without any user input.

My plan for my next piece of software is to pick a nice library, compile in on Haiku, and then write a native GUI to interact with it. I decided to start by writing an RSS client. It’s coming along slowly but fine.

It’s funny, there’s “no software applications for Haiku”, but at the same time, every time I think I have a great idea to fill in some functionality gap, I find out there already is an application for it in Haiku that works fine. Combine that with the WebPositive web browser and you now have a ton of functionality that’s provided by websites (RSS feed readers, email, document creation…) Probably the biggest application gap I see is that there’s no native word processor, but it’s really hard for me to care. I don’t really use word processors in any operating systems.

Lastly, here’s my usual list of some of the stuff I did in Haiku recently:

  • Log in to my MSN, Yahoo, AIM, and Gmail chat accounts using Caya
  • Download YouTube videos using youtube-dl and watch them using MediaPlayer
  • Listen to music while I program using a playlist in MediaPlayer
  • Host a simple static web page using PoorMan (a “poor man’s” web server)
  • Create a new software project with the Paladin IDE, setup a new project on SourceForge, and sync my work using git
  • Check my email and visit various websites using WebPositive
  • Use BePDF to view some documents that were emailed to me
  • I had some fun trying out and voting on some of the new software releases on Haikuware.

In the past I’ve downloaded files through bittorrent using Transmission, but for some reason it wasn’t working last week. I didn’t really look into it, but I think I was trying to use a crummy seeds.

I plan on spending more time in Vision, the native IRC client, to learn more about software development in Haiku.

Oh, I almost forgot! I resized my partitions and gave myself a new Haiku native partition. So I now have a partition for the Arch Linux operating system, the Haiku operating system, my Linux personal data, and my Haiku personal data. This way I don’t have to fret when upgrading.

Software development lessons

  • There should be clear communication about what the problem actually is.

Don’t solve the wrong problem.

  • Solve the problem to meet specifications.
  • Perform test driven design.

If you are unsure of your goals then you’ll never reach them.

  • Use debugging tools.

You can find and fix the problem much faster using debugging tools instead of print commands or, worse, randomly changing things.

  • Don’t repeat yourself.
  • Create a personal collection of software tools and libraries that I wrote.

Learn from the work you do, and keep it with you in order to use it in the future.

  • Write modules with a single responsibility.

If a module tries to do more than one thing, splitting it up will probably make the design easier.

  • Write against interfaces, not classes.

Even if it seems simple and silly to write a simple interface for a single class to use, chances are, in a big project, having it written against an interface will very likely make your life easier in the future.

  • Learn how the entire software system works.

If you can be that person on the project that knows what every part of the system does, you’ll be invaluable.

Steps for being a good programmer

Here are some general pointers I try to remember when writing code. Even though following these guidelines always helps me, I do a poor job at following them. So, I’m hoping that¬† I’ll follow them better if I write them down here.

Work from the top down

    This can be a nice way to ease into writing . Think about what you want the code to do and write a function name that represents it. (for example, play_game(…)) Then, think about what you want that function to do, and write function names that represent it. (initialize_game(…), update_game(…), draw_game(…)) Keep doing this until you have super simple functions that need to be filled in to make everything work.

    Design good data structures

      This applies to both object oriented design and not. Spend time designing good data structures and objects. Design good relationships between them. I’m not going to describe what makes a data structure good or bad here, but for some reason I can always tell the bad ones when I begin trying to use them in functions.

      Design good simple functions

        Similarly to designing good data structures, design good simple functions. For example, if you have a function name that has the word “and” in it, it may be time to reconsider the design of your code.

        Break the problem down into smaller parts

          This is a more general way of summarizing all of the points above. Writing a new application may be a daunting task. Break the problem down into smaller problems, until the problems that remain are simple and easy to solve.

            If you don’t have the data you need, move the functionality up to a higher level function

            This one’s a little tricky to describe. If you’re working in a function and you seem to need to keep sending more and more data structures as parameters, stop and reconsider if that function is really the right place for all of that logic to happen. Consider moving it up into the function that calls that function instead. This principle seems to help me pretty often.

              Code for the specific application you’re working on

              This is one of the most important points in this list! It’s easy to think it’s a good idea to make your data structures and functions work well for other programs or “future projects”. You know, making your code generic and “reusable”. Well, stop it. The future projects you’re thinking of probably won’t ever get written, and you’ll waste time making your code generic instead of just making it work well for the program you’re working on.

              I hate C++

              I hate C++. I will never ever use it by choice to write software again.

              C has been my favorite programming language for many years, but I never really did anything with C++.

              I’ve decided it’s incredibly wordy, error messages from the STL are really hard to read, there are so many things I need to do myself instead of having the compiler take care of them for me, there are many ways to do everything, it takes an incredibly long amount of time to compile my small application, and the standard library is so small and painful to work with. I could go on and on.

              I don’t hate pointers, I don’t need automatic garbage collection, but holy moley it feels like everything that’s been implemented in C++ has been done in the worse way possible.

              Why is this language so popular? It has almost an infinite number of features, which can be nice I suppose. If you want a fast, compiled, object oriented capable language then there traditionally aren’t too many options. Some others are Ada and Objective-C.

              I may have made a mistake. Before working on my first C++ application, I wrote my first Python application. I think Python spoiled me.

              I wish there was a language that was like Python but compiled like C. I’m sure many programmers want the same thing. Maybe one exists, but if it does I don’t think it’s very popular yet.

              For now, I think I’m going to start using Python a lot more. Throughout my life as a programmer, I’ve written software in assembly and C. I’ve learned a lot about good programming principles and managing all of the details in the code myself.

              But I’m getting of tired of it. Writing code in a language like C++ can be kind of fun, but I never get anywhere. Alternatively, with Python I can have fun and actually finish an application.

              Contributing to the FOSS community

              In what ways have I contributed to the free and open source software community? And what can you do to help? Here are some thoughts.

              I love helping FOSS projects, but it can be difficult to decide what to do.

              Keep it simple

              Choose a project where you need to learn one thing at a time.

              There are languages (examples: Python, C), libraries (examples: GTK, Qt), and programming paradigms. (examples: GUI programming, threaded programming) When you begin working on a project, you will probably need to learn something new. Try to learn only one thing at a time. For example, if you have to learn gstreamer and GTK (two libraries) at the same time then you might become frustrated. Or, if you have to C++ and Qt (a language and a library) at the same time then you might become frustrated.

              So, try to learn one thing at a time.

              Working with other FOSS developers

              I love working online with FOSS developers. When I get to talk to the lead developer of a project, it feels like I’m talking to a celebrity.

              Of course, you should join the mailing list and bug tracker for the project you want to work on. I don’t usually introduce myself. Instead, I just start helping, and people will know me soon.

              My FOSS experience

              Here are some examples from my FOSS experience.

              Many years ago, I wanted to write a new FOSS application. I couldn’t think of any new applications to make, so I decided to make a video game. There are never too many video games.

              I learned many things by making video games:

              Languages: C, Objective-C, Java, Assembly, Ada

              Libraries: Allegro, SDL, Java SWING

              I’ve submitted many bug reports to many different projects, such as wxWidgets, Allegro, Udiskie, and Haiku. I really like submitting bug reports and working with the developers to fix the problem. It’s easy to do and I get to use better software.

              I maintain some AUR packages. (very easy, but it helps FOSS)

              I helped write the documentation for some software from the Arch Linux community, such as Packer and Udiskie. I’ve contributed to the Arch Linux wiki.

              Recently, my wife and I wanted a new application for budgetting. I decided to write one. I used Python and wxWidgets. It works pretty well. My next goal is to convert it to C++ and wxWidgets, and then make a version for Haiku using C++ and the Haiku API.

              Interesting things

              You should definitely work on something that you think is interesting. To me, that’s Arch Linux, Haiku, bug reports, and documentation. Try to find things that are interesting to you!

              Lastly, don’t make your goal too big and don’t try to do too much. There are many many people helping in FOSS. If everyone does a little bit, then we can make something great.

              The return of malloc

              Should you always check the return value of malloc? There’s a heated debate over the answer.

              One group insists that, in good software development, you always check the return value of a function, including malloc. It appears that most software developers are in this group.

              The other group thinks otherwise. I’m in this group. Here’s why.

              I was taught, like many programmers, to always check the return value of malloc. This thread made me think otherwise:¬†Always check malloc’ed memory? The asker raises many interesting points.

              When thinking about checking the return value of malloc, it’s important to consider the operating system, hardware, and type of software that you are working on. Linux may behave differently from FreeBSD, a desktop computer may behave differently from a mobile phone, and a GUI application may need different considerations than a shared library. Also remember that it may not even be your application that is causing malloc to fail.

              I’m primarily concerned with the case of a GUI application running on Linux on a desktop computer, because that’s what I work on. Even so, it’ll be fun to think of the other cases.

              Failure Response

              So, let’s say you check the return value every time you use malloc. What do you when a return from malloc fails? You could simply quit your application immediately. You could try to quit your application gracefully. You could cancel the command that caused the fail and display an error message. You could loop until either malloc returned a valid result or the computer catches on fire.

              Can You Respond?

              Let’s pretend that malloc failed. Imaging the state that the computer is in that caused it to fail. Would it still be able to do any processing at all? I agree that it is extremely important for an application to never lose the user’s data, but would the computer even still be able to recover anything at that point?

              Does malloc Fail?

              In Linux, malloc may never even fail. On the malloc man page under “Bugs”, it states that just because malloc didn’t fail doesn’t mean it has enough memory.

              The Trial

              So, I wrote some code to try and make malloc fail. When it does, it tries to recover and quit gracefully.

              #include <malloc.h>
              #include <stdio.h>
              #include <stdlib.h>
              typedef struct NODE
                int data[40000000];
                struct NODE* next;
              } NODE;
                NODE* node;
                NODE* first;
                NODE* last;
                int stop;
                int count;
                first = NULL;
                stop = 0;
                count = 0;
                while (!stop) {
                  node = (NODE*)malloc(sizeof(NODE));
                  if (node == NULL) {
                    printf("FAILED! %d \n", count);
                    stop = 1;
                  } else {
                    if (first == NULL) {
                      first = node;
                      last = node;
                    } else {
                      last->next = node;
                      last = last->next;
                count = 0;
                node = first;
                while (node != NULL) {
                  last = node;
                  node = node->next;
                printf("FREED %d \n", count);

              The Results

              Here are the results when running it on three different operating systems.

              Arch Linux: After 55 seconds, the message “Killed” was displayed. This was a message from the operating system, not my code. My program never had the opportunity to see a failure from malloc nor try to cleanup after it.

              Haiku: Almost immediately the program stopped. The output was “FAILED 10, FREED 9″. That means that after trying to allocate about half a gigabyte of memory, it failed to allocate anymore and was able to clean up the stuff it had.

              Windows XP: The results were similar to Haiku: Almost immediately the program stopped. The output was “FAILED 12, FREED 11″.


              By using this simple test, it appears that checking the result of malloc can be a worthwhile task. My conclusion is contrary to my feelings from the beginning of this post. I think I just might have to change my programming habits.

              My new love: Python + wxPython

              I have a new love. It’s Python with wxWidgets. Add xwGlade, and I think I’ve found programming nirvana.

              I’ve been programming in Python for a couple of weeks now. I find it very easy to learn, writing code is super fast, I don’t have to waste my time writing things that the language already understands, it’s well documented, and it’s pretty to look at and read. That also happens to be pretty much everything I’d read about Python. As an interpreted language, I’d also heard that Python is slower that C, but I certainly haven’t noticed it being slow.

              I also started using wxPython about two weeks ago. It was easy to learn and make a GUI with, and the GUI I made looks great on both Linux and Windows.

              wxGlade was dead simple to learn. I was able to throw together a GUI really quickly and start adding functionality to it.

              Here are some of my favorite sites for learning wxPython:

              I have very little time to work on personal programming projects, but working with Python + wxPython + wxGlade has been extremely fast and fun.

              Somebody already made that!

              I wanna write an application for Haiku, but every time I think of something to make and begin writing down ideas for it, I find out it already exists!

              I was all excited to start working on a personal finance and budget application when I found out about BeFinancial. Recently it’s even been released as open source software.

              With Linux I think of it as normal to have many different applications that have very similar functionality, but with Haiku that just doesn’t seem to happen as much. Reasons that happen with Linux include:

              Different toolkits – On Linux there is GTK+, Qt, FLTK, Fox, GNUStep, and on and on. On Haiku there is one standard toolkit.

              GUI vs CLI – Haiku was designed from the beginning to have a fast and easy GUI, although it is still simple to a terminal window with BASH.

              Heavy vs light – Haiku applications feel fast and light, even when they are “heavy”. Haiku applications are written to use functionality provided elsewhere as much as possible. For example, emails are saved simply as files in a folder.

              Maybe I should think simpler. Maybe I should think, “What do I want to use my computer for that could be made easier and faster by having a special application?”