Why Names Matter

Original Author: Ben Carter

A common motif in many fantasy settings is the idea that naming something gives you power over it. And nowhere is that more true, in my opinion, than when writing code.

Names in code are simultaneously the most and least important thing. After all, a large part of the compiler/assembler’s job is to take all of the names of variables, functions, classes and get rid of them in favour of address, indices or register numbers. It’s like humans giving names to cats – no self-respecting cat is going to ever actually use the name a mere human gave them, even if occasionally they will deign to show interest when called by it.

So, the names don’t matter. Except when they do.

The reason they do, of course, is because only a relatively small proportion of the average program is written for the compiler’s benefit. The rest – the comments, the whitespace, the helper functions… are there for the programmer. They’re there to help you. They are your friends.

So why is it that, as programmers, we tend to treat our friends so badly? After all, if we were more caring, things like this wouldn’t have happened to me (or happened to other people because of me):

  • A large codebase where both “matrix” and “Matrix” (entirely different classes) existed in the global namespace, and did approximately, but not   exactly the same thing, in almost entirely different ways (most notably, one was 16-byte aligned and the other… well… was 16-byte aligned approximately 1/4 of the time, shall we say? You can imagine the hilarity that caused).
  • One project which had world cells and streaming cells and audio cells and collision cells and no-one could ever tell them apart in conversation without detailed cross-examinations of every statement made.
  • A codebase where every single object had its own namespace, and inside that namespace was a static function simply called Init(). Throw a hefty dose of using statements into the mix and the only realistic way to figure out what any given call to Init() actually did was to breakpoint it in the debugger, step in and see where you landed.
  • A large function consisting of about 7 nested loops each using a set of variables that started out in the outermost loop with names like “x” and “y” and then acquired (approximately) one extra letter per level of indentation, giving “x”, “dx”, “dx2”, “dddx” and so on… which I had to convert to MIPS assembler.

The big problem with this is that in the short term, and in some case the medium term, it’s easy to get away with it. When you’re working on the code you can relatively easily remember what goes where, and if something clashes with a module elsewhere then… well, as long as it isn’t a compile error it’s easy to overlook. The problem arises when someone else needs to look at the code, or when in a year’s time you come to work on it again, or even simply when a designer comes around to ask if the “cell” object in the editor is used for streaming or collision or both? And only then does the true scale of the problem become apparent – all those little questions and doubts and fears slowly build up until you realise that you’re wasting huge amounts of time looking things up, guessing, clarifying documentation… the only way you will ever feel clean again is to take the code in question and Kill it with Fire.

So, what can be done to avoid flamethrowers in the office? Well, my belief is that as with many code design-related problems, the only ultimate solution is to keep worrying about it. Not constantly, not to the point where it becomes a factor in stress-related hair loss, but when designing any new system, or even just writing a new function, I think to myself:

    1) Is it unique?

This generally trumps all other concerns. If two things have the same name, they get mixed up. Things getting mixed up is about as bad as it can get, and opens the door to All Sorts of Secondary Unpleasantness to boot. On a couple of projects I’ve worked on we actually had a naming whiteboard, on which people would write any new terms they came up with (and a one-line definition) – this worked wonders in keeping people away from overlapping names, and avoided too many “excuse me but WTF does this thing do?” moments.

2) Does this name make sense?

Ideally, people seeing the name should understand what it refers to… however, this comes second to uniqueness – an invented or arbitrary yet unique name (see the use of “Widget” by UI toolkit for an example of this) is almost always preferable to a correct yet overused one.

Similarly, consider the use of language – for example, function names should generally be verbs, whilst variables and types are nouns (or at a stretch adjectives). Sometimes a tiny subtlety can make all the difference – for example, Vector.Normalise() is a verb and therefore logically performs an action on the object itself, where as Vector.Normalised() is an adjective and should probably return the normalised vector, leaving the object itself unaltered.

Arguably, GetNormalised() might well be better in the general case (as it is more obvious at a glance) – however maths classes are one place where readability of the resulting code also very strongly impacted by the length of names, as people will often stack many operations onto a single line of code, and hence shorter may well be better, even at the cost of some linguistic ambiguity.

3) Does it fit with any existing naming schemes?

Often ignored in coding standards documents, this isn’t just about capitalisation, but about expected usage. Do all objects have Init() and Deinit() methods, for example? Then it would be bad to create one with Create() and Destroy() unless the semantics are somehow different (and, for preference,   documented). The principle of least astonishment should be the order of the day.

Mixing metaphors is also to be avoided – an object you Engage() but then Deactivate() is just confusing all-round. Get() and Set() should do what they say on the tin without side-effects. Likewise I always try to steer clear of negatives when describing boolean variables or results, because once someone has to write things like “if (!IsNotValid())” you can guarantee there’ll be a bug as a result.

4) Is there any additional information I should provide here?

