Saturday, March 06, 2010

best practices in coding

Some basic issues in every development team
fundamental discipline issues in coding
number of years of exp. does not match delivery
by the time they actually become good coders, they are promoted to leads
70% of the whole employees, belong 0-4 years of experience

In India, senior developer means 3-5 years of exp, in USA, senior developer means 6-10 years of exp – There is a huge gap in expectation and quality

Coding is not rocket science

The rework time in coding is the actual killer
20-25% of the time is spent in reworking in software – that means, fix the mistakes done
In a mobile phone, can you insert sim card wrongly? You cannot. Because the sim card design is like that. So the highest level maturity is not to give an opportunity to make mistakes

As a kid, you were asked and helped to brush the teeth. It was tough to brush teeth.
One fine morning, you start brushing teeth by yourselves.
Then it has become a habit. You need not be told to do brushing by anyone.
Commenting is necessary for maintaining any program
Without commenting, the program is not complete
Do not assume that the other person who reads this program will understand it clearly
If commenting is not done at the beginning, it is forgotten.

Program - a physical file – you need to comment the following at the top.
at the top of the program - header comment
what the program achieves
who coded on what day

Classes
Comment at the beginning of the class about what the class does
class Employee
// this class is used to manage all information
// about employees and retrieve specific data

Methods within classes
what this method/function/procedure does
what are the parameters and their purpose
what are the return values

Comment before every loop.

Comment before every file or database operation

Comment before every if condition
If you are team leader, if your team member comes with a code, that does not have these comments – what will you do?
You take over a program for maintenance from another person, and that program has no comments – what will you do?
Your company hands over a project to client. Programs do not have comments. What the client will say?
Readability improves understanding; that further improves maintainability
If programs are not consistent, maintenance is tough
If 20 developers work in a project and each one names functions in the way he/she wants, will the client approve the same?
We must have a document on naming conventions
Every document must be named properly and it must be stored in a proper folder.
You need to have a convention for naming
Programs
Classes
Methods
Variables
Labels in programs
Reusable library functions
There are established methods like Pascal casing, camel casing etc.
Usually you will tend to use a mixture of uppercase, lowercase letters, underscore etc
The ultimate aim is to achieve consistency across programs
Placing a number or quoted text inside active code is hard coding
This is deadly as the program restricts itself to this hard coded value
To make a change, you need to change code, recompile and redeploy
Usual way to avoid hard coding is to use constants at the top of a program; here also, you need to edit the program, but the change is in one place
Other way is to put all configurable values in a csv or ini or dat file. Every program must read the name value pair from the file and later use them in the code
Eg. MAX_LENGTH 150, PORT 8097

Modularity is important for easy maintenance
Do not write lengthy methods or procedures
We can split the modules based on
A functional operation as per requirements
A piece of code is used in more than one place
Logical breakdown of events in the functionality
Modularity must be decided right at the design level itself
Modular programs are easy to debug
Fixes done on modular programs are easy to isolate from other regression effects
A loop is - repeat some logic for specific number of times or as long as a condition is true/false
If this is not checked, it can run forever, infinitely and can bring down the server
Loop Sample
gateway 1 // variables, flags
xyz = 10
loop starts here
...gateway 2 // variables, flags, counters
..
logic
... gateway 3
loop ends here
gateway 4
Gateways are the check posts where we must watch the value of the variables, loop counters and loop flags
Ensure proper resetting of flags and counters and check their values and gateways of the loops
Never allocate memory inside a loop
Never instantiate a class inside a loop; if needed, close it within the loop
Usually companies do not suggest more than 3 levels in the loops

Issues may be caused by programmer
Issues may be caused by system
Most of the languages allow try-catch or on-error-goto exceptions

Exception is also an error condition
we do not know when it will happen

1. Any file operations – handle exceptions, because
file may not exist
file is already opened by someone
file does not have privilege
file is already full

2. Any database operation – handle exceptions, because
database you may not have rights
database is down
connections exhausted

3. Memory
low memory exception
pointers - writing in privileged memory
array boundary breach

4. Any external evices
your program accesses webcam or printer
We need to monitor cpu, memory, network

Memory is directly related to variables and object – do not declare huge arrays or objects

Cpu is consumed more when you deal with db or files or devices

Any database operations, open late and close the connection early.

Usage of indexes in queries must be examined

Any column used in where condition of db query must have index on it

Any memory allocated must be freed – else the program will shut down after some time

Any object instantiated must be released – else system will be depleted of memory and hence performance will come down
Usually the logic design will be provided to the developer
If it is not provided, take 30 minutes and write the logic of the program in English first
Do not start coding right away. You will make so many assumptions and it will spoil the show
Get the logic approved by the team lead and then start coding
Developers usually feel that this takes time; but it reduces the time effectively while coding and reworking
Since developers are not used to documenting, they feel it is not their job. Hence they miss a lot of finer points
If you write the logic first, you will get a lot of clarifications at that time itself and hence the code will come out clean

Sample Test Paper For CHSSC

