Thursday, 13 June 2013

[Gyan/ Knowledge] 10 Steps to help write a readable code

10 Steps to help write a readable code


  • Commenting and documentation

IDE (integrated development environment) have come a long way and most are comfortable using these IDE’s because they save a lot of our time.
Comments should be simple and basic English understandable to everyone. Comments help us to understand the code even without going through the function. IDE’s help us by showing these comments to know what the function does while calling the function.

  • Consistent Indentation

It is very important to indent your code simply because it makes it readable
Ex: in C++
Cout<<”hello world”; if(i==0) cout<<”zero”; else cout<<”not zero”;
(will work perfectly fine)

Cout<<”hello world”;
If(i==0)
{
Cout<<”zero”;
}
Else
{
Cout<<”not zero”;
}

(brackets are not compulsory, code will work if not as well)
There are many styles of indentation, you can choose any style but it is very important to be consistent with your style.
But remember when in group doing a project it is always good when all the team follows the same style.

  • Avoid obvious comments

Commenting your code is fantastic however, it can be overdone or just be plain redundant. When the text is that obvious, it’s really not productive to repeat it within comments. If you must comment on that code, you can simply combine it to a single line instead.
Adding a comment at the beginning of each block of code also emphasizes the virtual separation.

  • Consistent naming scheme

Function names and variables names should be consistent, readable and understandable.
It is very important to have word boundaries in names, two ways to do:
    • camelCase: First letter of each word is capitalized, except the first word.
    • Underscore: underscore between words, like: mysql_real_escape_string().
Similar to indent this also has many ways. It is always advisable to follow certain convention in an existing project. There is no “best” style but always remember one thing be consistent.

  • DRY (dont repeat yourself)

The purpose for most application is to automate repetitive tasks. This principle should be maintained in all code, even web applications. The same piece of code should not be repeated over and over again.

  • Avoid deep nesting

Too many levels of nesting makes it harder to read and follow and sometimes even harder to remove errors (if any). For the sake of readability it is better to reduce deep nesting.

  • Limit line length

As humans we are more comfortable reading small horizontal lines. So it is good practice not to write long lines.

  • Use of files and folders

You can always write the entire program in a single file, but that would be a nightmare to read and follow. As the programs become huge it is advisable many files and use “include files” etc. Common files can be combined in a folder for better understanding.

  • Capitalize SQL Special words

Creation of database is a important part of any web application. If writing raw SQL queries, it is a good idea to them readable as well.
Even though SQL special words are case insensitive, it is common practice to capitalize them to distinguish them from table and column names.

  • Object oriented Vs. procedural

Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good. Objects should be used for representing data, usually residing in a database.


[Gyan/ Knowledge] Structured vs Object Oriented Programming

Arranging your codes

When we talk about the difference between C and C++(in this matter python and JAVA as well), we often come across the term "Structured" and "Object Oriented", w.r.t C and C++ respectively.
So, what are these?
What exactly is the difference between them?
Why is Object Oriented Programs more used and needed in this present world?
Let us understand these concepts and try to implement them in a program.


Data Structure:


It is a method of storing and organizing data. Examples would include an array, a struct, a class, etc.
Take for example, you own a company. Now you want to store some information of your employees, say Employee ID and Employee Name. You could save them just like that in a Alphabetical order. Now this becomes your Data Structure.


Structured Programming:


This is a older style of programming. It is said to have approximately been born in 1960s. It follow top-down logic.
Now what is top-down logic? Well, consider you are given a recipe to prepare a cup of tea. Assuming you accurately attempt each individual step, but you do not follow the order in which the recipe was given, i.e, you do not start from 1st step(top) and then go downwards. Rather you assume your own priorities and do the work. This would lead to a great tea massacre in the kitchen. Following the steps, in a procedural manner is what top down logic is all about!
Structured Programming was aimed at improving the quality, clarity and development time of a program by using subroutines(functions), block structures and loops(for and while loops). This technique emphasizes on the procedure. They are:


  1. Sequence: Executing one subprogram and then another subprogram (Ex: Addition of 2 numbers follows a specific procedure). Executing instructions one by one is nothing but the top-down logic.
  2. Selection: Executing one of the two subprograms according to the value of a Boolean expression (if loop)
  3. Repetition: Executing a subprogram until a Boolean expression is true (for loop)

