Formatting

Neatness is a big word – not as big as consistency. Therefore to have your code neat and consistent involves a lot of struggle, not necessary from the way it is built or from the classes dependencies point of view (though these, among many others are extremely important – we’ll talk more about them in the next few weeks) but from any person’s point of view, careless if that human is a programmer or not, a good looking, indented and very well formatted code is like looking under the hood of a car and see everything is at its place and clean – or at least as clean as it can be.

If you’re a car lover you would agree that you want your under-the-hood place to be clean and have everything at its place. Yet if you’re not and are, for example, a chef think of the way you like your food to be organized on a plate – would you like it disorganized, everything mixed-up in a bunch of messy, unrecognisable dish? Of course not, you want it clean, everything in detail put at just the right place for it to look stunning.

Of course, you could not be a cook but you got the point. Order means simplicity, attention to detail but more importantly neatness and consistency. I hope now you understood why code should be like this to be clean. If I still didn’t convince you, it’s time for some examples.

I once saw a function in a colleague’s project and… didn’t even know it was a function until I stared at it for a few seconds.

private
    static
        string GetNameOfClass()
{ if (MyRoleHereIs.Equals("Admin"))
{ string className = MethodBase.GetCurrentMethod().DeclaringType.Name; return className;
} return "You are not allowed to do this! Not an admin much?"; }

Even though, after I read the returned messages I was a little amuzed, I was like… “dude…”. When I asked him why he did write code like this he told me that he wants to save space because he thought that shorter functions were better than long ones. And also that he reads it better.

Face palm moment, I know. (If you don’t think so, read this and understand why). I then told him: “My friend, you are wrong in so many ways. How can you say you are writing clean code? It took me a few minutes to realize this is a function after how it looks.” He indeed stated that his code is consistent, that it has good variables names and only by looking at the header file you could understand what the function does. “Yes, if you could only see the function’s header as a header!”, I replied.

My friend (and many other programmers) think that if you use good names, have functions that do one thing and do it well or comment only what needs to be commented then they write clean code. I believe otherwise, because if they write awful looking code, that’s not even close to clean.

Think of the cook’s case: indeed, he cooks every part of a dish very well (delicious taste – compare this to good variable names), cooks everything separately, so everything has it’s own taste and flavor (like methods do one thing and do it well) but at the end throws everything on a plate, mixing them and making it look awful – do you think that this would be a clean dish? He did cook everything separately and took care that every part of a dish is perfect. But still, if at the end it looks awful, it’s not clean.

The same applies to coding formatting. In this post I will enumerate some formatting techniques I apply when I write code.

  • Vertical formatting

A file should be as long as it should be. But not too long.

There is a technique called Log-normal distribution that sustains you could write files up to logn(numberOfTotalLines) long. Meaning that if you approximate your project having up to 20000 lines of code you could easily break it into maximum 200 lines of code files.

Of course, in a C# (or any OOP oriented programming language) there are classes and namespaces involved, but we will cover that up later on when we talk about classes.

 

  • Vertical Openness

Everyone has that one friend that thinks a newline insertion only makes the code longer.

That’s completely wrong, obviously – if someone would count your code (though no one actually does that, trust me) he or she wouldn’t count blank lines, let’s be serious.

This is because they don’t care (and don’t even realize) the blank lines you left between different concepts, all the more to count them. Let’s have a look at an example:
protected void getInformation()
{
       int musicYear;
       string message = "";
       List<string> givenMusicalEraData = new List<string>();

       string musicYearFromInput = GetInput();

       musicYear = GetMusicYear(musicYearFromInput);

       string musicalEra = GetMusicalEra(musicYear);

       message = CreateMessage(musicYear, musicalEra);
       PrintMessage(message);

       givenMusicalEraData = PrintAndReturnEraData(musicalEra);
}

Cute, isn’t it? Now think of this code without any spacing between different modules of a the function. Right, awful, that was my opinion, too. Remember how my friend didn’t know this and how his code looked.

Don’t push it, though.

I mentioned earlier that if someone would count your code he or she wouldn’t count blank lines, let’s be serious and that they don’t care/notice the blank lines you left between different concepts; yet, they do observe how many you did left.