I generally think of the name as the thing that people will see in the IDE, and the   sole bit of information they will (hopefully) read – especially in the modern age of autocomplete, where people often hunt for functions and variables simply by trawling the list of names in a menu. Is there anything really, really important to tell that person? “size_in_bytes” is wordier but so much more useful than simply “size”, or how about the oft-used but still-invaluable SomeFunction_DoNotEVERCallThis() pattern? (otherwise known as “the closest games programmers ever get to using private: properly”)

As a side-note, whilst not wanting to start a religious war about notations, my personal opinion is that with the current state of autocomplete/Intellisense/etc in IDEs, putting actual type information in variable/function names is redundant, and simply asking for pain when it becomes necessary to change the type later.

5) Am I going to regret it later?

There’s always some point where I’ll end up bashing my head off a table because of a naming decision, and since I know that   really hurts, it’s worth avoiding where possible. Assuming that the above are all in order, most of these will be technical issues – like the pitfall of using “Handle” or “Socket” in C++ as the name for just about anything, for example (in particular, Windows has a really, really nasty habit of using #defines on names like these, resulting in the strangest compile errors imaginable). Or in C# naming a property with a name that has funny qualifiers and/or only makes sense to someone reading the code – lots of things (such as the XML Serialiser and PropertyGrid components) will use that as the name to expose to the end-user.

If I was a better person, I’d include “using UK English spellings” here, as they just seem to end up causing trouble (especially “colour”, which I suspect many of my current and past teammates would cheerfully punch me over the use of). However, I’m not a better person, and (largely) unrepentant on this one.

I’m sure there are more good rules-of-thumb that people have come up with (comments thread, anyone?), but that’s my shortlist. 

Aliasing, the silent killer

Original Author: Julien Hamaide

I was recently discussing aliasing problems when it comes to code optimization. And something stroke me : most people aren’t aware of very simple cases where aliasing just kill your performance. Before studying some simple code, let’s explain what aliasing is. And how it annoys your tiny precious compiler when it comes to optimization.

Aliasing refers to a simple fact : the same piece of memory can be accessed by different symbolic names. ( ). The memory containing item_index is written just before the same memory is read. The CPU just stalls a lot of cycle waiting for the store and the read to be finished. Fixing this problem is easy : use a local variable. The same code again, but fixed :

bool findItem( int & item_index, const string & value, const string_table & table )
    int count = table.size();
    for( int local_item_index = 0; local_item_index < count; ++local_item_index )
        if( table[ local_item_index ] == value )
            item_index = local_item_index;
            return true;

    return false;

Aliasing can impact performances even if the piece of code does not seem critical. But for critical code, it can be worst. Let’s image a 4X4 matrix multiplication :

r->xx = a->xx * b->xx + a->xy * b->yx + ….
r->xy = a->xx * b->xy + a->xy * b->yy + ….

If no care is taken, a->xx will be read four times. So will be all other elements. After having wrote r->xx, any elements of any matrix can be changed, as r->xx might have point to the same memory. Once again, __restrict or local variable can be used to fix the problem.

Consider aliasing early in your code. It can improve performance without much work. If you use the __restrict keyword, you must respect the contract you made with the compiler (asserts are your friends to ensure condition are ok ). Using local variables, the code will still be valid, but might be a little less optimal. But whatever technique you decide to use, I recommend you read the generated code, you might be surprised!

Looks like I’m up

Original Author: Jaymin Kessler

So, I couldn’t think of anything cool and advanced (that isn’t covered by my NDA) to talk about on such short notice, so I figured I’d start with something easy.  My apologies to all the veterans on the list since its basic stuff you already know.

We all know that when it comes to programming, there aren’t many language types as fun and exciting as assembly.  Unfortunately, in this crazy world of power lunches and tight deadlines, we don’t really get as many chances to write in assembly as we’d like to.  However, being able to read and understand that alien language in your debugger’s disassembly tab is something that every programmer needs to be able to do.  It’s essential for debugging crashes that occur in release builds only, diagnosing optimization-related compiler bugs, and better understanding what the compiler is thinking so you can make more informed optimization decisions.

Since all non-handheld gaming platforms are based around PowerPC, I’ll be focusing on that.  Maybe I’ll update this to include ARM/NEON or MIPS someday.  VFPU would be awesome but I’m not sure if that’s supposed to be secret (can anyone verify?)

Basic Calling Convention

The first thing you can do is familiarize yourself with the PowerPC calling convention and ABI.  If you know the calling convention and some basic instructions, you can extract almost any information you need. 

Lets start with something simple that comes up often.  You step into a function and want to see the arguments that are passed in to the function.  Mousing over the variable either gives you something like 0xFFFFFFFF or no value at all.  What can you do?  Well, lets see what the generated code looks like for an update function:

void Doooooosh( Bag* bag,  DooooooshLevel level)
mflr             r12  
bl               __savegprlr + 0034h (82eea8c4h)  
stfd             fr31,-38h(r1)  
stwu             r1,-90h(r1)  
mr               r31,r3  
mr               r30,r4

There are a few things you need to know about the PowerPC calling convention.

1) for non-member functions or static member functions, small non-float arguments ( int, bool, pointers, etc… ) are passed in as r3 through r10