1.In case of Unix File System , how many pointers from I Node block are needed to
access memory size of 1,00,000 bytes of data?(Let one pointer = 4 bytes, 1 block =
512 bytes)
a)11
b)12
c)13
d)10
2.Withdrawing cash from a bank is an example of …………….processing.
a) independent
b) cooperative
c) both a) and b)
d) none of these
3.Consider the following instruction:
move r0,#3324
move [r0],#5
The data 5 can be found at …………………. after the execution of this instruction.
a) location whose address is 3324
b)at r0
c)location whose address is 5
d)none of thes
4.With the help of single indirect pointer,total data that could be reffered to is:
a) 128bytes
b) 512bytes
c) 70656bytes
d) 32bytes
5. Lexical Analysis performs
a) CHECKS THE CORRECT USAGE OF KEYWORDS,CONSTANTS,IDENTIFIERS
AND TOKENS.
b) STORES THE INFORMATION ABOUT
KEYWORDS,CONSTANTS,IDENTIFIERS IN SYMBOL TABLE.
C) STORES THE INFORMATION ABOUT
KEYWORDS,CONSTANTS,IDENTIFIERS IN PARSE TREES.
d) CHECKS THE VALIDITY OF ASSIGNMENT OPERATIONS.
6. In fully connected network for 3 and 4 sites number of hops is
a) 1
b) 2
c) 0
d) 3
7. Examine the following code segment
for(i=0,i{
a=a+i;
}
The error given during compilation is the responsibiity of
a) Lexical Analyser
b) Semantic analyser
c) Syntactic Analyser
d) Code optimization
8. When the page size decreases, the number of page fault increases.
a) true
b) false
c) cannot be stated
d) no choice
9. Where we need the idea of compaction in the memory management
a) variable partition allocation
b) fixed partition allocation
c) re-locatable partition allocation
d) single contiguous allocation
10. Which type of scheme does windows3.1 have
a) preemptive multitasking
b) preemptive scheduling
c) uni programming
d) co-operative multitasking

C language programs

1. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
Answer:
0 0 1 3 1
2. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Answer :
three
3. main()
{
printf("%x",-1<<4 br="">}
Answer:
fff0
4. main()
{
int c=- -2;
printf("c=%d",c);
}
Answer:
c=2;
5. main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}
Answer: i=0
1
6. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
7. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
8. main()
{
printf("%p",main);
}
Answer:
Some address will be printed
9. main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300
10. void main()
{
int i=5;
printf("%d",i++ + ++i);
}
Answer:
Output Cannot be predicted exactly.
11. void main()
{
int i=5;
printf("%d",i+++++i);
}
Answer:
Compiler Error
2
12. #include
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
Answer:
Compiler Error: Constant expression required in function main.
13. main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
14. main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer:
1
15. main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.
16. main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
3
17. main()
{
char not;
not=!2;
printf("%d",not);
}
Answer:
0
18. main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Answer:
1==1 is TRUE
19. main()
{
int y;
scanf("%d",&y); // input given is 2000
if( (y%4==0 && y%100 != 0) || y%100 == 0 )
printf("%d is a leap year");
else
printf("%d is not a leap year");
}
Answer:
2000 is a leap year
20. main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1
21. #include
main()
{
const int i=4;
float j;
j = ++i;
printf("%d %f", i,++j);
}
Answer:
Compiler error
4
22. main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11
23. main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0
24. int i;
main(){
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
// If the inputs are 0,1,2,3 find the o/p
Answer:
4--0
3--1
2--2
25. main(){
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer:
hello
26. void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer:
0 65535
5
27. main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer:
I hate U
28.a<<1 2="" a="" above="" adding="" b="" br="" by="" c="" d="" dividing="" equivalent="" is="" multiplying="" none="" of="" the="" to="">29. The operation of a stair case switch best explains the a) or operation b) and operation c)exclusive nor operation d)exclusive or operation
30. Which of the following is/are syntactically correct? a) for(); b) for(;); c) for(,); d) for(;;);
31. The expression 4+6/3*2-2+7%3 evaluates to a) 3 b) 4 c) 6 d) 7
32.Any C program a) must contain at least one function b) need not contain ant function c) needs input data d) none of the above
33. Using goto inside for loop is equivalent to using a) continue b) break c) return d)none of the above
34.The program fragment inta=5,b=2; printf(“%d”,a+++++b); a) prints 7 b)prints 8 c) prints 9 d)none of the above
35. printf(“ab” , “cd”,”ef”); prints a) ab abcdef c) abcdef, followed by garbage value d) none of the above
36. Consider the following program segment. i=6720; j=4;
while((i%j)==0)
{
i=i/j;
j=j+1;
}
On termination j will have the value
a) 4 b) 8 c) 9 d) 6720
UNIT-II
Predict the output or error(s) for the following:
6
37. main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn
38. main()
{
extern int i;
i=20;
printf("%d",i);
}
Answer:
Linker Error : Undefined symbol '_i'
39. #define int char
main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}
Answer:
sizeof(i)=1
40. #define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
41. #include
#define a 10
main()
{
#define a 50
printf("%d",a);
7
}
Answer:
50
42. #define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
43. main()
{
clrscr();
}
clrscr();
Answer:
No output/error
44. main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
45. #define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}
Answer:
100
8
46. main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
47. main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer:
Compier error: Type mismatch in redeclaration of show.
48. int i,j;
for(i=0;i<=10;i++)
{
j+=5;
assert(i<5 br="">}
Answer:
Runtime error: Abnormal program termination.
assert failed (i<5 file="" name="">,
49. #define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
Answer:
TRUE
50. #define max 5
#define int arr1[max]
main()
{
typedef char arr2[max];
arr1 list={0,1,2,3,4};
9
arr2 name="name";
printf("%d %s",list[0],name);
}
Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})
51. int i=10;
main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}
Answer:
30,20,10
52. #include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d..%d",*p,*q);
}
Answer:
garbagevalue..1
53. #include
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}
Answer:
hello 5
54. main()
{
int i=_l_abc(10);
10
printf("%d\n",--i);
}
int _l_abc(int i)
{
return(i++);
}
Answer:
9
55. main()
{
char c=' ',x,convert(z);
getc(c);
if((c>='a') && (c<='z'))
x=convert(c);
printf("%c",x);
}
convert(z)
{
return z-32;
}
Answer:
Compiler error
56. main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}
Answer:
1000
57. What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}
ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
11
i. ANSI C notation
ii. Kernighan & Ritche notation
58. void main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}
Answer:
0 0 0 0
59. void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7
60. void main()
{
char a[]="12345\0";
int i=strlen(a);
printf("here in 3 %d\n",++i);
}
Answer:
here in 3 6
61. void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}
Answer:
Ok here
12
62. main()
{
clrscr();
}
clrscr();
Answer:
No output/error
63. main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer:
5 4 3 2 1
64.Cpreprocessor a) tales care of conditional compilation b) tales care of macros c) tales care of include files d) acts before compilations
65.A preprocessor command a) need not start on a new line b) need not start on the first column c) has # as the first character d) comes before the first executable statement
66. The following program
main()
{
int a=4;
change(a);
printf(“%d”,a);
}
change(int a)
{ printf(“%d”,++a); } outputs a)5 5 b)4 5 c) 5 4 d)4 4
67. The output of the following program is
main()
{
static int x[]={1, 2, 3, 4, 5, 6, 7, 8};
int i;
for(i=2;i<6 br="" i="">x[x[i]]=x[i];
for(i=0; i<8 br="" i="">printf(“%d”,x[i]);
}
a) 1 2 3 3 5 5 7 8 b)1 2 3 4 5 6 7 8 c) 8 7 6 5 4 3 2 1 d)1 2 3 5 4 6 7 8
13
68. The order in which actual parameters are evaluated in a function call a) is from the left b)is from the right c) is compiler dependent d)none of the above
69. The default parameter passing mechanism is a) call by value b) call by reference c) call by value result d) none
70. C does no automatic array bound checking. This is a) true b) false c) C’s asset d) C’s shortcoming
71. If a two dimensional array is used as a formal parameter, then a) both the subscripts may be left empty b) the first( row) subscript may be left empty
c)the first subscript must be left empty d) both the subscripts must be left empty
72. If storage class is missing in the array definition, by default it will be taken to be
a) automatic b) external c) static
d) either automatic or external depending on the place of occurrence
73. Consider the declaration static char hello[]=”hello”; The output of printf(“%s\n”,hello); will be the same as that of a) puts( “hello”); b) puts(hello); c) printf(“%s\n”,”hello”); d) puts(“hello\n”);
74. The array name can be pointer to a) another array b) another variable c) to that array only d) none
75. Array of pointers to table of strings saves a) time b) memory c) CPU utilization d)none of the above
76. The following program
main()
{
inc(); inc(); inc();
}
inc()
{
static int x;
printf(“%d”,++x);
} prints
a)0 1 2 b) 1 2 3 c) 3 consecutive, but unpredictable numbers d) 1 1 1
UNIT-III
Predict the output or error(s) for the following:
77. main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5 br="" j="">printf(" %d ",*c);
14
++q; }
for(j=0;j<5 br="" j="">printf(" %d ",*p);
++p; }
}
Answer:
2 2 2 2 2 2 3 4 6 5
78. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet
79. void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer:
4..2
80. main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H
81. main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}
15
Answer:
Compiler error: Lvalue required in function main
82. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
M
83. main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(“%u %u %u %d \n”,a,*a,**a,***a);
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
}
Answer:
100, 100, 100, 2
114, 104, 102, 3
84. main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5 br="" j="">{
printf(“%d” ,*a);
a++;
}
p = a;
for(j=0; j<5 br="" j="">{
printf(“%d ” ,*p);
p++;
}
}
Answer:
Compiler error: lvalue required.
.
85. main( )
{
16
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}
Answer:
111
222
333
344
86. pointers are of a) integer data type b) character data type c) unsigned integer data type d) none of these
87. main( )
{
void *vp;
char ch = ‘g’, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}
Answer:
g20fy
88. main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}
Answer:
17
ck