The Art of Writing Good Conditionals

Posted September 2, 2009 by Ben Mahler
Categories: Tips and Tricks

Tags: , , , ,

Based on my experience, many of the finer points of writing optimal conditional statements are not covered in most introductory computer science courses. For that reason, I thought I’d go ahead and write a post on the topic. There are other points that I will not be covering, but I’ll offer some advice on how to write great conditionals and I’ll show a few tricks on how to optimize your conditional statements. Keep in mind that conditional statement optimization is a form of micro-optimization and that performance gains from macro-optimization (ie. Good design, optimal data structures and algorithms) will be much greater. The code examples will be written in Java, for concreteness.

Common Mishaps

These are two simple examples of bad practices that should be avoided.

If you have a Boolean b, use it directly! Do not compare it with true or false:

If (b == true) {
//do something

Doing so adds a bit of overhead in your conditional (assuming the compiler doesn’t optimize it out). Instead, just write:

If (b) {
//do something

Use the following table to see the best use of the Boolean b in a conditional.

Expression Better Alternative
b == true / b != false b
b == false / b != true !b

Of course, in order to maintain code clarity, appropriate naming conventions are crucial. Using appropriate names means that one should be able to deduce the meaning of the expression simply by reading it:

if ( !empty && valueFound ) //Expression is easily understandable by reading it

Another bad practice is using the value of a Boolean indirectly:

if (someBooleanExpression) {
return true; //if true return true...
} else {
return false; //if false return false...

Again, just use it directly:

return someBooleanExpression; //use the value directly

Indirect usage of conditionals makes the code unnecessarily long, slightly slower and shows a lack of a true understanding of how Booleans work (or you weren’t paying attention :) , it happens)

Lastly, if you find that you’ve got a large if, else-if structure checking the value of an integral type, use a switch statement instead. Most importantly, switches increase code readability. Also, they are typically better optimized by the compiler and will be anywhere from much faster to roughly the same speed as a large if, else-if structure. The details of the optimization are the topic of a different discussion.

Short-Circuit Evaluation

Hopefully, if you’re reading this post, you are aware of this concept and can skip over this section. Short circuit evaluation occurs when a Boolean statement’s evaluation stops once the overall value of the Boolean is known.  Short circuit evaluation is typically enabled by short-circuit Boolean operators which differ from standard operators. This is the case with C++ and Java:

Standard operators: &, |

Short-circuit operators: &&, ||

This means that in the following two cases, otherExprs will not be evaluated:

if ( falseExpr && (otherExprs) ) //Always false regardless of value of otherExprs

if ( trueExpr || (otherExprs) ) // Always true regardless of value of otherExprs

If you know how to use these operators well, you can use them to write some pretty powerful conditional statements by deliberately short-circuiting in order to:

1. Avoid handling a null object erroneously:

if ( obj != null && obj.doSomething() )  //this ensures that contains is never called on a null object

2. Avoid expensive operations:

if ( value == lastValue || largeMatrix.contains(value) ) // if we can know that the large matrix contains the value without having to call the contains method, we do not need to make the call and can avoid the expensive operation, yes.. not the best example but you get the point

Regular Boolean operators should be avoided. However, in rare cases, they may prove useful: if a Boolean method has a side-effect that is desired regardless of the outcome of the expression then a regular operation may be useful.

if ( func1WithSideEffects() & func2WithSideEffects() ) //this ensures that both functions are always evaluated

Strategies for Conditionals

Finally, I thought I would outline two general strategies that can be used when writing conditional statements in a program. These aren’t hard and fast rules, so they should not be strictly adhered to in all situations. I’ll call the first strategy clarity.

The clarity strategy is an important strategy to follow, it deals with if blocks that handle numerous cases. It consists of placing the valid/good/expected case first, followed by the invalid/bad/exceptional cases.

if ( (x1 > 0 && x1 < 100) && (x2 > 100 && x2 < 200) ) {
//valid input first
} else {
//invalid input, can check what exactly makes it invalid here, or can use else-ifs instead of else

This makes code more readable and maintainable, and if the common case is the valid one, then performance is better as we do not need to check for all possible invalid scenarios, which in most cases is much larger than the set of valid ones.

This leads into the other strategy I’ll mention: speed. The speed strategy consists of handling the common case first (or fastest case first if its performance is such that it warrants being checked first despite occurring less often). Typically this strategy requires profiling to observe which ordering yields the best performance. Another important aspect is to effectively use the else block. The fact that the code has progressed to the else block means that all of the other expressions evaluated to false. By taking advantage of this fact, you can shift slowly evaluating expressions into the else clause, thus avoiding needing to evaluate them. In general, if you can use an else instead of an else-if based on the pre-conditions resulting from all the expressions evaluating to false, then do so. Use an assert statement instead if you want to ensure the conditions are indeed met.

Altogether, remember that macro-optimization is much more crucial, but by writing better conditionals you can really squeeze out those small performance gains, especially when tight looping is involved. Most importantly, better conditionals greatly improve code readability and maintainability.



Opening a Dell Inspiron 6400/E1505

Posted August 31, 2009 by Steven Chung
Categories: Student Life

Tags: , , ,

It’s been about a month since my last post, and a lot of things happened. I’ve been working on my work term report, finishing things up for the work term, playing Street Fighter 4… yeah. Now that my work term is over, one of the things I’ve been stalling on is changing my laptop fan.

I bought my Dell Inspiron 6400/E1505 just before going into university (Summer 2006). But once I got to university, the laptop was everywhere. I think this laptop is probably the most popular laptop of my generation, so I thought that this post might help someone with their computer problems.

Dell Inspiron 6400/E1505
Dell Inspiron 6400/E1505

I’ve been generally happy with my laptop though, had a few minor problems: a blue screen every now and then, and my CD drive doesn’t work at the moment. But from my experience, it seems like the fan is the first thing that breaks down after about 2 years of collecting dust. My fan died last summer in the middle of a LAN party. After, the fan was loud all the time; it was a little embarrassing in the library. But I never realized that the fan was the problem until I opened my computer, cleaned the dust, and checked the fan last January.

So I’ve opened my computer before. And that’s the main problem; the laptop’s annoying to open. I pried open some plastic, fooled around with some wires, and removed the palm rest, keyboard and monitor. Seems like a lot more work than needed. I don’t have much experience with technician work, but thanks to Dell’s service manual, it wasn’t that bad. You just need to be careful and follow instructions. It was good bonding time with my dad.

Innards of a Dell Inspiron 6400/E1505. Didn’t know the heat was transferred through those metal bars.
Innards of a Dell Inspiron 6400/E1505. Didn’t know the heat was transferred through those metal bars.

Replacing the fan was simple. Testing the fan turned out to be simple too. While opening the computer, I was sort of scared because I was too lazy to backup my stuff, but it turns out that the computer is still fully functional without the parts I took out. I used the palm rest to turn the computer on, and external monitor, keyboard and mouse for input/output. I used WarCraft III to trigger the fan. After, I cleaned the computer with some compressed air and put the computer back together.

Running my computer without the internal input/output components
Running my computer without the internal input/output components

Other than that, I ordered my fan off eBay. It’s the first thing I’ve ordered on eBay and I got it in about three weeks. Best of all, it was only four dollars American with shipping. Pretty good deal.

Next up, my CD drive. (You take out one screw and pull it out.)

The field of screws
The field of screws

Behind the text, your font

Posted August 3, 2009 by Steven Chung
Categories: Links

Tags: , , , , ,

I’ve been looking for a good article on typography for a while. (But I haven’t really been trying.) Cheers to bumping in this introductory article on web fonts.

The first language debate

Posted July 25, 2009 by Steven Chung
Categories: Student Life

Tags: , , , ,

As a student at the University of Waterloo during its transition from Java to Scheme as a first language to teach, the debate about “what programming language should one learn first?” has been all too familiar to me. This article got me thinking about it again.

In summary, the article states that Scheme is a simple language to learn because it expresses programs using the functional programming paradigm. The syntax has less operators and represents the programs as mathematical functions (lambda calculus) instead forcing you to learn different ways of doing the same thing. While other languages, such as C and Java, have the benefit of practicality, letting you explore and aspire to make the computer do stuff.

With Waterloo’s transition, the most common complaint I get about Scheme is that no-one uses it. And it’s true; I haven’t seen Scheme’s use outside of school. And seeing that some Waterloo students do co-op after their first four months of school, Scheme can seem pretty meaningless when job descriptions ask for Visual Basic, C++, etc. But with my first language being a Java-like language, C#, when I was in Computer Engineering, I do have some bias over my opinion (thanks to Mr. Gates’ donation to the Engineering faculty).

To be honest, I don’t truly know what functional programming and lambda calculus is, but I think the topic is important enough to cram in with my Geography courses (check out CS 442). I barely remember functional programming because I used it about two times while learning Python, such as iterating through a data structure functionally (which is pretty elegant). From my view, Scheme’s syntax is minimalistic and unlike any language I’ve worked with. Scheme deals with more recursion, while avoiding object oriented programming – something I struggled with.

It’s pretty random that I’m in CS right now; I actually avoided programming jobs for my first co-op because I didn’t understand what an object really was. (It’s a box? A recipe? Huh?). Later, I learned programming by playing around with the debugger in Visual Studio – going through the program step by step. The debugger got me over the learning bump others struggled with. I was lucky to figure out the debugger on my own, and I wish educators considered using the debugger when teaching any language.

But if C# wasn’t as practical as it was, I might not be in CS because what really got me into programming was volunteering to write a program to format and merge Excel spreadsheets during my first co-op. Practicality is what got me going into CS, and still motivates me.

Even though I don’t fully understand the pros of Scheme, I will agree with the author of the article: go for the middle ground, Python. It’s used by the University of Toronto. Python’s syntax is minimalistic, it’s easy to setup, and it can be object oriented or functional. Something as mathematical as Scheme would probably detract students like me. People learn better if they apply their knowledge outside of class. After all, school isn’t everything.

(By the way, for the Waterloo-ers, the Math Faculty curriculum for CS isn’t that bad, you get to learn C or Python later on. I’d think that the transition from Scheme to C must be brutal though.)

PS: If you know of any other good developer related RSS feeds other than InfoWorld, a link would be nice =)

The Mac Operating System (OS X)

Posted July 20, 2009 by Steven Chung
Categories: Reviews

Tags: , , , , ,

Yay, I get first post, which is a good and a bad thing depending on how you look at it. The good thing is well, first post! The bad thing is I get to be the test dummy for how the blog will work, how to post up pictures, (finding out that you need a credit card to sign up to flickr,) and so forth. I’m still learning how to write blog posts without forgetting small, but important details (which is a terrible habit of time). It’s hard to get into the habit of writing. Next time, I probably won’t write something this large and intricate, but the topic fits well with this blog and it forces me to learn capabilities of WordPress. Now that we’re over that setup period, time got get the ball rolling with the first post!

It’s over two months in my co-op term this spring working at Sunnybrook Health Sciences Center. I’m having a great time in the new work environment at a hospital, but I’ll save the piece on my co-op experience for later.

As part of the Imaging Research Centre for Cardiac Intervention group, I was lucky to get the best computer equipment I’ve ever worked with. Everything in my lab is new and has a tint of the iLife on it. I work with a Mac Pro with 4 rock-hard cores and two monitors. And with the hardware, I haven’t had a speed bump yet. With the software, it’s a different story.

The awesomeness of a window seat (Imaging Research Centre for Cardiac Intervention, Sunnybrook Health Sciences Center)
Mac OS X Leopard Desktop

Being mainly a Windows XP user, I decided to write a personal review of the Mac to help others thinking about the transition. Plus, I told a friend I would write this review (sort of as a joke though).

At first glance

As expected, the Mac looks great. Everything is shiny, animated (bouncy icons), and has a consistent look (they have some seriously heavy documentation about looks, they even go down to writing alert messages). The typography is easier to read than Windows (because of font smoothing) and the icons are big. Looks like any other Mac product. (As expected.)

Mac OS X Leopard Desktop
Mac OS X Leopard Desktop

Quick Configuration

But after looking at the layout, I began noticing the small things that I missed from Windows. First of all, you have turn on the right click button on your mouse (why not use the button when it’s right there?). I also changed my middle button to match Windows’. The default middle click shows the Dashboard of widgets, which I have yet to use.

Down to work

After settling in, the first thing I noticed is that if I click on an application icon many times, only one window pops up. And when I close all the windows of an application, the application seems to continue running. It confused me a bit, until a friend told me that the Mac uses multiple document interface (MDI), which made things more clear.

MDI works like a lot like tabs in internet browsers (tabbed document interface). For example, in a Firefox window, you can open multiple tabs inside of it. But once you close the entire window, the tabs disappear. Mac’s MDI is similar, but there are multiple windows inside an application, where the application represented by the bar at the top. Like tabs, once the application is closed, the windows are also closed.

Mac’s bar representing the Finder application (similar to Explorer in Windows)
Mac's bar representing the Finder application (similar to Explorer in Windows)

Out of nowhere, Microsoft Excel also uses MDI, which I find annoying at times (I used to wonder why different Excel windows like to follow each other). It’s a topic that is nice to know if you’re interested in program designs (like me).

There are pros and cons for everything (sadly). But in many cases, I find it a bit unintuitive to not close the application when there are no windows for it. Also, opening the application twice sort of implies having another instance (or window) of the application. Maybe I see it this way because I’m a Windows user, but these little things force you to either drag your mouse a lot or learn your hotkeys. Because of MDI, Command + Q (quit application) and Command + N (new window) soon became my best friends (and then you start confusing with Windows’ hotkeys).

What I miss most about Windows’ windows

What I miss most about Windows is its ability to tile windows quickly, which avoids manually sizing your windows to see two windows at once.

Tiling windows on Windows. I find these instructions to be more useful.

Sadly, not many people know about this functionality, but it’s useful when comparing things or reading something while writing. Having two monitors easily avoids this problem because you can drag the window to the other monitor as an alternative to tiling windows.

Another thing I miss is the maximize button, instead you get this green plus button called the zoom button, which doesn’t zoom or maximize the window. It switches the window between the standard state (the window size defined by the application, which varies from application) and the user state (the manually sized window size). To be honest, I really prefer a simple maximize button – it’s that Bill Gates inside of me. You can read more about this here (I think the site has some bias though).

The good things

In the operating system

The best thing about the Mac for me is that when you plug in earphones into the computer, the volume changes to “earphone volume state”. It’s good because earphones usually feel a lot louder then your laptop speakers. (I love music okay. Ever had a moment where you put on your earphones, plug them in your laptop, only to have them blasting in your ear at max volume?)

Command + space is another one of my friends on the Mac; it opens a quick search bar called Spotlight that’s really easy to use.

Mac’s Spaces
Mac's Spaces

Two things useful things that also exist in Ubuntu are Apple’s Exposé and Spaces. Exposé shows small representations of windows to allow quick navigation amongst them. Nowadays, sometimes I feel that Windows needs Exposé too. Borrowed from the open source community, Spaces allows windows to be stored in different… spaces (look up), but required me to learn more hotkeys (yay! more friends).

The software

When it comes down to software, I think there’s enough good quality software out there for the normal user – including those popular quirky applications that people play around with that I couldn’t use at work. The provided software seems less complicated and bloated than Windows’ alternatives. Just note that there isn’t an “uninstall thingy” to remove software. Most of the time, you have to manually delete the application in the Applications folder (which could scare people who are massively paranoid about deleting files).

But if you’re missing Windows, you can always buy Parallels, which can run Windows on your Mac almost seemlessly (it’s a virtual machine for you techies out there). Great software, and it’s easy to use. Boot Camp is an alternative that’s a bit more complicated (partitioning your computer), but it comes with the operating system.

Oh yeah, you can’t really play “hardcore” games either without Windows. Almost forgot.

The little bad things

Two small quibbles (because my quick googling skills weren’t sufficient):

  1. I still can’t find the up one level button when I’m browsing through files and its stuck in a folder.
  2. I haven’t found a way to manually type in which directory you want to go into.

(edit: 1. Normally, it’s Command + Up, but I overrided it with a Spaces hotkey, so I have to make a custom hotkey (too lazy to fix at the moment though), 2. Command + Shift + G, thanks again Roman)

Steve the developer

Warning: If you don’t know what a conditional expression is, skip to the conclusion.

So did I write about Parallels, the great virtual machine (VM) software? I think I did. Mac has some other good VMs too, which can provide good/cheap/clean testing environments for those developing with platform-depandant languages (cough, Abstractive Software, cough). I did some quick research and I don’t think the VMs on Windows are as good (correct me if I’m wrong), but Wikipedia says that only PearPC can emulate a Mac.

Having a Unix base is nice, as the file structure is similar to Unix. Bash is also included, which is way better than the Windows shell.

The main problem about developing on the Mac is that the Mac is usually the last OS to be supported. Manually building libraries is a huge hassle, which is why packagers such as Fink and MacPorts exist. For a computer neat freak like me, I don’t like having things done for me, as I get paranoid about other things getting installed (and I’ve had MacPorts install random stuff by accident).


Coming from a Windows XP background and using the Mac for over two months now, I believe that working on Windows is simply easier and logical to work with, but the differences are not huge (especially if you have two monitors). Just be prepared to have a larger learning curve (learning hotkeys and making sense of Mac’s windows) and expect your workflow to slow down if you’re going through a transition. Once you’re over the bump, you’re set. And most people will probably work faster after learning those hotkeys and using their software.

If you think the iLife style is worth going through the learning curve and price, go for the Mac. Get one now before school starts.

For the developers out there, the availability of good virtual machine software for testing may be a selling point for the Mac. Otherwise, the alternatives are likely better.