2) for C++ member functions, r3 is always the this pointer, and function arguments are passed in as r4 through r10

3) more often than not, float arguments are passed in using the floating point registers ( fr1, for example )

So, knowing this is a C style standalone function, all you have to do is set a breakpoint early in the function and look at r3 and r4.  Later on you’ll see why it has to be early.  To get the real values, all we have to do is open up a watch and cast each register to its expected type:

( Bag * )r3
( DooooooshLevel )r4

When working with a C++ member function we’d use r4 and r5 instead, and we could also get the this pointer using:

( SomeClassName * )r3

As a side note, if you’re wondering how the proper values end up in the right registers to make a function call, its set up like this:

Doooooosh( bag, level );
mr               r4,r30
mr               r3,r31
bl               Doooooosh (8293d0e8h)

mr is the “move register” instruction.  In the above example, mr  r4, r30 will take the contents of r30 and copy it to r4.  We must assume that r31 and r30 contain the bag pointer and level respectively.  Since all C function calls expect their arguments to be in r3 and up, we have to copy all our arguments to those registers.  bl stands for “branch link” and is how we usually call non-leaf functions.

Now there is a catch.  Remember when I said we have to look at these registers early in the function?  At the very beginning of Doooooosh( ) we can assume that the bag pointer and level will be in r3 and r4 respectively.  Thats just how function arguments are passed in.  But what if Doooooosh( ) calls another function?  Wont that called function also need its argument in r3?  The point is that just because your function arguments are originally in r3 and r4 doesn’t mean you can expect them to stay there for long.  Taking a look back at the original example, you’ll see  

mr               r31,r3  
mr               r30,r4

Basically, this is the code saying “I understand that r3 is probably going to get overwritten very soon so I’m going to  back up its value in r31″.  Any time after these two register moves are executed, we can now get the function arguments ( more safely ) like this:

( Bag * )r31
( DooooooshLevel )r30

Remember, on the PS3 and Xenon, r3 through r10 are considered volatile and r14 through r31 are considered general use non-volatile.  Non volatile means that if you stick a value in r30 and then make a function call, when that function call returns r30 will be just as you left it.  That is why at the beginning of Doooooosh( ) we save all the argument registers ( r3 and r4 ) into safe non-volatile registers ( r31 and r30 ) 

Some More Debugging Tips

Don’t be afraid to go back in the call stack if the info you need can’t be found by the above method.  For example, I wanted to examine a string that only existed in a function earlier up in the call stack.  The solution was to go up one call in the call stack and look for the bl function call.  A few lines above that, we were copying the function argument from r30 to r4 ( like we always do for function arguments ).  I moused over r30, casted it to a char *,  and that gave me the string.  Remember that this usually only works for non-volatile registers r14 to r31 ( this is because the registers are “spilled” or copied into the stack frame.  Visual Studio and SN debugger are usually able to look in the stack frame to retrieve the saved register values. )

Getting local variables stored in registers can be a little tricky.  While I don’t think there is any one way that works 100% of the time, there are a couple of tricks you can use that may help you through.  I’m sure with a little imagination, you’ll figure it out

1) If the local variable is passed as the first argument of the function, look for it in the corresponding register right before the function is called ( r3 for a C function or r4 for a C++ member function ) before a function call ( bl ).  If you need to catch it a little earlier, start at the function call and work backwards.  If you know that the value in r31 is moved into r3 right before the function call, then work your way up the code and see where r31 is being set.  The lesson is don’t be afraid to work backwards.

2) look for landmarks.  Often, the generated assembly wont match the code very well.  Sometimes in mixed view, you’ll have what looks like 10 lines of perfectly good C++ code that seem to have no assembly code generated.  Thats when landmarks come in handy.  If you have something like this

float x;
x = sqrt( y );

manually scan through the function and look for some assembly opcode that looks like it could correspond to a floating point square root.  From there, you can see what the code does with the result and better trace through the assembly.  Some other good landmarks include incrementing, trig functions, floating point multiplies, loop conditions, NULL checks, and any other function that would have some stand out opcodes.

3) look for constant initializers.  If you have something like this

int x = 123;

and you see some assembly in the function that looks like

li r30, 123

You may have found a hint that r30 corresponds to x at this point in time.  By the way, in case you didn’t already know, li stands for “load immediate” and it loads an immediate value into a register.  Note that you can only load 16 bit constants in this way.  32 bit constants are done in two instructions by loading the lower 16, then loading the upper 16 and shifting left.

4) if the local variable is used in a conditional, see what is being compared.  Compares look something like this

