Sie sind auf Seite 1von 36

p.

B:hEmAl rAJYAGURU,gujarat

Cod guidlin

S. To:Mr. Rahul Dev Singh,


Sirsa,Haryana

Coding Guidelines
Submitted To:
Prof. Rahul Dev Singh
CE Department
NIT-Kurukshetra

Presented By:
Hemal Rajyaguru
M. Tech-211519
NIT-Kurukshetra

Why Standard is Important?


Though at initial stages it seems like a burden to follow standard, its
advantages become visible once the software grows to few thousand
lines spanning and few hundred files.
Some of the advantages are: Programmer feels comfortable with
the code written by others, as it is similar to what he himself would
have written.
Person joining the group at later stage can pickup the code easily
(once he is familiar with the standards).
If care is taken to define the standard in such a way that it avoids
problematic idioms, then silly mistakes can be avoided.
The problem with having standard is that it takes time to get
acquainted with it. And if care is not taken during this transition
period, then the resulting code will be a mix of standard and
programmer's natural style.

Naming Conventions
My name is Bond. James Bond.
It is very important to give
meaningful names to all your
constructs.
e.g. A name like
getAverageHeight() or
get_avg_height() gives us much
more information then calculate().

Variable Naming
As a rule of thumb : bigger the scope bigger the name.

Global variables should have descriptive names.

Also, the declaration of global variable should be accompanied by small comment


describing its purpose.

The reason for it is that many people will be using the global across different files in
different contexts, and every one should be sure of its usage.

If the scope of variable is limited, then it can have smaller name. For example, It is OK
to call a variable i which is used as a loop counter or index variable, provided it is not
used to do anything else significant.

It should start with lower case.

use camelCasing for member variables like maxHeight;

Some names do have standard abbreviation, for e.g. max. So, calling a
variable maxLength gives us the same amount of information as
maximumLength, but using the former saves some keystrokes .
Names starting with _ (underscore) and __ (two underscores) are
reserved for compiler writers. These should be avoided.
There are 2 common practices to separate words in a multiple word
name:
using _ or capitalization. For e.g., a routine for getting maximum length
can be called either max_length or or maxLength.
We are planning to follow 2nd practice (maxLength), unless there are
serious objections to it. Since we shall definitely use STL, and STL uses
first style of names, it will allow us to distinguish between STL variable
and inhouse variables.
If an abbreviation is contained in a name, it should not be used in all
uppercase form.
for example: use getHtmlPage // not getHTMLPage

Constants

Constants names should be distinguishable from variables. There


are few conventions for it: All uppercase name, with _ as word
separator: MAX_ERRORS

suffix C in name: maxErrorsC

Most of time companies using first convention ( all


uppercase with _ ).

Classes

Name of a class should communicate its purpose. It is always


beneficial to identify and name all the major classes in the
program at design stage itself.

Class name should start with an uppercase alphabet. class


BasicBlock;

Functions

functions should be named similar to variables. We can


always distinguish between, because of the parenthesis
associated with functions. Prefixes should be used in
functions to make its meaning clear. This is specially useful
for boolean functions. Some common prefixes are:
is : isPrinterOn()
has: hasPages()
can: canOpenBottle()
get: getMaxLimit()
set: setPath()

As per standard, Variable name are


noun and function name are verb to
clarify functionality of function.

Success is more a function of consistent common sense than it


is of genius. -- An Wang e.g. chandani chowk to china

A Function should normally do only one job and do it well.

Avoid generic functions with lots of conditional branches to do


everything.

If a function is supposed to do multiple jobs (for e.g. a driver function


to add, delete, modify etc.), then create helper functions and delegate
responsibilities to them.

Make functions simple and small. Ideal size of functions is around 35


- 40 lines.

Number of parameters to a procedure should be no more then 5-6.

The name of function and its parameter should have logical


significance.

File Naming and Organization


It is not so important to know everything as
to know the exact value of everything, to
appreciate what we learn, and to arrange
what we know. -- Hannah More
Example of mind at exam time.
In routine we know everything but we have to
arrange the thing in exam.
Give directory structure of project in eclipse.

Formatting and Indentation