Even though structured programming improved quality, clarity and development time, it failed to solve one problem, i.e, ABSTRACTION. Structure Programming has a lower level of Abstraction!
Ok, so now what is Abstraction?
As the name suggest, we try to give a abstract picture of the implementation of the code, to the programmer(us)  with the help of a representation relevant to the current perspective. Abstraction tries to reduce and factor out the details, so that the programmer(we) can focus on a few concepts at a time. We shall deal with this further, when we go into OOPS completely.


Object Oriented Programming:

In this style of programming, the programmer can not only define the data type, but also define functions that can be applied to the Data Structure. This is how a Data Structure turns into a Object!

What is an Object?

Just look around, you'll find many examples for an "Object"! Let us take a PEN. A pen is an object? How do we say that? By observing its characters! Any object has 2 qualities: State and Behavior.  For a PEN, the State would be its Shape, Color, Size, etc.  And Behavior?? Behavior is basically the operations it can perform. Like Pen can be used to write, draw, etc. Now look at it this way, the "State" of a object in your program is like your Data Types and the "Behavior" is the Functions defined to perform various activities in capability of that object! You can now use the PEN with the desired size and shape for playing pen fight. In this case you refer only the size and shape of the object,ie, using data types only. And if you are writing a exam paper, you'd probably look in the behavior of the pen (how smooth it writes, comfort it has, etc), ie, using its properties (defined functions).
In the Software world, the State is referred to as fields or variables and Behavior as Methods.
Methods use the objects internal state and help in object to object communication(MESSAGE PASSING).
Hiding the internal state and requiring interactions to be performed through an object's methods is called "DATA ENCAPSULATION". Such a kind of bundling code into objects has various advantages like:
  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.


What is a Class?

A set or category of things, having some property or attribute in commin and differentiated from others by kind, type or quality. In the software world, class is a collection of similar type of objects.It is like a blueprint (or prototype) that defines methods and variables common to all objects of that kind. For Example, take your own class. You would be a object(with your state and behavior), so would the other students in your class be as well. Additionally, your school would be the program and your principal would be the main routine. Now if your pricipal calls for Shubham, the class needs to be specified so that the specific Shubham in that class could be summoned in front of the principle(Assuming there is only one Object called Shubham).

Some Very Important terms and definitions in OOPS:


Instance

It is the actual object created at run-time. We can have instance of a object or a class (ie, During run-time the variables may change).


Abstraction

Refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes.


Encapsulation

It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. Like isolating one code from another. Like the medicinal capsule, even though the composition of the medicine is the same, we store them in capsules, so that the dosage is fixed! So classes can be thought of as a container and data present can't be accessed by outside world.


Inheritance

It is the process by which one object acquires the properties of another object. This helps in hierarchical classification, without which, we'd need to explicitly define all the characteristics. Inheritance is a property that generally passes from parent class to sub class. Kind of like the genes that is transferred from our parents to us to our children.


Polymorphism

The ability to take more than one form. An operation may exhibit different behavior in different instances. The behavior depends on data types used in the operation. To be precise, it means, one interface, multiple methods.


Generalization

It describes an is-a relationship which represent a hierarchy between classes of objects. Like PEN is a generalization of "black pen", "blue pen", etc.


Specialization

It means an object can inherit the common state and behavior of a generic object. To be more clear, each object needs to define its own special state and behavior. So specialization means to subclass Generalized class, ie, if Pen is generalization, Red pen is specialization, ie, Red-Pen is a special kind of Pen.

We shall utilize these concepts and build programs around these in the upcoming articles!
ShrekzZzCount Up