if( player_controller < 8 )  
cmpwi            cr6,r3,8  
bge              cr6, CPlusPlusSucks::AndSoDoesThisFunc + 0064h (8283457ch)

most compare instructions begin with cmp.  Here you are comparing r3 with 8 and setting some result flags in cr6.  bge means branch greater than or equal.  It checks the cr6 result flags that were set by the compare and then branches if appropriate.  The point is that we know for sure that at this point r3 is player_controller.  If needed we can work our way backwards and look for useful information.

Stack Frame: When When All Else Fails

The above diagram is what the stack frame could look like on Xenon.  If there is some weird bug you have to track down and all else fails, including good old fashioned logical thinking about the problem at a higher level, you can draw out one of these stack diagrams and extract more information than you could get using some of the previous techniques.  

PPC updates its stack all at once at the beginning of the function, unlike LoseTel which seems to do it as you pop and push.  The code will look something like this

stwu   r1, -96(r1)

Obviously r1 is the stack pointer, and stwu is a clever way of telling people to shut up.  Errr… I mean its “store word and update.” It atomically stores r1 at the address and then updates r1 with the new address.  The update direction is negative because the stack grows towards low memory.  Since the caller’s SP is saved  exactly at the top of the new stack frame, this is exactly what we want.

This can get you a few things.  First, it enables you to get a call stack in some cases where the debugger goes nuts.  It allows you to get the value of params that are too big or too numerous to pass in registers.  It also leads to your religious coworkers calling you a witch and trying to burn you for your black magic.

Here is a quick way to decipher instructions you may not know:

if it starts with “L”, it’s probably a load

if it starts with “S”, its probably a store ( instructions starting with “sl” and “sr” are bitshifting operations )

if it starts with “F”, it’s probably a floating point math instruction

if it starts with a “B” it’s a branch.

if it has an “i” at the end of it, it’s probably taking input from an immediate rather than a register.

    Thats the very basics.  Hopefully that should be enough to get you started reading and understanding your code’s disassembly.  Real understanding only comes with practice, so when you have free time (during rebuilds?), look at random bits of code in optimized and unoptimized builds and see how they differ.  Don’t just look at the code and see a bunch of instructions, one of which may or may not be a bl with a function name.  Instead, try to really understand every instruction and what the code is doing.  Its not easy, but someday you’ll be a hero to your unenlightened coworkers who truly believe that optimized builds can not be debugged by humans.

    Jaymin Kessler

It’s a trap!

Original Author: Mike Acton

Or,questions for engine teams to ask to avoid common traps.