When I'm working on a problem, I never think about
beauty. I think only how to solve the problem. But when I
have finished, if the solution is not beautiful, I know it is
wrong. -- R. Buckminster Fuller (1895 - 1983)

The start brace "{" and end brace "}" for a function should be in
first column (and preferably alone in that line). That makes easy
navigation to start and end of a function.

Indentation should be 4 spaces/one tab.

A line should NEVER be more than 80 characters, because that


is the default width of xterm, printers etc. Agreed you can adjust
the width while reading on screen, but you cannot adjust the
width of your printout.

Final rule for it::MAKE IT READABLE.

Comments and
Documentation
Comments are free but facts are sacred(holly/useful). -- Charles
Prestwich Scott
Start each file with a copyright notice, followed by a description of the
contents of the file.(Include author name, date, developed at,etc)
(Note: Here I am not talking about the documentation as in design-document
or user-guide, but documents which explain working of some part of the code
and passed among generation of developers to understand the source code.)
Comments and Documentation are aid to understand the code. They
help us in following the program flow, and skip parts for which we are not
interested in details.
If one is not careful, then they become rewriting of what is already written in
the code. So, they have same problems as duplication of source code:
consistency, maintenance etc. These should be minimized by making the code
self explanatory.

Though a pain to write, comments are absolutely vital to keeping our


code readable.
The following rules describe what you should comment and where.
But remember: while comments are very important, the best
code is self-documenting.
Giving sensible names to types and variables is much better than
using obscure names that you must then explain through comments.
When writing your comments, write for your audience: the next
contributor who will need to understand your code. Be generous
the next one may be you!
Pay attention to punctuation, spelling, and grammar; it is easier to
read well-written comments than badly written ones.

Classes
The loftier the building, the deeper must the foundation be laid. -Thomas Kempis
don't make your modifier routines public thereby allowing every class to
modify the data and thus creating a cause for potential havoc. Instead: Make
the modifiers private.
Some routines/interfaces are inherently used by every one - for e.g. push/pop
routines of a generic Stack class. Only such routines must be made public.
Separate the core algorithm/strategy to be implemented in a separate class
from the actual class consisting of data and data management/bookkeeping
routines.
Ensure that your classes are not bloated. If you have a class which has a huge
amount of data and methods, it means that you have not designed to correct
level of granularity and hence need to break this bloated class into more
classes.

Minimizing Bugs while Coding


If debugging is the art of removing bugs, then programming
must be the art of inserting them. -- Unknown
Being a little careful while coding makes it easy to minimize bugs in
the code.
Initialize your variables.
Limit the scope of variables. In a language like C++, local variables
should be declared near to its first use. This helps in keeping track of
initialization of local variables.

Keep optional compiler warnings on. Most of the compilers can warn
for legal language idioms which can be used in mistaken way and for
non-portable code.
So as a good programmer you should notice error as well as
warnings.

Minimizing Bugs by Testing

No part of your code should remain un-exercised. There


should be separate tests to exercise all branches in the
program.

Use code profiling tools (see Miscellaneous) to make sure


code is getting exercised.

Looking at the final output is not enough. Use debugger


to step through the code to make sure that the test
executes the correct part of the code.

Miscellaneous
Programming today is a race between software engineers running to
build bigger and better idiot-proof programs, and the University trying
to produce bigger and better idiots. So far, the University is winning.
-- Hemal Rajyaguru(Inspired from Rich cook)

Some of the processes which help in developing good software are: Having
functional specifications, design document, and other helper documents ready
before start of coding.

Peer code review.

Some of the important tools used for code tuning in large software development
are:
Lint tools (lint, splint) - To catch portability problems
Debuggers (gdb, dbx) - To catch logical errors
Memory Profilers (purify, mempetrol, valgrind) - To detect memory leaks,
unutilized memory use etc.
Code coverage tools (purecov, tcov, gcov) - To look for the part of code which
did not get exercised.
Code Profilers (quantify, gprof, prof, vprof) - Used for optimizing the
performance
Look for the tools available for your platform, learn them and use them
extensively.

References
The man who doesn't read good
books has no advantage over the
man who can't read them. -Mark Twain (1835 - 1910)
So try to refer concrete and well
knowledgeable reference while
learning coding.

Never forget your programming


