Functional is not Procedural

January 5th, 2010

I’ve recently seen some confusion about the terms functional and procedural in the software development community. Let me spend a moment trying to clear things up for (both of) my readers.

First of all, just because a programming language has functions, that does not mean it is functional. In fact, its confusing name has nothing to do with functions. The history of the term function, as used in the computation world, hails back to the 1930′s when Alonzo Church created Lambda Calculus to be able to use and define mathematical algorithms on paper. Later, when computers arrived on the scene, programmers adopted the term function to describe a chunk of code that could be re-used by other chunks of code. Functions, in this context, have been adopted by every programming language I know of, including assembly language. Functions are commonly referred to as “routines”, “subroutines”, or “procedures”. Some might even argue that a “method” is pragmatically identical to a function.

Here’s where the confusion begins.

This is hard to explain rigorously, but here goes anyway.

Some languages, like C, tend to encourage computer programmers to make use of functions. Programs written in these languages tend to consist of a set of functions, and a “main” function that kicks everything off. Such a language is often referred to as “procedural”, but really the term “procedural” refers to a style of programming, and does not really describe a language, per se. It is often used incorrectly as an antonym to the concept of “object oriented”. But procedural programming can be equated to functional programming in the same way a bingo game can be equated to a trip to Las Vegas.

Other languages, like Scheme and Haskell, tend to encourage computer programmers to write code with functions that avoid internal state changes and produce no side effects when called. For example, these language discourage global variables, and particularly the calling of functions that would mutate global variables (that would be a side effect).

To sum up.

Procedural programming languages can be functional or not. Functional programming languages can be procedural or not.

Here’s a table:

Language Functional Procedural
C No Yes
Haskell Yes Yes
Python Can be Can be
C++ No Can be (if you write it like C)
Java No Usually not
OCaml Yes Yes

If you take nothing else away from this article, take this: The C programming language is not a functional language. It’s not bad, it’s just not functional.

Technology Predictions for 2010

January 1st, 2010

My brain’s been a stewing about 2010, and I just gotta let it all out. If I’m even half right, 2010 will be awesome.

1. Hulu in the Living Room

In 2010, Hulu will partner with a company like Western Digital or Popcorn Hour to release a tiny box that connects to your HDTV to watch TV shows and movies, streamed from Hulu’s servers. The box will cost less than $100, and have no monthly subscription, because its development will be subsidized by Hulu’s ad revenues. If it’s not released in 2010, it will at least be announced.

2. Cable Networks Become Record Labels

Just like iTunes changed the music industry, online media and broadband Internet access will start to change the TV industry. It remains to be seen who will be the big player (my money’s on Hulu), but one thing is for sure: Americans will have a choice when it comes to buying subscription TV services. The trend will begin in 2010, allowing consumers to get on-demand TV content for free, and will finish some time in the future with cable companies either totally transforming into something like modern record labels, or going out of business.

3. HDTV Sales Will Boom

HDTV’s have gotten so inexpensive that nearly every American household will have one by the end of 2010. This will be driven by the fact that online media will be so easily accessible that most people won’t need to buy cable, so they can easily justify the cost of a new $500 TV.

4. Qt’s Best Year

Companies who develop desktop application software that needs to run on Mac and Windows will simply have no other choice for their developers than Qt. That trend will strengthen in 2010 to the point that it’s a no-brainer decision over platform-specific choices like .NET, Cocoa, and others. Qt has matured so much over the last 5 years that its toe-hold in this market will grow to a full Nelson in 2010.

5. Model Aviation Takes Off

Model airplanes have gotten very popular and accessible. Manufacturers have pushed prices down so low that anyone can afford to get into the hobby. Batteries, R/C electronics, and planes have gotten cheaper, and planes have gotten easier to fly for the novice pilot. The entry-level model airplane market will take off in 2010.

Your Turn

Do you agree with my predictions, or am I totally off?

Have any predictions of your own?

Apple Time Machine User Interface Win

October 25th, 2009

Earlier this year, a shiny new iMac graced my home (increasing my resale value by about 10%, according to Zillow). Since then, I’ve had to replace my keyboard three times due to drool damage.