Are you trying to please everyone?
This is easy to fall in to. Everyone has an opinion. Everyone has stuff they think is critically important for success, in their opinion. But ultimately you have to realize that you simply can’t give everyone, everything. If you try, you will never be able to give anyone, anything (good.) Accept it. Embrace it. Know what problems you’re trying to solve and stick with those. However, be careful not to ignore issues, either! What can I say? It’s a balance. That’s not sexy and it’s not a hard rule, but there you go, man.
Do you know what the interesting questions are?
If you ask anyone on an engine team what they want to do, you’re very likely to get a specific technical feature in response. That’s okay. I know I’ve certainly been known to get really excited about technical features now and again 😉 But is that really the most interesting question? Or the most important one? Ultimately, we’re all here to serve the players. As engine teams, we often do that indirectly through our production teams. For me, some of the most interesting questions are: What can we give the player? What can we inspire in the player? What do we want the players to feel? What can we learn from the players? How can we help the production team give the players more?  Technical features answer those questions, but we have to be careful not to simply do things for the sake of doing them. There is always a reason. Sometimes it’s just not a good one. Let’s make sure it is.
Is it better? Or just different?
We all want to put our stamp on the world. I know there’s a general fear out there of Not Invented Here Syndrome, but honestly doing stuff for yourself is how you learn and definitely how you advance the state of the art. Someone has to do it, and it might as well be you. If, and only if, you can do it better. Not just different. You have to be answer what better means. Is it faster? Cheaper? Does it give something new to players? Does it allow the production team to do something no one else can do? Does it serve the central vision better? Don’t move forward without knowing the answer.
Are you paying attention to what’s happening in the world?
Like it or not (and well, you should like it because that’s the way it is), our work is ephemeral in the extreme. Nothing you do will survive very long. If I look back at the games I made ten or fifteen years ago, for example, there’s virtually no one playing them today in any capacity (some people are a lot luckier than me – but still it’s rare.) And certainly all the actual work I did is gone and would require quite a feat of digital archeology to dig it up and get it to compile again. The point is: The same is true of what I do today. The world is changing and the work that we do now reflects the world of today. We need to understand what’s happening so that we can do this moment justice. Because in twenty years it just won’t matter anymore. Pay attention to what’s happening in games, and in technology, for sure. But look outside too. I mean damn, ten years ago? Where was the internet? Where was social media? Where were our freaking cellphones? Where was CG in movies? Don’t fool yourself into living inside a little sandbox and believing that what’s happening in the world doesn’t make a difference to what you do. Reflecting the world is what you do.
Do you understand the problem?
Don’t ask for the solution. Ask for the problem. Be especially vigilant about this. Certainly you should appreciate people’s suggestions for what you might want to do or how you might want to accomplish it. But really, you are responsible. You are the one that is supposed to understand the problem at hand from all the angles. Considerations for performance, and usability and direction and memory, etc. etc. But to do that you must understand the problem. If someone makes a suggestion, any suggestion, it’s your responsibility to figure out exactly why they thought that. What problem are they really trying to solve? Their suggestion may honestly be the best answer, but unless you thouroughly understand the problem you simply cannot know that. And if you don’t know that, you simply can’t do a good job. Who wants that? So for any issue, always stop and figure out how you can understand the real problem better first, before you decide on any solutions.
Are you waiting for someone else to solve the problem?
Sometimes it’s tricky to see when you’re falling in this trap. But let’s look at an example. Customization. If you find yourself saying “well, we’ll allow them to customize it, so it’s cool” then you know there’s a problem. That can be simple things like hotkeys or what values are displayed.  The default answer needs to be the right answer. At least most of the time. Right means usable. Right means expected. Right means predictable. Right means performant. If you have different types of users, find out who they are, how they work and provide solutions that work for them.
Are you really trying to solve 100% of the problems?
Ah. A classic. Programmer philosophizing. I’m sure you’ve been into one of these traps. “Oh, but will that work in this situation?”  “What if aliens come down with new technology that we can’t even imagine – how will we handle that?!” Listen closely: You cannot solve all problems. More than that, you don’t want to solve all problems. You want to solve the important ones. You want to solve the common ones. You want to solve the ones that will ultimately matter to the player. Solve the common case really well. Handle the outliers separately. If you find your system becoming more and more complicated because of all the different problems you are trying to solve, you know you’ve fallen in this trap. Systems that solve the common problems well (and first) get simpler as they mature, not more complex.
Are you questioning “the way things are done?”
Momentum is hard to overcome. But you solve hard problems. This is just one more that you have to solve. If “the way things are done” isn’t getting the job done, you owe it to yourself (and the project, and the players) to push to change that. The status quo may have solved yesterday’s problems, but you have to ask: Will it solve tomorrow’s? Don’t wait for someone to ask you what problems you see and what ideas you have for solving them. Be pro-active. Make a difference.
Do you understand the data?
Okay. You didn’t think I’d leave this one off did you? Look at the data. Understand it. Visualize it. The only thing you do is transform data from one form into another. Understand what that actually means. Here’s an exercise: Take any function. It doesn’t matter which one. Output every data change throughout a some reasonable run of the game or level or assets or whatever. Every change. Every parameter that’s passed. Every value that’s stored. Every variable in the function. Dump them all. Then look at the values. Then find a different way to look at the values. I guarantee there will be surprises that will change the way you understand the problem and change the way you think it should be solved. You simply cannot write good solutions without understanding the data, at least on some level. And the better you understand it, the better solutions you’ll be able to provide.
Do you know how your UI influences user behavior?
This can be a GUI for tools or even a programmer API (which is just a text-based UI.) Every UI influences the behavior of the one that uses it. Sometimes in subtle ways. But the only way to know is to pay attention, experiment and evaluate results. Take Twitter, for example. Here’s my theory: I think a lot of sites tried to do what Twitter did. It wasn’t the first micro-blogging solution. And granted, they certainly had some innovations in the space. And they really didn’t fall into the trap of trying to please everyone, which is great. But I think others did that too, and I don’t think that’s why it caught fire. I believe it caught fire because of the “Fail Whale.” (WTF? I hear you saying. How could their infamous early, well and if we’re honest, continuing, server scaling problems have helped them succeed?) It’s because of that one image. It’s was the UI for failure. They took that one thing, which is too often just the default server message, and turned it into something fun and compelling. It made people want to come back. That, I think, is the secret to Twitter’s success. So take a look at your UI and see what it says to your users. But more generally: Find the worst thing about any system you’re working on and turn it into something compelling. It doesn’t have to be complicated (just a simple image in that example), but it can make a world of difference.
Do you know how the engine is actually used?
I mean, really, truly, used. Day to day. Or do you just have a rough idea? Or just a guess? Find out. Two things for me have been enlightening experiences. (1) Usability testing. Do it as often as you can. Put a real user in front of the system, whether it’s a GUI for the tools or a programmer, and just watch them tackle a task. You can’t get all the answers in this kind of environment, but you can get a lot. It’s absolutely worth every minute. And (2) Shadowing sessions. Just sit behind someone and watch them do what they normally do. Try to be hyper-aware of all the little workarounds and frustrations and patterns of behavior that the user isn’t even aware of (or has forgotten about because they’re so used to it.) And ask them “why?” – Why are you doing that? What is it that you really want to do? And ask them how they would describe what they want to do in their own terms.
Do you know what “the right way” actually is?
Sigh. “The right way” is usually just another way to say “the way I was taught” or “the way I’m used to” or “the way some guy on the internet said it should be” – What is the right way? What are your real constraints? What are you really trying to solve? If it’s “right” then it’s provably right. If it’s not provable then it’s probably just opinion at best and nonsense at worst. So if you find yourself saying you want to do this in this way because it’s “the right way” you need to first figure out how you would actually demonstrate that it accomplished that. “Right” is not even interesting. Faster, better, cheaper, more compelling, more value, more usable – those are much more interesting and valuable.
What does “right” mean to you?
Do you know how to decide what is better?
You need a test. You need a way to judge the value of an idea or feature or choice. Those are the central principles of the project. I can’t really stress this enough: If you don’t know what the central principles (or values) of your project are, you cannot make good choices. Decisions will be arbitrary. And inconsistent. If you don’t know what those principles are, if you don’t know how to judge an idea and on what merits, find that out. Right. Now.
What can you cut?
Cut ruthlessly. Much, much better to solve fewer problems really well than more problems poorly. Or as our own Joe Valenzuela (@jvalenzu) says:
That’s enough for today!