That is because no one likes to scroll down through a function to infinite, let’s be serious. Ok, you made your function do one thing only but if you \n\n\n\n, anyone who reads it would think “but why?”. And if you wanted to make your code clean, if someone asks you that question there are two reasons of that:

  1. He or she has no idea what Console.WriteLine() method does (or any other method if that matters)
  2. Your code isn’t clean.

Rule: keep it at the minimum necessary, everything – the number of classes, the variables, but more importantly the newlines and he spaces.

 

  • Vertical Density

If earlier I mentioned about openness and how it is broken by the lack of newlines, the Vertical density refers to the example of having too many intruders – like comments (bad, bad comments they are).

Take a look at the last example. Imagine how would it look with comments before every variable. Yes, that’s my point, too.

 

  • Variables declaration: I already covered this here. I would add that you should keep the declarations at the top of the method/class/functions as of the fact that many coding conventions (including the Linux Kernel Coding Style) use this – and it is more fluent as of the fact that many programmers first analyze the variables used.
  • Vertical ordering: You want your code to have its own flow, so that everyone who reads it be like “oh, right.”, “cool”, “oh, I saw this coming”, “and that would be… here, of course, cool”. Because you want to make them see everything coming you have to give them everything when they want it – for example, a function that is called should be below a function that does the calling.
“We expect the most important concepts to come first, and we expect them to be expressed with the least amount of polluting detail.” – Robert C. Martin

 

  • Horizontal formatting

I mentioned in my previous posts about how long a line should be – 80 characters at most! And yes, that counts the white spaces, too. If you would ask me if you could just spare some white spaces so that your line is framed in the 80-characters rule, I would say something is wrong in your line of code – this because I wouldn’t understand it at once or I would lose it trying to read it.

This is because it’s very hard to… Actually, lets better look at an dummy example.

musicYear+=(musicYear/2)-2*7/musicYear%1000;

Well, that hurts a little. I am a programmer, not a mathematician, you know? I shouldn’t have to figure out the order of the operands – that’s not my job. Instead:

musicYear += (musicYear / 2) - (2 * 7 / (musicYear % 1000));

Now that’s better, isn’t it? Of course, I have no idea what 2 * 7 do but it’s a dummy example, as I said, in which we are focusing of the formatting.

A general rule is that you should always use white spaces between words and more important before and after a opperand.

 

  • Indentation

Finally, right? I bet you believed I would only talk about this.

You not once heard the word hierarchy in OOP programming – this because every source file represents one.

To make this hierarchy of scopes visible, we indent the lines of source code in pro-portion to their position in the hierarchy. Statements at the level of the file, such as most class declarations, are not indented at all. Methods within a class are indented one level to the right of the class. Implementations of those methods are implemented one level to the right of the method declaration. Block implementations are implemented one level to the right of their containing block, and so on.

Now lets indent my friend’s code and see the final result:

private static string GetNameOfClass()
{
     if (MyRoleHereIs.Equals("Admin"))
     {
          string className =
               MethodBase.GetCurrentMethod().DeclaringType.Name;

          return className;
     }

     return "You are not allowed to do this! Not an admin much?";
}

 

  • Conclusion: This is the best.

The newspaper metaphor sustains that you should read a clean code from top to bottom just like a very well written newspaper, having a headline (the header) with the “short description” that allows you to decide whether it is something you want to read or it simply doesn’t raise interest to you or you do not need to know what that part is about (for example, your co-worker told you he tested that part and it’s fully functional. Leaving it collapsed saves you a lot of time. You would want your code to be like a well-written newspaper article: the name should be simple and explanatory – and also, sufficient to tell whether we are in the right module or not. As we go downward we should see more details about what the function/module does until we find the lowest level functions and details in the source file.

“A newspaper is composed of many articles; most are very small. Some are a bit larger. Very few contain as much text as a page can hold. This makes the newspaper usable. If the newspaper were just one long story containing a disorganized agglomeration of facts, dates, and names, then we simply would not read it.” – Robert C. Martin

Sounds familiar? Exactly, that is how clean code should be, too.

Leave a Reply

Your email address will not be published. Required fields are marked *