Coding
Coding
Coding 1
Coding
Goal is to implement the design in best
possible manner
Coding affects testing and maintenance
As testing and maintenance costs are high,
aim of coding activity should be to write code
that reduces them
Hence, goal should not be to reduce coding
cost, but testing and maint cost, i.e. make
the job of tester and maintainer easier
Coding 2
Coding…
Code is read a lot more
Coders themselves read the code many times for
debugging, extending etc
Maintainers spend a lot of effort reading and
understanding code
Other developers read code when they add to
existing code
Hence, code should be written so it is easy to
understand and read, not easy to write!
Coding 3
Coding…
Having clear goal for coding will help achieve
them
Weinberg experiment showed that coders
achieve the goal they set
Diff coders were given the same problem
But different objectives were given to diff
programmers – minimize effort, min size, min
memory, maximize clarity, max output clarity
Final programs for diff programmers generally
satisfied the criteria given to them
Coding 4
Weinberg experiment..
Resulting Rank (1=best)
O1 o2 o3 o4 o5
Coding 5
Programming Principles
The main goal of the programmer is write
simple and easy to read programs with few
bugs in it
Of course, the programmer has to develop it
quickly to keep productivity high
There are various programming principles
that can help write code that is easier to
understand (and test…)
Coding 6
Structured Programming
Structured programming started in the
70s, primarily against indiscriminate use
of control constructs like gotos
Goal was to simplify program structure
so it is easier to argue about programs
Is now well established and followed
Coding 7
Structured Programming…
A program has a static structure which is the
ordering of stmts in the code – and this is a
linear ordering
A program also has dynamic structure –order
in which stmts are executed
Both dynamic and static structures are
ordering of statements
Coding 8
Structured Programming…
To show a program as correct, we must show that its
dynamic behavior is as expected
But we must argue about this from the code of the
program, i.e. the static structure
I.e program behavior arguments are made on the
static code
This will become easier if the dynamic and static
structures are similar
Closer correspondence will make it easier to
understand dynamic behavior from static structure
This is the idea behind structured programming
Coding 9
Structured Programming…
Goal of structured programming is to
write programs whose dynamic
structure is same as static
I.e. stmts are executed in the same
order in which they are present in code
As stmts organized linearly, the
objective is to develop programs whose
control flow is linear
Coding 10
Structured Programming…
Meaningful programs cannot be written as
seq of simple stmts
To achieve the objectives, structured
constructs are to be used
With these, execution of the stmts can be in
the order they appear in code
The dynamic and static order becomes same
Coding 11
Structured Programming…
SP was promulgated to help formal
verification of programs
Without linear flow, composition is hard and
verification difficult
But, SP also helps simplify the control flow of
programs, making them easier to understand
and argue about
SP is an accepted and standard practice today
– modern languages support it well
Coding 12
Some Programming Practices
Control constructs: Use only a few
structured constructs (rather than using
a large no of constructs)
Goto: Use them sparingly, and only
when the alternatives are worse
Use-defined types: use these to make
the programs easier to read
Coding 13
Some Programming Practices..
Nesting: Avoid heavy nesting of if-then-
else; if disjoint nesting can be avoided
Module size: Should not be too large –
generally means low cohesion
Module interface: make it simple
Robustness: Handle exceptional
situations
Side effects: Avoid them, document
Coding 14
Coding Standards
Programmers spend more time reading code than
writing code
Readability is enhanced if some coding conventions
are followed by all
Coding standards provide these guidelines for
programmers
Generally are regarding naming, file organization,
statements/declarations, …
Coding 15
Coding Standards…
Naming conventions
Package name should be in lower case (mypackage,
edu.iitk.maths)
Type names should be nouns and start with
uppercase (Day, DateOfBirth,…)
Var names should be nouns in lowercase; vars with
large scope should have long names; loop iterators
should be i, j, k…
Const names should be all caps
Method names should be verbs starting with lower
case (eg getValue())
Coding 16
Coding Standards…
Commenting and layout
Single line comments for a block should be
aligned with the code block
There should be comments for all major
vars explaining what they represent
A comment block should start with a line
with just /* and end with a line with */
Coding 17
Coding Process
Coding starts when specs for modules from
design is available
Usually modules are assigned to
programmers for coding
In top-down development, top level modules
are developed first; in bottom-up lower levels
modules
For coding, developers use different
processes; we discuss some here
Coding 18
An Incremental Coding Process
Basic process: Write code for the
module, unit test it, fix the bugs
It is better to do this incrementally –
write code for part of functionality, then
test it and fix it, then proceed
I.e. code is built code for a module
incrementally
Coding 19
Coding 20
Test Driven Development
This coding process changes the order
of activities in coding
In TDD, programmer first writes the
test scripts and then writes the code to
pass the test cases in the script
This is done incrementally
Is a relatively new approach, and is a
part of the extreme programming (XP)
Coding 21
TDD…
In TDD, you write just enough code to pass
the test
I.e. code is always in sync with the tests and
gets tested by the test cases
Responsibility to ensure that all functionality
is there is on test case design
Help ensure that all code is testable
Coding 22
Coding 23
Verification
Code has to be verified before it can be used
by others
Here we discuss only verification of code
written by a programmer
There are many different techniques; key
ones – unit testing, inspection
Coding 24
Code Inspections
The inspection process can be applied to
code with great effectiveness
Inspections held when code has compiled and
a few tests passed
Usually static tools are also applied before
inspections
Inspection team focuses on finding defects
and bugs in code
Checklists are generally used to focus the
attention on defects
Coding 25
Code Inspections…
Some items in a checklist
Do all pointers point to something
Are all vars and pointers initialized
Are all array indexes within bounds
Will all loops always terminate
Any security flaws
Is input data being checked
Obvious inefficiencies
Coding 26
Code inspections…
Are very effective and are widely used in
industry (many require all critical code
segments to be inspected)
Is also expensive; for non critical code one
person inspection may be used
Code reading is self inspection
A structured approach where code is read inside-
out
Is also very effective
Coding 27
Unit Testing
Is testing, except the focus is the module a
programmer has written
Most often UT is done by the programmer
himself
UT will require test cases for the module –
will discuss in testing
UT also requires drivers to be written to
actually execute the module with test cases
Besides the driver and test cases, tester
needs to know the correct outcome as well
Coding 28
Unit Testing…
If incremental coding is being done, then
complete UT needs to be automated
Otherwise, repeatedly doing UT will not be
possible
There are tools available to help
They provide the drivers
Test cases are programmed, with outcomes being
checked in them
I.e. UT is a script that returns pass/fail
Coding 29
Unit Testing…
There are frameworks like Junit that can be
used for testing Java classes
Each test case is a method which ends with
some assertions
If assertions hold, the test case pass,
otherwise it fails
Complete execution and evaluation of the test
cases is automated
For enhancing the test script, additional test
cases can be added easily
Coding 30
Static Analysis
These are tools to analyze program sources
and check for problems
Static analyzer cannot find all bugs and often
cannot be sure of the bugs it finds as it is not
executing the code
So there is noise in their output
Many different tools available that use
different techniques
They are effective in finding bugs like
memory leak, dead code, dangling pointers,..
Coding 31
Metrics for Size
LOC or KLOC
non-commented, non blank lines is a
standard definition
Generally only new or modified lines are
counted
Used heavily, though has shortcomings
Coding 32
Metrics for Size…
Halstead’s Volume
n1: no of distinct operators
n2: no of distinct operands
N1: total occurrences of operators
N2: Total occurrences of operands
Vocabulary, n = n1 + n2
Length, N = N1 + N2
Volume, V = N log2(n)
Coding 33
Complexity metrics…
Halsteads
N2/n2 is avg times an operand is used
If vars are changed frequently, this is
larger
Ease of reading or writing is defined as
D = (n1*N2)/(2*n2)
There are others, e.g. live variables,
knot count..
Coding 34
Complexity metrics…
The basic use of these is to reduce the
complexity of modules
One suggestion is that cyclomatic
complexity should be less than 10
Another use is to identify high
complexity modules and then see if
their logic can be simplified
Coding 35
McCabe’s Complexity
Measures
McCabe’s metrics are based on a
control flow representation of the
program.
A program graph is used to depict
control flow.
Nodes represent processing tasks (one
or more code statements)
Edges represent control flow between
nodes
Flow Graph Notation
While
Sequence
If-then-else Until
Cyclomatic Complexity
Set of independent paths through the
graph (basis set)
V(G) = E – N + 2
E is the number of flow graph edges
N is the number of nodes
Example
i = 0;
while (i<n-1) do
j = i + 1;
while (j<n) do
if A[i]<A[j] then
swap(A[i], A[j]);
end do;
i=i+1;
end do;
Flow Graph 1
2
7 4 5
6
Computing V(G)
V(G) = 9 – 7 + 2 = 4
Basis Set
1, 7
1, 2, 6, 1, 7
1, 2, 3, 4, 5, 2, 6, 1, 7
1, 2, 3, 5, 2, 6, 1, 7
Summary
Goal of coding is to convert a design into
easy to read code with few bugs
Good programming practices like structured
programming, information hiding, etc can
help
There are many methods to verify the code of
a module – unit testing and inspections are
most commonly used
Size and complexity measures are defined
and often used; common ones are LOC and
cyclomatic complexity
Coding 42
Common Coding Errors
Goal of programmer is to write quality code
with few bugs in it
Much of effort in developing software goes in
identifying and removing bugs
Common bugs which occur during coding
directly or indirectly manifest themselves to a
larger damage to the running program
List of common coding errors can help a
programmer avoid them
Coding 43
Memory Leaks
A memory leak is a situation, where the memory is allocated to
the program which is not freed subsequently
Occurs frequently in the languages which do not have
automatic garbage collection
Can cause increasing usage of memory which at some point of
time can lead to exceptional halt of the program
E.g char* foo(int s)
{
Char *output;
If(s>0)
Output=(char*) malloc (size)
If(s==1)
Return NULL /* if s==1 then mem leaked */
Return (output);
}
Coding 44
Freeing an Already Freed Resource
Programmer tries to free the already freed resource
May be serious, if some malloc between the two free stmts as
the freed location may get allocated to a new variable, and
subsequent free will deallocate the new variable.
E.g main()
{
char *str;
Str=(char *)malloc(10);
If(global==0)
free(str);
Free(str); /* str is already freed */
}
Coding 45
NULL Dereferencing
Occurs when we access a location that points to NULL
Improper initialization and missing the initialization in different
paths leads to the NULL reference error
E.g char *ch=NULL;
if (x>0)
{
ch=‘c’;
}
printf(“\%c”. *ch); /* ch may be NULL */
*ch=malloc(size)
ch=‘c’; /* ch will be NULL if malloc returns NULL */
Coding 46
NULL Dereferencing (accessing
uninitialized memory)
NULL dereference is the error of accessing initialized
memory
Often occurs if data is initialized in most cases, but
ALL cases do not get covered
E.g switch(i)
{
case 0: s=OBJECT_1; break;
case 1: s=OBJECT_2; break;
}
return (s); /* s not initialized for values other
than 0 or 1 */
Coding 47
Synchronization Errors
Possible when there are multiple threads which are accessing
some common resources, in a parallel program
categories of synchronization errors: deadlocks, race condition,
Deadlock example:
Thread 1:
synchronized (A){
synchronized (B){ }
}
Thread 2:
synchronized (B){
synchronized (C){ }
}
Thread 3:
synchronized (C){
synchronized (A){ }
}
Coding 48
Synchronization Errors…
Race condition occurs when two threads access same resource
and result depends on the order of the execution
piece_of_code1
{
// bunch of stuff done here
a=1
}
piece_of_code2
{
// another bunch of stuff done here
a = 2;
}
main
{
start_in_new_thread(piece_of_code1)
start_in_new_thread(piece_of_code2)
// wait for both piece_of_code1 and
// piece_of_code2 to complete
print(a) // whats the value of "a" here ?
}
Coding 49
Other common type of errors
Array index out of bounds, care needs to be taken to see that
the array index values are not negative and do not exceed their
bounds
Enumerated data types can lead to overflow and underflow
errors, care should be taken while assuming the values of such
types
typedef enum {0,1,2, 3} grade ;
void foo( grade x){
int l,m;
l= GLOBAL_ARRAY [x -1];
/* Underflow when A */
Coding 50
Other common type of errors..
Arithmetic exceptions, include errors like divide by zero
and floating point exceptions
Off by one errors like starting variable at 1 instead of
starting at 0 or vice versa, writing <= N instead of < N or
vice versa etc.
String handling errors like failure of string handling
functions e.g strcpy, sprintf, gets etc.
Illegal use of & instead of &&, arises if non short circuit
logic (like & or |) is used instead of short circuit logic (&&
or ||)
Coding 51