There’s a thousand other questions that we need to ask ourselves to avoid the most common traps, but I think that’s good for now.

I’d really like to hear your thoughts too: What’s one question we should ask ourselves to avoid a problem you’ve experienced?


A Smoky Kitchen

Original Author: Brett Douville

David boarded the tour bus, smelling acrid smoke as he entered the main cabin. “Nigel, what’s going on in the kitchen, it smells like you let the Stonehenge effects off in here!”

Nigel indicated a pan aside the stove. “I overcooked the pork patties.”

“How did that happen? They take like four minutes, you throw them on medium and just make sure you turn them.”

“Well, I put them on the front burner and…”

“The front burner? In that pan? You know you have to use the heavy pan on that burner, it runs hot. Don’t you remember Derek’s Bean Surprise?”

Both shuddered involuntarily. Derek had had his cooking responsibilities delegated away after they had lost a drummer to Derek’s Bean Surprise.

“I wasn’t thinking, I was thinking about that hot pink 12-string I picked up in Pittsburgh. I put a cover on the pan and got the guitar out to tune it.”

“Yeah, but man, didn’t you smell the smoke?”

Nigel stared. “You know how I am with a guitar in my hands. I only noticed once I had tuned the first neck. Smoke was everywhere.”

“Great. Just great. Well, that’s all we’ve got for breakfast, and we can’t stop because we’ve got to get to Sioux City for the 7pm show.”

Just then Derek entered the bus. He took a whiff and said, hopefully, “Bean Surprise?”

This little parable¹ illustrates a few problems that I think constantly assault us in game development, either as small developers or parts of big teams. But the big one I want to talk about today is the trap of divided attention/multi-tasking.

When he went over to tune his guitar, Nigel got caught up in a new feedback loop, and his senses were attending to that — putting all of his focus on the guitar caused him to slip easily into a flow state² where the feedback of tuning his guitar occupied all his attention. Only when he had a natural break did his senses have a moment to attend to the environment around him, and that led to the discovery of a ruined breakfast.³

Despite our hopes and dreams to the contrary, human beings are not actually able to multi-task. We use machines which can do so many different things at once that we begin to think we ourselves can do more than thing at once. What we’re able to do is fool ourselves into thinking we are multi-tasking by switching rapidly between tasks that we focus on completely. Indeed, doing little chunks of tasks like this is insidious precisely because accomplishing little bits of things constantly causes our brains to release dopamine, which is a tasty little reward4. So it becomes a vicious cycle of check Twitter-type three lines-kick compile-browse RSS-respond to email interruption-Twitter again-oh wait, compile is done, what was I doing?

Our brains just don’t work well that way — we can really only put our attention on one thing at a time.

Clifford Nass is a Stanford researcher that investigates how the human brain works. In this clip, he suggests dividing your time into 15 minute chunks, and at the end of each 15 minute chunk, simply choosing deliberately at that time what to do for the next 15 minutes.

The key here is to actually commit those 15 minutes — if you decide you’re going to look at your email, you need to do so for 15 minutes. I can tell you from experience that it only takes spending 15 minutes on email a few times before you start only checking your email once or twice a day, maximum, because it gets really tedious to stare at a bunch of old mail. And as someone who receives quite a lot of email at work, I can say that no one has commented on how slow I’ve gotten on replying to emails or anything like that despite the fact that I am reading and replying with less frequency.

When I decided to start experimenting with 15 minutes, there were times I particularly had difficulty in remaining focused on the one thing I was supposed to be doing. For example, time spent compiling can seem like “dead time”, time when you’d really like to be doing something else, browsing the web or reading things close at hand, whatever. But what I found was that often I would get absorbed in those things and lose track of what my next step had been — I quickly dropped out of flow.

