KEMBAR78
Guidelines to clean coding | PDF
GUIDELINES TO
CLEAN CODING
- Janak Porwal
PROGRAMMING PRACTISES
WHY?
“Most software today is very much like an
Egyptian pyramid with millions of bricks piled on
top of each other, with no structural integrity, but
just done by brute force and thousands of
slaves.”
-Alan Kay
SOFTWARE DEVELOPMENT
PROGRAMMING PRACTISES
“If builders built buildings the way programmers
wrote programs, then the first woodpecker that
came along would destroy civilization”
-Gerald Weinberg
$(function() { $( "#button" ).click(function() {
$( "#effect" ).addClass( "newClass", 1000, callback );
}); function callback() {
setTimeout(function() {$( "#effect" ).removeClass( "newClass" ); },
1500 ); } }); </script><script>
$(function() { $( "#button" ).click(function() {
$( "#effect" ).addClass( "newClass", 1000, callback );
}); function callback() {
setTimeout(function() {$( "#effect" ).removeClass( "newClass" ); },
1500 ); } }); </script><script>
$(function() { $( "#button" ).click(function() {
$( "#effect" ).addClass( "newClass", 1000, callback );
}); function callback() {
Evolution of a successful application
● “A successful application is going to be
used by real users”.
Evolution of a successful application
● “A successful application is going to be
used by real users”.
● “It is also likely to be augmented with more
features.”
Evolution of a successful application
● “A successful application is going to be
used by real users”.
● “It is also likely to be augmented with more
features.”
● “More features More developers
More collaboration”
Evolution of a successful application
● “A successful application is going to be
used by real users”.
● “It is also likely to be augmented with more
features.”
● “More features More developers
More collaboration”
● “Longer support”
PROGRAMMING PRACTISES WHY?
“Any fool can write code that a computer
can understand. Good programmers
write code that humans can understand”
- Martin Fowler
“Any code of your own that you haven't looked
at for six or more months might as well have
been written by someone else”.
- Eagleson's law
PROGRAMMING PRACTISES WHY?
DESIGNING PROGRAMS
WHAT IS A PROGRAM? ( And Evolution of Programming )
Programming = Instructions to control machines
WHAT IS A PROGRAM? ( And Evolution of Programming )
Programming = Logical expressions to create
machine instructions
WHAT IS A PROGRAM? ( And Evolution of Programming )
Programming = Language to express logic.
WHAT IS A PROGRAM? ( And Evolution of Programming )
Programming = Description of a system
GOOD PROGRAM
“Measuring programming progress by lines of
code is like measuring aircraft design progress
by weight”
-Bill Gates
● Aim to reduce the number of lines of code to
a point that reducing it any further makes
the code unreadable.
GOOD PROGRAM
● Aim to reduce the number of lines of
code to a point that reducing it any
further makes the code unreadable.
Programming Guidelines
Thumb rules to write CREAM code
(Clean, Robust, Efficient and Modular)
AVOID CODE REPETITION
● “Avoid duplicating logic in your code”
AVOID CODE REPETITION
● “Avoid duplicating logic in your code”
● I repeat - “Avoid duplicating logic in your
code”
● “Avoid duplicating logic in your code”
● I repeat - “Avoid duplicating logic in your
code”
AVOID CODE REPETITION
function codingGyan() {
print “Avoid duplicating logic.”;
}
codingGyan();
I repeat - codingGyan();
AVOID CODE REPETITION
if (direction == EAST) {
x = x + 10;
} else if(direction == WEST) {
x = x - 10;
} else if(direction == NORTH) {
y = y + 10;
} else if(direction == SOUTH) {
y = y - 10;
}
steps++;
strength--;
if (direction == EAST) {
x = x + 10;
steps++;
strength--;
} else if(direction == WEST) {
x = x - 10;
steps++;
strength--;
} else if(direction == NORTH) {
y = y + 10;
steps++;
strength--;
} else if(direction == SOUTH) {
y = y - 10;
steps++;
strength--;
}
GOOD PROGRAM
Aim to reduce the number of lines of code to a
point that reducing it any further makes the code
unreadable.
var a=b=c=d=e=o;
if ( expression ){Statement(s) to be executed if
expression is true }
Else{ Statement(s) to be executed if expression
is false }
var a;
if ( expression ){
statement(s) to be executed if expression is
true
}
Else{
Statement(s) to be executed if expression is
false
}
If a function/module/file starts to grow too
large, break it
SPLIT AND SOLVE
NO MAGIC NUMBERS : Code should be an art – not “black magic”.
int monthsToStock = 2;
int numberOfEmployees=26;
int notebooksPerMonth=1;
int quantity = monthsToStock *
numberOfEmployees *
notebooksPerMonth;
placeOrder(quantity);
placeOrder(52);
NO MAGIC NUMBERS
Advantages
● Better configurability
AVOID GLOBALS
Function 3
Function 1
Function 2
Function 4
● Good variables names bridge the gap
between machine language and human
language.
VARIABLE NAMING
var yellowBottle;
● Neither too short, nor too long. When in
doubt, use long.
var brightYellowMetalWaterBottle;
var b1;
var temp=[];
for(var i = 0; i < 10; i++) {
temp[i]=0;
}
function doSometing(x) {
var p=0;
var d=999999999;
for(var i = 0; i < 10; i++) {
if(d > temp[i]) {
d=temp[i];
p=i;
}
}
temp[p] += x;
}
WHAT'S IN A NAME?
WHAT'S IN A NAME?
var temp=[];
for(var i = 0; i < 10; i++) {
temp[i]=0;
}
function doSometing(x) {
var p=0;
var d=999999999;
for(var i = 0; i < 10; i++) {
if(d > temp[i]) {
d=temp[i];
p=i;
}
}
temp[p] += x;
}
var numQueues=10;
var queueBusyTill = [];
for(var nq = 0; nq < numQueues; nq++) {
queueBusyTill[nq]=0;
}
function chooseQueueForJob(jobDuration) {
var firstAvailableQueue=0;
var startTime=MAX;
for(var nq = 0; nq < numQueues; nq++) {
if(startTime > queueBusyTill[nq]) {
startTime=queueBusyTill[nq];
firstAvailableQueue=nq;
}
}
queueBusyTill[firstAvailableQueue] += jobDuration;
}
WHAT'S IN A NAME?
Bad code
temp = sqr ( b*b -4 *a *c );
root [0] = ( -b + temp ) / ( 2 * a );
root [1] = ( -b + temp ) / ( 2 * a );
...
temp = root [0];
root [0] = root [1];
root [1] = temp;
Better code
var discriminant = sqrt ( b * b - 4*a*c);
root [0] = ( -b + discriminant ) / ( 2 * a);
root [1] = ( -b - discriminant ) / ( 2 * a);
...
var oldRoot = root [0];
root [0] = root [1];
root [1] = oldRoot;
Use each variable for only one purpose !!!
CONSISTENCY
As you’re about to add a comment, ask yourself,
‘How can I improve the code so that this comment
isn’t needed?'
● Add comments when the logic cannot be
deduced at a glance or there are tricky areas
● Code with documentation: roads without signs
● Avoid redundant comments
DOCUMENTATION AND COMMENTS
function addSalary(basic , pf, medical) {
Basic = 12 * grossSalary - pf + medical;
var sum = a + b; // add two numbers
}
● There are certain things programming
languages allow you to express.
● For everything else, there are
“programming conventions”
● File and folder structures, naming
conventions, etc.
● Familiarity helps.
CONSISTENCY
Avoid long list of parameters to functions.
● Split into smaller functions
● Share the variables (data members of a
class / module)
● Group together into a data object
LONG PARAMETER LIST
function iTakeLotsOfParameters(name, surname,
gender, age, city, email, phoneNumber, interestList)
{
print “Hello”, name;
}
function doTheSameThing(personDetails) {
print “Hello ”, personDetails[‘name’’];
}
Between classes / methods / files
TOO MUCH TALKING
“First – solve the problem. Then, write the
code.”
-John Johnson
PACING SOFTWARE DEVELOPMENT
Test matches -> One Day -> 20-20
FAST PACED WORLD
“Walking on water and developing software
from a specification are easy if both are
frozen.”
EVER CHANGING
ADAPTIVE SOFTWARE DEVELOPMENT
Collaboration
● Self-organizing, cross-functional teams.
● Adaptive planning and evolutionary development
● Early delivery
● Continuous improvement
● Rapid and flexible response to change
● Plan -> Do -> Check -> Act
AGILE
DEBUGGING
“The word “Bug” is a lame attempt by software
people to blame someone else by implying that
mistakes somehow creep into the software from
outside while the developers are looking
elsewhere – as if it were not the developers who
made the mistakes in the first place.”
-Edsger W. Dijkstra
DEBUGGING
“It's hard enough to find an error in your code
when you're looking for it; it's even harder
when you've assumed your code is error-free.”
-Steve McConnell.
DEBUGGING
“When debugging, novices insert corrective
code; experts remove defective code.”
-Steve McConnell
DEBUGGING
“Computers are good at following instructions,
but not at reading your mind.”
-Donald Kruth
DEBUGGING
● Better to test incompletely than to
completely skip testing
● Think at the boundaries of the box
TESTING
To restructure software by applying a series of changes without
changing its (observable) behaviour
REFACTORING
● To restructure software by applying a
series of changes without changing its
(observable) behaviour
● Incremental, in short packets
REFACTORING
● To restructure software by applying a
series of changes without changing its
(observable) behaviour
● Incremental, in short packets
● Separate code clean-up, optimizations
and fixes
REFACTORING
THANK YOU

Guidelines to clean coding

  • 1.
  • 2.
  • 3.
    “Most software todayis very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves.” -Alan Kay SOFTWARE DEVELOPMENT
  • 4.
    PROGRAMMING PRACTISES “If buildersbuilt buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization” -Gerald Weinberg $(function() { $( "#button" ).click(function() { $( "#effect" ).addClass( "newClass", 1000, callback ); }); function callback() { setTimeout(function() {$( "#effect" ).removeClass( "newClass" ); }, 1500 ); } }); </script><script> $(function() { $( "#button" ).click(function() { $( "#effect" ).addClass( "newClass", 1000, callback ); }); function callback() { setTimeout(function() {$( "#effect" ).removeClass( "newClass" ); }, 1500 ); } }); </script><script> $(function() { $( "#button" ).click(function() { $( "#effect" ).addClass( "newClass", 1000, callback ); }); function callback() {
  • 5.
    Evolution of asuccessful application ● “A successful application is going to be used by real users”.
  • 6.
    Evolution of asuccessful application ● “A successful application is going to be used by real users”. ● “It is also likely to be augmented with more features.”
  • 7.
    Evolution of asuccessful application ● “A successful application is going to be used by real users”. ● “It is also likely to be augmented with more features.” ● “More features More developers More collaboration”
  • 8.
    Evolution of asuccessful application ● “A successful application is going to be used by real users”. ● “It is also likely to be augmented with more features.” ● “More features More developers More collaboration” ● “Longer support”
  • 9.
    PROGRAMMING PRACTISES WHY? “Anyfool can write code that a computer can understand. Good programmers write code that humans can understand” - Martin Fowler
  • 10.
    “Any code ofyour own that you haven't looked at for six or more months might as well have been written by someone else”. - Eagleson's law PROGRAMMING PRACTISES WHY?
  • 11.
  • 12.
    WHAT IS APROGRAM? ( And Evolution of Programming ) Programming = Instructions to control machines
  • 13.
    WHAT IS APROGRAM? ( And Evolution of Programming ) Programming = Logical expressions to create machine instructions
  • 14.
    WHAT IS APROGRAM? ( And Evolution of Programming ) Programming = Language to express logic.
  • 15.
    WHAT IS APROGRAM? ( And Evolution of Programming ) Programming = Description of a system
  • 16.
    GOOD PROGRAM “Measuring programmingprogress by lines of code is like measuring aircraft design progress by weight” -Bill Gates ● Aim to reduce the number of lines of code to a point that reducing it any further makes the code unreadable.
  • 17.
    GOOD PROGRAM ● Aimto reduce the number of lines of code to a point that reducing it any further makes the code unreadable.
  • 18.
    Programming Guidelines Thumb rulesto write CREAM code (Clean, Robust, Efficient and Modular)
  • 19.
    AVOID CODE REPETITION ●“Avoid duplicating logic in your code”
  • 20.
    AVOID CODE REPETITION ●“Avoid duplicating logic in your code” ● I repeat - “Avoid duplicating logic in your code”
  • 21.
    ● “Avoid duplicatinglogic in your code” ● I repeat - “Avoid duplicating logic in your code” AVOID CODE REPETITION function codingGyan() { print “Avoid duplicating logic.”; } codingGyan(); I repeat - codingGyan();
  • 22.
    AVOID CODE REPETITION if(direction == EAST) { x = x + 10; } else if(direction == WEST) { x = x - 10; } else if(direction == NORTH) { y = y + 10; } else if(direction == SOUTH) { y = y - 10; } steps++; strength--; if (direction == EAST) { x = x + 10; steps++; strength--; } else if(direction == WEST) { x = x - 10; steps++; strength--; } else if(direction == NORTH) { y = y + 10; steps++; strength--; } else if(direction == SOUTH) { y = y - 10; steps++; strength--; }
  • 23.
    GOOD PROGRAM Aim toreduce the number of lines of code to a point that reducing it any further makes the code unreadable. var a=b=c=d=e=o; if ( expression ){Statement(s) to be executed if expression is true } Else{ Statement(s) to be executed if expression is false } var a; if ( expression ){ statement(s) to be executed if expression is true } Else{ Statement(s) to be executed if expression is false }
  • 24.
    If a function/module/filestarts to grow too large, break it SPLIT AND SOLVE
  • 25.
    NO MAGIC NUMBERS: Code should be an art – not “black magic”. int monthsToStock = 2; int numberOfEmployees=26; int notebooksPerMonth=1; int quantity = monthsToStock * numberOfEmployees * notebooksPerMonth; placeOrder(quantity); placeOrder(52);
  • 26.
    NO MAGIC NUMBERS Advantages ●Better configurability
  • 27.
    AVOID GLOBALS Function 3 Function1 Function 2 Function 4
  • 28.
    ● Good variablesnames bridge the gap between machine language and human language. VARIABLE NAMING var yellowBottle; ● Neither too short, nor too long. When in doubt, use long. var brightYellowMetalWaterBottle; var b1;
  • 29.
    var temp=[]; for(var i= 0; i < 10; i++) { temp[i]=0; } function doSometing(x) { var p=0; var d=999999999; for(var i = 0; i < 10; i++) { if(d > temp[i]) { d=temp[i]; p=i; } } temp[p] += x; } WHAT'S IN A NAME?
  • 30.
    WHAT'S IN ANAME? var temp=[]; for(var i = 0; i < 10; i++) { temp[i]=0; } function doSometing(x) { var p=0; var d=999999999; for(var i = 0; i < 10; i++) { if(d > temp[i]) { d=temp[i]; p=i; } } temp[p] += x; } var numQueues=10; var queueBusyTill = []; for(var nq = 0; nq < numQueues; nq++) { queueBusyTill[nq]=0; } function chooseQueueForJob(jobDuration) { var firstAvailableQueue=0; var startTime=MAX; for(var nq = 0; nq < numQueues; nq++) { if(startTime > queueBusyTill[nq]) { startTime=queueBusyTill[nq]; firstAvailableQueue=nq; } } queueBusyTill[firstAvailableQueue] += jobDuration; }
  • 31.
    WHAT'S IN ANAME? Bad code temp = sqr ( b*b -4 *a *c ); root [0] = ( -b + temp ) / ( 2 * a ); root [1] = ( -b + temp ) / ( 2 * a ); ... temp = root [0]; root [0] = root [1]; root [1] = temp; Better code var discriminant = sqrt ( b * b - 4*a*c); root [0] = ( -b + discriminant ) / ( 2 * a); root [1] = ( -b - discriminant ) / ( 2 * a); ... var oldRoot = root [0]; root [0] = root [1]; root [1] = oldRoot; Use each variable for only one purpose !!!
  • 32.
  • 33.
    As you’re aboutto add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?' ● Add comments when the logic cannot be deduced at a glance or there are tricky areas ● Code with documentation: roads without signs ● Avoid redundant comments DOCUMENTATION AND COMMENTS function addSalary(basic , pf, medical) { Basic = 12 * grossSalary - pf + medical; var sum = a + b; // add two numbers }
  • 34.
    ● There arecertain things programming languages allow you to express. ● For everything else, there are “programming conventions” ● File and folder structures, naming conventions, etc. ● Familiarity helps. CONSISTENCY
  • 35.
    Avoid long listof parameters to functions. ● Split into smaller functions ● Share the variables (data members of a class / module) ● Group together into a data object LONG PARAMETER LIST function iTakeLotsOfParameters(name, surname, gender, age, city, email, phoneNumber, interestList) { print “Hello”, name; } function doTheSameThing(personDetails) { print “Hello ”, personDetails[‘name’’]; }
  • 36.
    Between classes /methods / files TOO MUCH TALKING
  • 37.
    “First – solvethe problem. Then, write the code.” -John Johnson PACING SOFTWARE DEVELOPMENT
  • 38.
    Test matches ->One Day -> 20-20 FAST PACED WORLD
  • 39.
    “Walking on waterand developing software from a specification are easy if both are frozen.” EVER CHANGING
  • 40.
  • 41.
    Collaboration ● Self-organizing, cross-functionalteams. ● Adaptive planning and evolutionary development ● Early delivery ● Continuous improvement ● Rapid and flexible response to change ● Plan -> Do -> Check -> Act AGILE
  • 42.
  • 43.
    “The word “Bug”is a lame attempt by software people to blame someone else by implying that mistakes somehow creep into the software from outside while the developers are looking elsewhere – as if it were not the developers who made the mistakes in the first place.” -Edsger W. Dijkstra DEBUGGING
  • 44.
    “It's hard enoughto find an error in your code when you're looking for it; it's even harder when you've assumed your code is error-free.” -Steve McConnell. DEBUGGING
  • 45.
    “When debugging, novicesinsert corrective code; experts remove defective code.” -Steve McConnell DEBUGGING
  • 46.
    “Computers are goodat following instructions, but not at reading your mind.” -Donald Kruth DEBUGGING
  • 47.
    ● Better totest incompletely than to completely skip testing ● Think at the boundaries of the box TESTING
  • 48.
    To restructure softwareby applying a series of changes without changing its (observable) behaviour REFACTORING
  • 49.
    ● To restructuresoftware by applying a series of changes without changing its (observable) behaviour ● Incremental, in short packets REFACTORING
  • 50.
    ● To restructuresoftware by applying a series of changes without changing its (observable) behaviour ● Incremental, in short packets ● Separate code clean-up, optimizations and fixes REFACTORING
  • 51.