It happened again tonight, this time compliments of the Time Machine menu bar icon (I know, it’s a curse).

I noticed months ago that the icon spins while Time Machine is backing up my iMac. But that’s not the drool feature. The little hands on the clock spin, but they go backwards! It’s a gentle reminder that Time Machine lets you go back in time to restore your files.

Awesome, but now it’s time for another new keyboard.

R/C Stryker Slope Glider

October 14th, 2009

I finally took my newly built Stryker to the slope for some unpowered slope gliding at Ensign peak in Salt Lake City, Utah. I built the Stryker with these parts:

I did not put a motor on the Stryker and used a tiny battery. It slopes beautifully in 15-20mph wind. In fact, I had to add some weight to get better penetration.

I highly recommend the Stryker for slope flying.

Cool QProgressBar Stylesheet

October 13th, 2009

Qt’s powerful stylesheet system can make your boring progress bars look really cool.

Screenshot:

Here’s the code:

QProgressBar {
border: 1px solid black;
text-align: top;
padding: 1px;
border-bottom-right-radius: 7px;
border-bottom-left-radius: 7px;
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,
stop: 0 #fff,
stop: 0.4999 #eee,
stop: 0.5 #ddd,
stop: 1 #eee );
width: 15px;
}

QProgressBar::chunk {
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,
stop: 0 #78d,
stop: 0.4999 #46a,
stop: 0.5 #45a,
stop: 1 #238 );
border-bottom-right-radius: 7px;
border-bottom-left-radius: 7px;
border: 1px solid black;
}

And here’s the .ui file you can open in Designer (right-click that link and choose “Save as…”).

Happy hacking!

LDS General Conference Podcast Updated for October 2009 Sessions

October 4th, 2009

I added the October 2009 sessions to the podcast. If you’re already subscribed, you don’t have to do anything. iTunes (or other podcasting software) will download the latest sessions automatically.

To subscribe to the podcast, visit the LDS General Conference Podcast page.

Lock Free Multithreading in Qt

September 30th, 2009

If multithreading is challenging to get right in your applications, then lock-free multithreading is down-right killer.

This article won’t go into detail about lock-free algorithms, but instead I will offer a “poor man’s” method for crossing thread boundaries in Qt without using locks (no mutexes, no semaphores). At least, your code won’t have any locks. More on that later.

For years, Qt has sported an easy-to-use threading library, based around a class called QThread. As of Qt4, you can use QThread to start your own event loops. This might sound somewhat uninteresting at first, but it means you can have your own signals and slots outside the main thread. The Trolls created a new way to connect signals to slots such that signals can actually cross thread boundaries. I can now emit a signal in one thread and receive it in a slot in a different thread. This is hugely useful when you want to, for example, integrate a blocking-happy library into your application. Here’s what I’m talking about in pictures:

Signals can arrive at any time from the threads, just like any other signal, and the code in the main event loop doesn’t know anything about multi-threading, locks, or condition variables.

An Example

Let’s say you want to integrate with a third-party library that blocks when you call its functions. Of course, if you call this library from your main event loop, your application will freeze while it’s running. That would be annoying, and you can give your users a better experience than that. Let’s wrap that library in a QThread. First, you need to declare a new QThread subclass, like this:

class MyLibraryWrapper : public QThread
{
Q_OBJECT
public:
    MyLibraryWrapper();
protected:
   void run();
signals:
   void done(const QString &results);
private slots:
   void doTheWork();
};

The run() method is called automagically by Qt when the caller calls start() on your thread. This is similar to how Java’s Thread class works.

The done() signal is how the object tells you it is finished with its work. It emits a QString in this example, but it can emit anything you want (note that if you want to emit non-primitive or non-Qt types, you need to use the Q_DECLARE_METATYPE() macro, which we won’t go into in this article).

The doTheWork() slot is there to actually do the blocking work. It has to be a slot so we can put it to work after our event loop starts up (which you’ll see in a minute).

Now for the implementation of MyLibraryWrapper:

MyLibraryWrapper::MyLibraryWrapper() : QThread()
{
  // We have to do this to make sure our thread has the
  // correct affinity.
  moveToThread(this);

  // This will do nothing until the user calls start().
}

