Skip to main content

Coding conventions part 2 : Aligning Things


“Programs must be written for people to read, and only incidentally for machines to execute.”
—Harold Abelson
Hello there, welcome to another post in the “Coding conventions” series. This post is solely based on question, “How to align code?”. If you are coming to this post directly then it is highly recommended that you read this post about naming different sections of code first. It contains both introductory talk about coding conventions and their importance and tips on naming things viz. methods, classes and variables.
We humans are naturally in love with symmetry(tell me if I am wrong). Symmetry of faces, colors, things and their organization. A well-designed and aligned piece of writing makes reading both easy and fun. And when learning is fun remembering is easy. Undoubtedly things are no different in programming. A well aligned code is expressive and eye soothing. Correctly indented code blocks divided into equally sized chunks of statements really enhances quality and maintainability of code. Always remember this,“A programmer is by heart poet of logic and program is his/her poetry”. So, program must be treated the same way.
There are numerous ways to align code and At very heart of each of them are rules. Rules which can be summarized into following statements:
  • Position of opening and closing parenthesis Or brackets(U.K. English) after blocking statements(I'll explain what are they? Latter).
  • Number of Tabs or spaces to be inserted after statements belonging to sub Or child blocks.
  • Ideal count of number of characters to be written in each line of code.
As I have said earlier there are a lot many styles to align code(I know I am being ‘redundant’ here). I will only explain the best one(Lazy programmer. Hell yeah!).
Not too fast kid!. Before moving onto alignment section and flooding your “biological storage drives” with rules and do's and don't. Let me first introduce you to some words crucial to matter followed; which belong to programmer's glossary.
Indentation:
An indent is simply that extra space added just before starting code statement to reflect the parent-child or belonging relationship between unintended and intended block of code. It can be done either by using tab character or space. (1 tab is roughly equal to 4 space characters).

Blocks:
A code block is collection of code statements grouped together to perform or complete single ultimate goal. For example body of function.

#include <iostream>
#include <set> //set is a datastructre which automaticaly sorts the input
//code starts executing from here
int main(int argc, char const *argv[]){
//block of code
{
std::cout<<"I am block of code in main block";
if (1 == 1)
std::cout<<"I am part of if because I am intended";
std::cout<<"I am not part of if because I am not intended";
}
std::set<int>inputSet;
for(int i=10; i >= 0; i--){
inputSet.insert(i);
}
std::cout<<"Output:\n";
//c++ style foreach loop
for(auto i : inputSet){
std::cout<<i<<"\n";
}
return 0;
}
view raw exampleOne.cpp hosted with ❤ by GitHub

Now, as you know what blocks and intends are, let's move on to some tips to make your code beautiful.
  • Be consistent both in code and life. If you have used space for intending code in one file then use spaces in each and every file in that code. This rule also applies to the style of brackets that you are using.

  • Don't intermix spaces and tabs at least not in the same file. Mixing spaces and tabs can cause serious issues that's why languages such as Python has completely prohibited doing so. The root reason behind this is that every OS represent tabs using different amount of space characters, some use 4 spaces to represent one tab other might use 8. And when you transfer code from one OS to another conversion has to be done by Integrated Development Environment and this might render code useless.

  • Keep it detailed Keep it simple always. Think of code as piece of poem. Poems has definite structure each stanza(paragraphs in poems) consist of only those lines which have meaning in current context which are there to complete the goal in current context. Let me give you few examples.
    Incorrect way:
    #include <iostream>
    using namespace std;
    class MyFile{
    private:
    //some privates
    public:
    MyFile openFileForReading(string path);
    MyFile openFileForWriting(string path);
    bool printFile(string path,volatile void * printerAddress);
    //blah blah
    }
    int main(){
    MyFile * myFile = new MyFile();
    //using my file.......;
    delete myFile;
    return 0;
    }
    view raw exampleTwo.cpp hosted with ❤ by GitHub
    Correct way:
    #include <iostream>
    using namespace std;
    class File{
    //file buffer and stuff
    }
    class FileInput{
    //some privates
    public:
    File openFileForReading(string path);
    //other stuff related to input such as parsing etc
    }
    class FileOutput{
    //some privates
    public:
    File openFileForReading(string path);
    void writeToFile(File, char* content);
    //other stuff related to writing such as encoding different formats
    }
    class PrinterHandler{
    //code to handle printing
    }
    class MyFile{
    FileInput fInp;
    FileOutput fOut
    PrinterHandler printerHandler;
    File file;
    public:
    //code;
    }
    int main(){
    MyFile * myFile = new MyFile();
    //using my file.......;
    return 0;
    }
    See, In second example each class has its own goal and at the end objects of these classes are packed together to provide single ultimate solution to all the things related to file handling.
  • If it doesn't fit in one line then it doesn't have to be. Exactly, sometimes single statement of code becomes so large that it is hard to remain in limit of 80 characters. In these kinds of cases try breaking a single line into multiple sub lines. Follow style used by Java developers.
    package example;
    class ExampleThree{
    public static void main(String[] args){
    String someText = "someTextIsThereForYouToProcess";
    //ordinary way
    System.out.println(someText.trim().replace(" ","%20").substr(3,someText.length).concat("\\r\\n").toUpperCase());
    //recommended way
    System.out.println(someText.trim()
    .replace(" ","%20")
    .substr(3,someText.legth)
    .concat("\\r\\n")
    .toUpperCase());
    }
    }

Okay, that's all for this one. If you have any question you can ask them in comment section, I will try to respond ASAP. And do follow this blog(show some love naa ❣). Have a nice time.

Comments

Popular posts from this blog

Kotlin: Higher order functions, Lambdas and Extension methods

Photo by Aaron Burden “Truth can only be found in one place: the code.” ―Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship Happy winter, how are you?. This post is continuation of Kotlin series. If you haven't read my introductory post about Kotlin then I'll recommend you reading previous post before continuing with this one. Kotlin is a modern language. I've been working with kotlin for past few months now and I just love it. In todays post I'll talk about three features of kotlin viz. Higher Order Functions, Lambdas and Extension methods. This post also contains working code showing of each of these features. You are free to copy the code and experiment with it. If you haven't already setup kotlin on your system then you can run code using kotlin online playground . Higher order fu...

Coding conventions part 1 : Naming Things

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” —John Woods At some point in the life of every programmer comes a time, when he/she realize that the way he/she organize code sucks(I have this moment like every day). And it's time to change few things and start caring about the organization and readability of code. Code organization is crucial part of software development. Because software is not something which is developed from scratch again and again (as it will cost both time and money) but is updated and maintained for as long as it is possible to do so(this is why we have code re usability thingy). Programmer of special breed that is “Software Maintainer” is assigned this task. These are some of the most calm people in the industry because most of their salary is spent on Anger Management (May God bless them). If a code is poorly organized then more time is spent in refactoring it th...

Kotlin : An introduction

Photo by wu yi “A language that doesn't affect the way you think about programming is not worth knowing.” ―Alan J. Perlis World was nice and there was only assembly(“real programmers code in assembly”) but then one day out of blue he (hey! don't look at me like that I too don't know his name) came and said let there be compilers and interpreters(line by line) that will translate languages easy to read(uh! nah not really) and write into assembly to make programming fun again and that gave birth to an era of exotic new programming languages called procedural programming languages. Procedural programming languages were doing fine but after some time lot's of programmer started loosing their objects because of stateless functions which globally caused chaos. Seeing all this made him angry. So he said, “Procedural languages, I command you to treat everything as an ‘Object’ which will have it's own properties(attributes) and behavior(methods)”. They respond...