Code Review, Issue 1

It’s amazing that, while many programmers are able to create amazingly complex systems that solve amazing problems, many of us are never educated in the “proper” ways to write code. This isn’t an issue of style, guys – it’s an issue of maintainability, readability, and efficiency. We’ve all had that moment where we open somebody else’s code and we’re hit in the face by a monolith, a goto statement, or something equally offensive. I like to think this isn’t intentional negligence, however, and so I am to begin cataloguing my pro tips for developers as I encounter blunders in my own code and the code of others.

Tip #1: Comments like “Variable Declarations” and “Initialize Variables” are not helpful.

We’re programmers, so we know what’s going on. Comments like “Set up GUI elements” and “Declare variables to be used in GUI labels” are much more helpful, because they describe the use of the variables being initialized.

Tip #2: If you have to make a comment to delineate a section of code…

It’s a good indicator that that section of code belongs in its own function, file, class, or module.

Tip #3: If you find yourself repeating the same structure of code over and over again…

Think about how you could turn that structure into a function. Removing duplicated code is a great way to reduce complexity and save headaches when that duplicated code has to be edited. You don’t want to have to edit it seven times, one for each time it was duplicated.

Tip #4 The overall goal of any function is to be super readable.

If at all possible, we want it to look like this:

  MyFunction()
{
	DoThing1();
	DoThing2();
	DoThing3(using, these, things);
}

It’s not always possible to reach this ideal, but there’s a lot you can do to get it close. For starters, you can break all code that is part of one cohesive idea out into its own function. Don’t worry if this function is only called once – the overhead for pushing and popping the stack is worth it for the added readability.

Tip #5: It is OK to assign a boolean expression to a boolean variable.

It is far better to do this:

b = x && y;

than to do this:

if(x && y)
{
    b = true;
}

which unnecessarily clutters the code, AND it makes it a lot less efficient. It’s actually a good exercise to turn off compiler optimization and look at the difference in the assembly code between those two implementations.

Tip #6: Use positive logic where possible.

It is usually more clear to say “if this” rather than “if not this.”

Tip #7: Name booleans using positive logic

e.g. rather than naming a boolean “doorState” name it “doorOpen”. This is much better, because you never have to remember what true or false means in the context of the boolean.

Post navigation