void MyLibraryWrapper::run()
{
  // This schedules the doTheWork() function
  // to run just after our event loop starts up
  QTimer::singleShot(0, this, SLOT(doTheWork()));

  // This starts the event loop. Note that
  // exec() does not return until the
  // event loop is stopped.
  exec();
}

void MyLibraryWrapper::doTheWork()
{
  // Do the heavy-duty blocking stuff here
  // (simulated by a 5 second sleep for
  // this example)
  sleep(5);

  // When you're done, emit the results:
  emit done("First job's finished.");

  // And some more sleeping for fun
  sleep(3)
  emit done("Second job's finished.");

  // ...
}

To actually use this new class, all you have to do is instantiate it in your main event loop and connect it to a slot. Here’s an example. Let’s say you have a QMainWindow called MyMainWindow. This is how you would set it up as a result of a user button click:

void MyMainWindow::on_someButton_clicked()
{
  MyLibraryWrapper *wrapper = new MyLibraryWrapper();

  // This is the magic that tells the wrapper to
  // notify us when it's done. We use a QueuedConnection
  // to make sure Qt delivers the signal in a thread
  // safe manner
  connect(wrapper, SIGNAL(done(QString)),
          this, SLOT(wrapperDone(QString)),
          Qt::QueuedConnection);

  // This kicks off the wrapper's event loop by causing its
  // run() method to be called
  wrapper->start();
}

void MyMainWindow::wrapperDone(const QString &results)
{
  // The wrapper is now done with its long, blocking
  // operation, and we didn't freeze the application.
  // Yay for us!

  qDebug() << "Here are your results:" << results;
}

Conclusion

Notice that none of our code uses a semaphore, condition variable, or mutex? Using QThread makes it super easy to wrap up libraries that need to block the event loop in a way that is transparent to the caller.

I claimed earlier that this code would be “lock free”. I can’t actually claim that is 100% true. I don’t know for sure, but I imagine that Qt’s internal event loop code does indeed use locks to pass signals between event loops. All I know for sure is that this code crosses thread boundaries without any locks.

Stay tuned for another article that shows how you can call setter functions on your threaded objects without any need for locks.

Model/View/Presenter and Qt?

September 27th, 2009

Here’s a question for Qt hackers:

Does Qt implement the Model/View/Presenter design pattern?

The short answer is (drumroll): it depends on some stuff. Let’s dive into it and give you a real answer.

First of all, I am no Model/View/Presenter expert. I’ve only read what little information is available online, and I’ve never implemented an application with it (though it turns out that I’ve been using it for years on accident). Bottom line: Please correct me.

If you search the Qt documentation, you won’t find any mention of this design pattern (although the more prevalent Model/View/Controller does make many appearances).

Before we start, we should define Model/View/Presenter. The MSDN and Wikipedia summarize it thus:

  1. It is a multi-tiered design pattern that helps separate display logic from business logic in a testable way.
  2. The View is kept as thin and ignorant as possible
  3. It enables better automated unit testing (and helps prevent relying on awkward UI test runners)
  4. It moves lots of logic out of the View and into the Presenter (things like input validation for example)
  5. The Presenter should be common to multiple views (though I’m not totally sure on this one — please correct me)
  6. Methods in the Presenter should not return a value (i.e., void) and should take no arguments.

Let’s look at a typical Qt application. I like to use Qt Designer to design as much of my user interface as possible. Doing so, my source code tends to look like this:

Qt veterans should be able to identify the boxes in this graphic quickly, but for those of you who don’t work in Qt every day, let me explain.

Your Data Model

The data model is a class (or set of classes) that provides access to your app’s data. It emits signals to tell you when its data has changed (like if another app changed the data), and provides slots you can call to change the data yourself. You may have, for example, a list of User objects in your app, and maybe they are all contained within a UserModel class. When a user’s phone number changes, your model may emit a signal called phoneNumberChanged(). If a new user is created, the UserModel would emit something like userAdded(User*) and likewise userRemoved(User*) when a user goes away.

Your Widget Subclass