is part of your public image.
Programming should express who
you are, as an artist, your knowledge
level.
Eg:A.K.Singh Sir
Bachho jaisi programming mat karo.
so please do it like a IT professionals.

Golden Words
If you want to please the audience, please yourself
first
I think programming is first about you.
I may sound a little selfish here but let me explain. I deeply
believe that if you are intimately connected to the works you
play, the audience will do so.
If you are convinced your program and playing are wonderful,
you can convince an audience.
Eg:JAI BHADRAKALI

Audience dislikes being


lost
people like to feel in a safe environment.
And what is a safe environment musically speaking?
Music they know and appreciate.
You have to find a balance between known and unknown
pieces : enough hits for people who want to feel safe,
enough discoveries for people who like surprises.
In short keep code live.
And try to make linking code or keep precise flow so it
can able to allude interest in code.

Structure, structure and structure


again
Like musical forms, there must be a
structure in the program involving
among others the famous
tension/rest couple. No audience
could bear 2 or 3 very tensed works
in a row, nor 3 calm works in a row.
You have to let breathe the audience
after tension but not send them to
sleep!

Habits those we must


grow
1.Before sitting down for coding, you
must have formal or a paper-napkin
design of the solution to be coded.

Never start coding without any


design unless the code is trivial one.

2. Good code documentation is as important


as good knowledge of a programming
language.
Write brief logic for each major block of your
code as comments in source code file itself.
Its good to mention creation and
modification dates of your program alongwith why modification was required.

3. Maintaining versions of your program is


another important task.
Some present-day programming tools already
have a built-in version management.

Must insert at least date or some


explanation phrase to your program versions
in program.

Eg:eclipse

4. If your project contains multiple


source files then maintain a README
file stating purpose of each source
files, data files, intermediate and log
files (if any).

You may also mention the


compilation and execution steps.

5. Ever wondered why your IF statement is not


working as it should do.
May be you are using single equal i.e. = instead
of == in the condition check.
A good approach is to write condition in reverse
order. So, your condition should read something
like this:
if ( 10==i). So, if you put single equal sign by
mistake then it will be detected at compilation
time only as an error.

6. While using loops and conditional statements,


always first put closing braces corresponding
opening braces and then write the inner statements
i.e.
1)
2)
4)
3)

for(int i=0;i<10;i++)
{
printf(i=%d\n,i);
}

The numbers at the starting of each line indicate


sequence of writing loop code.
In present days tool are doing this for you.
Redirect to eclipse.

7. Avoid using magic numbers. For


example, instead of writing
circleArea = 3.14 * pow(radius,2);
use following code:
#define PI 3.14
circleArea = PI * pow(radius,2);

9. Using print statements for later debugging is a good


habit.

But, removing them when final code is ready is,


sometimes, a risky task.

So, make a function that displays debugging


information passed to it.

When your final version is ready, simply comment


the internals of this function. So, this requires changes
only at one place.

10. Once you are done with coding, start optimizing


your code.
Some of the variables you declared earlier may
not be of use at this stage.
Similarly, statements which are not loop
dependent can be moved out of loop block.
Sound knowledge(means how it treat ur code) of
compiler can also help in optimizing the code
further.

11. Always indent your code for clarity


and easy readability.
12. Always organize project files into
various folders like SOURCE,
HEADERS, MAKE, EXES etc.
Redirect to eclipse

13. Study the code written by others. This will


bring to you new programming techniques.
and what approach they have followed for the
task for which you have also coded.
And if u find better approach then simply copy
and paste it. like most of us are doing but try to
reach at that stage so other can take ur code
as an reference and do copy paste of it. this
will give u superb feeling.

14. Take backup of your source-code files so


that your effort dont go waste if hard-disk
crashes or a similar mishappening occurs.
15.Re-evaluate your code in free time.
After development when you have free time.
Re-evaluate your work, your coding styles.
Check weather you miss anywhere to apply
the standard. Find out loopholes and try to
overcome on it in your next session of coding.
Make them part of your quality
assurance process.

Last but not least keep habit to read


this habit often.
It will give u freshness for doing
coding.

Thanks!!!!!!!!!
Enjoy Coding!!!!!!!!!!!!!!!!!!!!!

Das könnte Ihnen auch gefallen