Code Police – The Importance of Code Style Consistency

It’s not my intention to talk about which coding style is the best. Everyone has a specific style and their reasons for it.

I do recommend thinking about this topic, and to that aim there is a very interesting tool out there on the market called ObjectiveClean

I’ve enjoyed working with my colleagues on my current project and have a very friendly relationship with my boss. I do however have to chide him from time to time for not sticking to a clean coding style. I joke about being the Code Police. He jokes about keeping me on my toes.

There are certain style conventions that should however be adhered to for the following reasons:
– Conventions create consistency.
– Consistency allows you to make assumptions about how the code is written
– Assumptions allow you to refactor more easily.

What? If for example I have in my codebase the requirement that we write:

someString = @"SomeString";  // note the spaces between the equal sign

I can then easily find strings by searching for = @". You might not think that this is a big deal. You probably haven’t refactored a lot of code.

I spent over one hour refactoring some constants purely because they didn’t follow a standard. Imagine error codes defined like this:

static int const errNotConnected = -1;
static int const errWifiOff = -2;
static int const errFileIOError = 1;

2 absolutely horrible things result by trying to define error codes like this:

i) I provide no context for these error codes. I have no idea what class they relate to, what functionality.
ii) do a find and replace for these. if you put in a Project wide search term “err”… you are going to basically get thousands of results.

Now, the know-it-alls amongst you are going to say something snarky like “well, why don’t you just write a regular expression that will find exactly what you’re looking for?” The answer is practicality. Regex is a bit of Voodoo for most programmers and it’s not exactly pretty syntax despite how powerful it is.

You could just provide a context, and even better, pack these in an enum

typedef NS_ENUM(NSInteger, HSConnectionManagerErrorCode)
  HSConnectionManagerErrorCodeNotConnected = -1,
  HSConnectionManagerErrorCodeWifiOff = -2,
  HSConnectionManagerErrorCodeFileIOError = 1

From the name alone, I gain a few things:

i) I know which class it relates to
ii) I know what the error was all about
iii) Any time I’m coding I can just type in HSConnectionManager and Autocomplete will give me a list of the enums I’m looking for, so I don’t even need to go digging through header files.

Good habits allow us all to do our jobs more quickly, and make it easier to work with each other’s code. I highly recommend caring about the quality of your work. You can be proud of yourself and others will enjoy coding with you.