When using Designer, you have to choose a QWidget-derived class from which your widget will inherit. Your widget may be a dialog, a main window, or even a nested widget inside some scroll box. Your widget subclass will usually connect to the data model’s signals (userAdded(), userRemoved(), and friends). Its job is to notice when the data model changes, and represent that on the screen by manipulating the view. It is also responsible for taking user input and pushing it into the model (like when the user wants to change a User‘s phone number, for example).

Generated UI Class

When you create and save a form in Qt Designer, it gets saved with a .ui extension. This file actually contains a bunch of XML that describes how you laid stuff out on the screen. Qt provides a tool called uic that takes that XML file and produces C++. uic stands for User Interface Compiler. The code that it generates is the view. It only does one thing: Draw crap on the screen, and tell you when the user does stuff. It is an extremely thin UI layer. So thin in fact, that it cannot implement any business logic at all. It’s simply not possible. The code is generated and unalterable (unless you’re an idiot and think it’s okay to go hack that code after it’s generated — hey, I’ve done stupid stuff too).

Now let’s apply some labels to our diagram:

I believe the widget subclass actually does conform to all the rules of a Presenter, even though it doesn’t conventionally bear that name. Let’s look at the rules again and see if it fits the bill:

  1. Separates display logic from business logic: Yes
  2. The View is thin and ignorant: Yes
  3. Enables automated unit testing: Yes (you can write unit tests against your widget subclass quite easily)
  4. It moves UI-related logic out of the View into the Presenter: Yes In fact, the View can do almost no input validation at all (unless you specify inputMasks in Designer, and note that QValidators are instantiated in the widget subclass).
  5. The Presenter should be common to multiple views: No Qt could allow this, but most people just don’t do it (perfectly possible, but I’ll discount it because it is not used in practice or recommended in the docs).
  6. Methods in the Presenter should not return a value: Yes Your widget subclass’s slots have to be void (and even if you do specify a return value, Qt ignores it anyway, so Qt actually enforces this requirement).

Conclusion

Qt can most definitely implement Model/View/Presenter, and in fact, the Qt documentation recommends exactly that, though they never use the term “Presenter”. You should probably also read up on the Model/View/Presenter’s latest development, since some argue that the term ought to be retired and replaced with new terminology, which coincidentally fits even better with Qt conventions.

What do you think? Does Qt actually implement this Design Pattern? It’s pretty important to recognize this stuff, or we can end up screwing up pretty bad.

Qt Stylesheet Sidebar Tutorial

September 18th, 2009

In some applications, a nice looking sidebar can really add some polish. In this tutorial, we’ll show you how to make a sidebar using nothing but Designer and Qt’s stylesheets. When we’re done, we’ll have this:

Step 1 Open Designer and create a new widget for your app. Enjoy the blank slate for a moment. When you’ve had enough zen, move on to step 2.

Step 2 Drop a couple QFrames onto the widget.

Step 3 Apply a horizontal layout to your widget (click on the background and then click the horizontal layout button in the toolbar). Then give the left-hand frame a maximum size of 200. This will become the sidebar and we don’t want it to occupy half of the screen. You may have to tweak this in your application depending on your user’s font size.

Step 4 Name your left-hand frame “sidebarFrame” and then add this stylesheet code to your widget (right-click on the top-most node in the Object Inspector and select “Change styleSheet…”).

#sidebarFrame {
background: #8af;
border: none;
border-right: 1px solid black;
}

This gives the sidebar a blue background and a single-pixel black border between it and the application’s main content area, like this:

Step 5 Drop a QFrame inside the sidebarFrame on the left.

Step 6 Add a custom property to the new QFrame that you just dropped on the widget. Do this by clicking the green “plus” sign in Designer’s property editor and picking “String”. In the popup dialog, type the word “class” (without quotes). By doing this, we are giving this widget a custom property named “class”. In the property editor, type the word “SidebarFrame” for the “class”. This should appear at the very bottom of the property editor.

After giving your new frame a class, add this style sheet code to your stylesheet:

QFrame.SidebarFrame {
border-top-left-radius: 10px;
border-top-right-radius: 10px;
border: 1px solid black;
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #56a, stop: 0.1 #016);
}

Now you should have this:

Step 7 That forms the outside of the frame. Now we’ll do the interior. Drop a QLabel and a QFrame inside your new QFrame, like this:

Step 8 Give the inner QFrame a custom “class” property of “SidebarInnerFrame”, and add this style sheet code:

QFrame.SidebarFrame QLabel {
color: white;
font-weight: bold;
}

QFrame.SidebarInnerFrame {
background: white;
border: none;
border-top: 1px solid black;
}

That will stylize the QLabel (which will be the title label for this box) to give it white, bold text. It will also stylize the inner frame to be white. You should have this now:

Step 9 Now layout your box by clicking on the box and then clicking the vertical layout button. Afterwards, give it the following spacing and margins in the “Layout” section of the property editor:

layoutLeftMargin 0
layoutTopMargin 5
layoutRightMargin 0
layoutBottomMargin 0
layoutSpacing 5

Having done that, you should see this:

Step 10 Drop some checkboxes or something inside your box and lay them out vertically (do this by clicking on the inner frame and then clicking on the vertical layout button). Then click on the light blue sidebar frame and give it a vertical layout. Insert a vertical spacer in the bottom, and you should see this:

Step 11 Now that you have your styles and layouts in place you can copy and paste the sidebar boxes to your heart’s content. You can name them whatever you want because we are using the “class” custom property to stylize them. These boxes can contain any widgets you like.

As an exercise for the reader, figure out why you can’t read the text of QLabels when you drop them inside these boxes.

Enjoy your finished product:

I am consistently impressed at how powerful Qt’s stylesheets are. You can do some really neat things with very little effort, all in a friendly WYSIWYG environment.

Happy hacking!

Qt Stylesheets Button Bar Tutorial

September 17th, 2009

To demonstrate the awesomeness of Qt’s stylesheets, we’ll make a modern looking button bar (inspired by Qt Creator) that looks like this:

Let’s get started

Step 1 Open Designer and create a new empty widget:

Step 2 Toss a couple QFrames on the widget, one above the other. Name them topFrame and bottomFrame, like this:

Step 3 Apply a vertical layout to your widget (just click on the background area and then click the vertical layout button in Designer’s toolbar. It should look like this now:

Step 4 Drag and drop a few buttons and a horizontal spacer onto the frame you called “topFrame” (don’t forget to name it if you haven’t already)

Step 5 Apply a horizontal layout to the “topFrame”

Step 6 Set the vertical size policy for the “topFrame” to “Fixed”. This makes it shrink to a minimum size and lets the bottom frame grow to fill the rest of the widget.

Step 7 Set your margins and spacings to 0 (do this by clicking on the background and at the bottom of Property editor you’ll find the “Layout” section which lets you specify this stuff).

Step 8 Add a style sheet to your widget (right click on the top-most entry in the Object Inspector and select “Change styleSheet…”). Put this style in there for now:

#topFrame {
border: none;
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #a6a6a6, stop: 0.08 #7f7f7f,
stop: 0.39999 #717171, stop: 0.4 #626262,
stop: 0.9 #4c4c4c, stop: 1 #333333);
}

#bottomFrame {
border: none;
background: white;
}

That will give the topFrame a nice modern background that looks like this:

Step 9 Now stylize the buttons. Add this to your stylesheet:

#topFrame QPushButton {
color: #333;
border: 2px solid #555;
border-radius: 11px;
padding: 5px;
background: qradialgradient(cx: 0.3, cy: -0.4,
fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 #fff, stop: 1 #888);
min-width: 80px;
}

#topFrame QPushButton:hover {
background: qradialgradient(cx: 0.3, cy: -0.4,
fx: 0.3, fy: -0.4,
radius: 1.35, stop: 0 #fff, stop: 1 #bbb);
}

#topFrame QPushButton:pressed {
background: qradialgradient(cx: 0.4, cy: -0.1,
fx: 0.4, fy: -0.1,
radius: 1.35, stop: 0 #fff, stop: 1 #ddd);
}

That style sheet makes the buttons have rounded corners, a nifty radial gradient background, and modern hover and click effects, like this:

Now press Ctrl+R and view the finished product:

Aren’t Qt stylesheets awesome?