Here’s how I work in 15-minute allotments:

  • I put my iPhone on my desk near my keyboard, and pop open the clock to set a 15 minute timer which plays an interrupting sound when it’s done. You might think that this interruption would disturb my flow state when I’m coding, but in practice, I’ve found that if I’m hotly pursuing some problem, I immediately start the timer over and dip right back in without missing a beat. It took a couple of days to get to that point, but now it’s basically an automatic, muscle-memory response when I’m working hard on something.
  • I also keep a running tally of tasks I’ve worked on open in a text file minimized on my desktop, as a reminder that I am consciously deciding to spend a chunk of time on something. This turns out to be useful at the end of the day, when I send out a little list of things I worked on to my colleagues5. I only enter items when I actually switch to another task, and I try to pursue that strictly. I can look back at the end of the week and see the trend of having started out reading email too frequently but having trended down to a more reasonable level over time. The other benefit here is that if I put everything in it, I am less likely to spend time on newsfeeds when I want to be working… those are good things to do while I’m at home zoning out on the latest season of Dexter or while eating lunch at my desk.
  • I keep a pad of paper near for thoughts which occur while I’m doing something else. While it can seem silly to have both a text file and a pad of paper, what I’ve found is that I more easily stay in flow if I jot notes to myself on paper. I think it’s because I’m using slightly different parts of my brain to do the work. The break to do something else after 15 minutes is already a time when I expect to drop out of flow, but the key here is to reduce the times when I might get distracted in the middle of a task.
  • As Nass advises, I’ve limited my sources of distraction. I get no email notifications, though I do leave myself open for IM, since I manage a bunch of programmers and like to be available to them. While I leave a twitter client running, it doesn’t make any noise or display any notifications either, it’s simply there to vent off random thoughts I might have. Let me tell you, I spend far less time on twitter now that checking it involves 15 minutes of it. Instead, I find myself looking quickly through it while I wait for my lunch or coffee.

Switching to this way of working has made me more productive overall, despite apparently doing less at any one time, both in my professional work and when working on my home projects.

And it has led to drastically less smoke in my kitchen.

Brett Douville is the lead systems programmer at Bethesda Game Studios, maker of Fallout 3 and the forthcoming TESV: Skyrim. He blogs occasionally at www.brettdouville.com, and can be found on twitter as @brett_douville.

¹Based on a true story, set in my kitchen, and involving an acoustic, 6-string guitar…
²Flow has been covered by a lot of different folks, so I’m not going to go into it in much detail here. Track down a copy of Mihaly Csikszentmihalyi’s Flow if you’d like to read about the neuroscience. It’s a dense but quite interesting book.
³I used this example in the parable explicitly because this happened to me. I’ve only recently started learning the guitar, and when I went to tune it using an electronic tuner, the feedback loop of tuning strings and seeing the needle move put me into a state of flow almost immediately. Only when I had finished did I actually notice how smoky the room had become. Which reminds me… perhaps it’s time to change the battery in the smoke alarm…
4Farmville anyone? Dopamine production is largely the reason why we think of some games as ‘addictive.’ Something like a World of Warcraft gives frequent feedback in little digestible chunks — attack effects, loot drops, etc. — which mask the highly repetitive nature of the time you’re spending. A topic for a whole ‘nother article, but just wanted to give you a little bit of context for what I’m talking about when I mention dopamine.
5My group consists of eleven engineers, including myself, and we each send a mail called a “five-one” at the end of the day, on the theory that it takes five minutes to write and one minute to read. With an investment of 15 minutes on a given day, then, we’re up to date on what others are working on in the group. This can be really helpful in quickly tracking down new issues, or noting trends, or avoiding work collisions.

Pattern Matching In Scala For Fun And Profit

Original Author: Sean Parsons

What Is Scala?

Before covering pattern matching in Scala, it would seem sensible to cover quick what Scala itself is.  REPL that you can use directly in the page.


Switch Statements As We All Know Them.

A case or switch statement is a concept familiar to programmers around the world, providing an alternative to a straight conditional with multiple clauses.


String intMatch(int number) {
  switch (number) {
    case 1: return “This is number 1.”;
    case 2: return “This is number 2, it comes after 1.”;
    default: return “This number is neither 1 nor 2.”;

Pattern matching in Scala has the same use case, with a more functional bend of returning a value from the invocation, which also results in a lack of the fall through that other languages have in their switch statements.


def intMatch(number: Int): String = {
  return number match {
    case 1 => “This is number 1.”
    case 2 => “This is number 2, it comes after 1.”
    case _ => “This number is neither 1 nor 2.”

Aside from some slight differences like an underscore being used for the default (a common element that is used elsewhere) and the match keyword used instead of a special switch method, these two pieces of code are fundamentally the same.  But in the case of Java certainly that’s pretty much all you can do, pattern matching in Scala does so much more, as we shall see.


Matching Types.

Easily the simplest type of matching that can be done is on types, anyone who has done more that a little Object Oriented Programming will have stumbled into a line of code that checks if an object is of a certain type and then attempts to cast the object to handle that specifically.  Pattern matching offers a very succinct and clear way of doing that particular task:


def anyMatch(something: Any): String = {
  return something match {
    case text: String => text
    case number: Int => “This is the number “ + number + “.”
    case _ => “Unknown thing.”

Taking the case that matches against the String type as an example, that line not only matches the type, but as part of that makes a variable of that type available to use, which in this case is returned directly.  For the Int type case that variable is concatenated into a String to return.  As a result of combining the check and cast, it also has the effect of removing the possibility of checking for one type and casting to another.


Matching Variables.

Type matching does present one dilemma, which is how to use already existing variables, like a parameter for a method for example, this is easily resolved however by the use of one of my favourite characters on a keyboard…the backtick:


def variableMatch(expectedNumber: Int, numberGiven: Int): String = {
  return numberGiven match {
    case `expectedNumber` => “Wahoo!”
    case _ => “Doh!”

All that needs to be done is to surround the variable with backticks to distinguish it from a variable for handling the case clause itself.


Just Add If.

Sometimes it would be helpful to include a little bit of logic in the matching as well, this is also supported as the following example demonstrates:


def positiveIntMatch(number: Int): String = {
  return number match {
    case positive: Int if positive >= 0 => positive + ” is greater than or equal to zero.”
    case negative: Int => negative + ” is less than zero.”

If the number -10 is passed in, it matches on the type of the first case statement but doesn’t match on the conditional so it continues down to the second case statement and matches on that as it only checks that it is an Int.


Sidestep To Case Classes.

Ahead of the next section, we need to take a slight detour to quickly skim over case classes in Scala.  Prepending a class definition with the word “case” causes various methods to be added automatically by the compiler, several of these will be familiar to anyone who has worked with Java in the past: hashCode, equals and toString.  There are a couple of extra secret sauce methods which relate to pattern matching as well, these are the apply and unapply methods, their full use is outside of the scope of this post however.  An example of a case class follows:


case class ChocolateCake(val chocolatey: Int) extends Food
The use of the “val” keyword purely states that the chocolatey field cannot be changed once the class has been created.

Pattern Matching And Case Classes, By Their Powers Combined.

Taking the example of a game server that receives actions from clients and replies with responses to said actions we can start building the conditional logic using pattern matching quite easily.  A first step would be that of a player firing their gun at a specific location, so we would need a case class for the request made of the server and a condition that handles that particular action:


case class ShotFired(val playerName: String, val atX: Int, val y: Int)
val result = new ShotFired(“Sean”, 2, 5) match {
  case ShotFired(by, atX, atY) => by + ” fired at (“ + atX + “,” + atY + “)”

In that example, the fields from the ShotFired class are extracted into several appropriately type variables.  This can be combined with matching by checking for a value as the following example shows:


case class MedikitUsed(val name: String, val useAmount: Int)
val result = new MedikitUsed(“Sean”, 0) match {
  case MedikitUsed(name, 0) => name + ” attempted to use none of their medikit and that makes no sense.”

On top of this, it’s also possible to nest case classes in the pattern:


abstract class SpecialWeapon
case class SpecialWeaponUsed(val player: String, val weapon: SpecialWeapon)
case class NuclearBomb(val megatons: Int) extends SpecialWeapon
val result = new SpecialWeaponUsed(“Sean”, new NuclearBomb(17)) match {
  case SpecialWeaponUsed(name, NuclearBomb(megatons)) => name + ” used a “ + megatons + ” megaton nuclear bomb.”


Final Bits.

I hope you found this journey through the world of pattern matching interesting, I’ve created a PatternMatching.scala file which is the Scala source itself.

It begins.

Original Author: Mike Acton

Starting Saturday, 15 January (that’s now in some places) we will begin posting on #AltDevBlogADay. Learn more about what we’re doing on the #readme (for Readers) and the #readme (for Writers) pages.
We have a great lineup of seasoned developers, indie up-and-comers and even some non-gamedev folk just to throw you off the scent.
  • Read more about us in our #AltDev discussion group Introduction Thread.
  • You can also see the upcoming schedule of posters and learn a little more about the process in the group’s Getting Started Thread.
I hope you enjoy the upcoming work. I know we’re all looking forward to getting to share more with you! (That’s the entire purpose of this group, of course! We all wanted to share more, but needed a little shove from our peers to take the time to get stuff out the door.)
If you have any suggestions for posts you’d like to see, please share! Part of the difficulty with posting more regularly is knowing that there are people out there who are interested in your take on the topic. So if we know you want to hear about it, it’ll encourage us to write about it!
See you tomorrow. (That’s my day!)
PS: Haters, go away. We guarantee nothing. kthxbai.