SlideShare a Scribd company logo
1 of 43
Download to read offline
Writing Beautiful Code
Vimal Joseph
Technical Architect
Aesthetics of code and its relevance
ZyxTech
How do you define beauty?
Image Courtesy: Indian People Collage by Jamie Furlong
ZyxTech
How do you define beauty?
Guernica by Picasso
ZyxTech
How do you define beauty?
Starry Night by VanGogh
ZyxTech
How do you define beauty?
Water lilies, Nymphaea nouchali, Okavango Delta, Botswana
ZyxTech
How do you define beauty?
Each of us will have a different opinion on what is beautiful
Beauty is relative
Beauty is a perception
Beauty is structure
Beauty is consistency
Beauty is some thing that please our senses
You may have some thing else to say...
Is it possible to measure beauty?
Can you identify anything common for beautiful things?
ZyxTech
How do you define beauty?
BMW M5
ZyxTech
How do you define beauty?
BMW M5
ZyxTech
How do you define beauty?
Microprocessor
ZyxTech
How do you define beauty?
/* match: search for regexp anywhere in text */
int match(char *regexp, char *text) {
if (regexp[0] == '^')
return matchhere(regexp+1, text);
do { /* must look even if string is empty */
if (matchhere(regexp, text))
return 1;
} while (*text++ != '0');
return 0;
}
/* matchhere: search for regexp at beginning of text */
int matchhere(char *regexp, char *text) {
if (regexp[0] == '0')
return 1;
if (regexp[1] == '*')
return matchstar(regexp[0], regexp+2, text);
if (regexp[0] == '$' && regexp[1] == '0')
return *text == '0';
if (*text!='0' && (regexp[0]=='.' || regexp[0]==*text))
return matchhere(regexp+1, text+1);
return 0;
}
/* matchstar: search for c*regexp at beginning of text */
int matchstar(int c, char *regexp, char *text) {
do { /* a * matches zero or more instances */
if (matchhere(regexp, text))
return 1;
} while (*text != '0' && (*text++ == c || c == '.'));
return 0;
}
http://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
ZyxTech
Beauty
I have a friend who's an artist and has sometimes taken a view which I don't agree
with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree.
Then he says "I as an artist can see how beautiful this is but you as a scientist take this
all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all,
the beauty that he sees is available to other people and to me too, I believe. Although
I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a
flower.
ZyxTech
Beauty (contd...)
At the same time, I see much more about the flower than he sees. I could imagine the
cells in there, the complicated actions inside, which also have a beauty. I mean it's not
just beauty at this dimension, at one centimeter; there's also beauty at smaller
dimensions, the inner structure, also the processes. The fact that the colors in the
flower evolved in order to attract insects to pollinate it is interesting; it means that
insects can see the color. It adds a question: does this aesthetic sense also exist in the
lower forms? Why is it aesthetic? All kinds of interesting questions which the science
knowledge only adds to the excitement, the mystery and the awe of a flower. It only
adds. I don't understand how it subtracts.
– Richard P. Feynman
ZyxTech
Appreciating beauty...
Context
Familiarity
Curiosity
Quest for Knowledge
Compassion
Ever thought about the audience of your code?
Code is also written for humans to read, not only for computers to execute.
– Erkki Lindpere
ZyxTech
Rules that make things beautiful
Proportions
Integrity
Clarity
Standards
ZyxTech
The Zen of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
ZyxTech
The Zen of Python (contd...)
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
by Tim Peters
Example: http://bit.ly/dQzuxW
ZyxTech
What they said about beautiful
code?
Beautiful code is likely to be simple -- clear and easy to understand. Beautiful code is
likely to be compact -- just enough code to do the job and no more -- but not cryptic,
to the point where it cannot be understood. Beautiful code may well be general,
solving a broad class of problems in a uniform way. One might even describe it as
elegant, showing good taste and refinement.
- Brian Kernighan
ZyxTech
What they said about beautiful
code? (contd...)
I like my code to be elegant and efficient. The logic should be straightforward to make
it hard for bugs to hide, the dependencies minimal to ease maintenance, error
handling complete according to an articulated strategy, and performance close to
optimal so as not to tempt people to make the code messy with unprincipled
optimizations. Clean code does one thing well.
- Bjarne Stroustrup, inventor of C++
ZyxTech
Clean the code
Always leave the campground cleaner than you found it.
- The Boy Scout Rule
Developers often get anxious to move on to the next feature and forget to clean
up the trash that they have left lying around: forgetting to clean
Duplicated code
Poorly named functions and variables
Huge functions
Magic numbers
Inappropriate combinations of differing levels of abstraction
Tight coupling
and the list goes on...
ZyxTech
Things to be taken care of...
Names
Expressions and Statements
Consistency and Idioms
Magic numbers
Comments
ZyxTech
Bad Code, Good Code
if (($country == SING) || ($country == BRNI) ||
 ($country == POL) || ($country == ITALY)) {
 // If the country is Singapore, Brunei or Poland then the current 
  // time is the answer time rather than the off hook time.
 // Reset answer time and set day of week.
 ...
What relationship links Singapore, Brunei, Poland and Italy? Why 
isn't Italy mention in the comment?
ZyxTech
Bad Code, Good Code - Names
define(“ONE”, 1);
define(“TEN”, 10);
define(“TWENTY”, 20);
define(“INPUT_MODE”, 1);
define(“INPUT_BUFSIZE”, 10);
define(“OUTPUT_BUFSIZE”, 20);
ZyxTech
Bad Code, Good Code - Names
for ($the_element_index = 0; $the_element_index < 
$number_of_elements;
  the_element_index++) {
  $element_array[$the_element_index] = $the_element_index;
}
for ($i = 0, $i < $nelems; $i++) {
  elem[$i] = $i;
}
ZyxTech
Bad Code, Good Code - Names
class UserQueue {
 public $no_of_elements_in_q = 10;
 public $front_of_the_queue = 0;
 public $queue_capacity = 20;
 public function no_of_users_in_queue() {
    ...
 }
}
queue = new UserQueue;
queue­>queue_capacity
$queue = new UserQueue;
$queue­>capacity++;
$n = $queue­>nusers();
class UserQueue {
 public $nitems = 10;
 public $front = 0;
 public $capacity = 20;
 public function nusers() {
    ...
 }
}
ZyxTech
Bad Code, Good Code - Names
if (checkprime($n)) {
  …
}
if (isprime($n)) {
  …
}
ZyxTech
Bad Code, Good Code - Names
function intable($obj) {
  $j = $this­>get_index($obj);//return a value between 0 and 
  //ntable – 1 if it find the string, and returns ntable if not.
  return ($j == $ntable);
}
­­
function smaller($s, $t) {
  if (strcmp($s, $t) < 1) {
    return 1;
  }
  else {
    return 0;
  }
}
ZyxTech
Bad Code, Good Code - Expressions
if (!($block_id < $actblks) || !($block_id >= $unblocks)) {
  …
}
if (block_id >= actblks) || block_id < unblocks)) {
  …
}
ZyxTech
Bad Code, Good Code - Expressions
$leap_yr = $y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0;
$leap_yr = (($y % 4 == 0) && ($y % 100 != 0)) || ($y % 400 == 0);
ZyxTech
Bad Code, Good Code - Expressions
$x += ($xp = (2 * $k < ($n ­ $m) ? $c[$k + 1] : $d[$k ­ 1]));
if (2 * $k < ($n ­ $m)) {
  $xp = $c[$k + 1];
}
else {
  $xp = $d[$k ­ 1];
}
$x += $xp;
ZyxTech
Bad Code, Good Code - Expressions
$length = ($length < BUFSIZE) ? $length : BUFSIZE;
if ($length > BUFSIZE) {
  $length = BUFSIZE;
}
ZyxTech
Bad Code, Good Code - Expressions
if ($month == FEB) {
  if ($year % 4 == 0)
    if ($day > 29)
      $legal = FALSE;
  else
    if ($day > 28)
      $legal = FALSE;
}
if ($month == FEB) {
  $nday = 28;
  if ((($year % 4 == 0) && ($year % 100 != 0)) 
    || $year % 400 == 0) {
    $nday = 29;
  }
  if ($day > $nday) {
    $legal = FALSE;
  }
}
ZyxTech
Bad Code, Good Code - Idioms
$i = 0;
while ($i <= $n­1)
  $array[$i++] = 1.0;
–
for ($i = 0; $i < $n;)
  $array[$i++] = 1.0;
–
for ($i = n; $i = $i ­ 1 >=0;)
  $array[$i] = 1.0;
–
for ($i = 0; i < n; i++)
  $array[$i] = 1.0;
ZyxTech
Bad Code, Good Code - Idioms
if (isset($f1) && isset($f2))
  if (($fin = $fopen($f1, 'r')) != NULL)
    if (($fout = fopen($f2, 'w')) != NULL) {
      while (($c = getc(fin)) !== false)
         fputs($c, $fout);
       fclose($fin);
       fclose($fout);
    }
    else
      printf("Can't open output file %sn", f2);
 else
   printf("Can't open input file %sn", f1);
else
  printf("Incorrect arguments");
ZyxTech
Bad Code, Good Code - Idioms
if (!isset($f1) || !isset($f2))
  print 'Incorrect arguments';
else if (($fin = $fopen($f1, 'r')) == NULL)
  printf("Can't open input file %sn", f1);
else if (($fout = fopen($f2, 'w')) == NULL) {
  printf("Can't open output file %sn", f2);  
  fclose($fin);
}
else {
  while (($c = fgetc($fin) !== false) {
    fputs($c, $fout);
  }
  fclose($fin);
  fclose($fout);
}
ZyxTech
Bad Code, Good Code – Magic
Numbers
/**
 * Print a histogram of letter frequencies on a
 * 24 lines by 80 columns screen
 */
$fac = $lim / 20; //set scale factor
if ($fac < 1)
  $fac = 1;
//generate histogram
for ($i = 0, $col = 0; $i < 27; $i++) {
  $col += 3;
  $k = 21 ­ ($let[$i] / $fac);
  $star = ($let[$i] == 0) ? ' ' : "*";
  for ($j = $k; $j < 22; $j++)
    draw($j, $col, $star);
}
draw(23, 2, ' '); //Label x axis
for ($i = 'A'; $i <= 'Z'; $i++)
  printf("%c ", $i);
ZyxTech
Bad Code, Good Code – Magic
Numbers
define(“MINROW”, 1);                   // Top edge
define(“MINCOL”, 1);                   // Left edge
define(“MAXROW”, 24);                  // Bottom edge (<=)
define(“MAXCOL”, 80);                  // Right edge (<=)
define(“LABELROW”, 1);                 // Position of labels
define(“NLET”, 26);                    // Size of alphabet
define(“HEIGHT”, MAXROW – 4);          // Height of bars
define(“WIDTH”, (MAXCOL ­ 1) / NLET)   // Width of bars
...
ZyxTech
Bad Code, Good Code – Magic
Numbers (contd...)
...
$fac = ($lim + HEIGHT ­ 1) / HEIGHT; // Set scale factor
if ($fac < 1)
  $fac = 1;
//generate histogram
for ($i = 0; $i < NLET; $i++) {
  if ($let[$i] == 0)
    continue;
  for ($j = HEIGHT ­ $let[$i] / $fac; $j < HEIGHT; $j++)
    draw($j + 1 + LABELROW, ($i + 1) * WIDTH, '*');
}
draw(MAXROW ­ 1, MINCOL + 1, ' '); //Label x axis
for ($i = 'A'; $i <= 'Z'; $i++)
  printf("%c ", $i);
ZyxTech
Bad Code, Good Code - Comments
// default
default:
  break;
// return SUCCESS
return SUCCESS;
$zerocount++; //increment zero entry counter
$node­>total = $node­>number_received; // Initialize total to 
number_received
ZyxTech
Bad Code, Good Code - Comments
// string comparison routine returns ­1 if s1 is
// above s2 in an ascending order list, 0 if equal
// 1 if s1 below s2
function strcmp(s1, s2) {
  …
}
// strcmp: return < 0 if sl < s2, > 0 if s1 > s2, 0 if equal
function strcmp(s1, s2) {
  …
}
if (n > MAX || n % 2 > 0) // test for even number
The comment is incomplete; the code actually tests for a even 
number or a number that is greater than MAX.
ZyxTech
Some food for thought...
Quality is not an act, it is a habit
First, solve the problem. Then, write the code.
— John Johnson
Incorrect documentation is often worse than no documentation.
— Bertrand Meyer
Controlling complexity is the essence of computer programming.
— Brian Kernighan
One of my most productive days was throwing away 1000 lines of code.
— Ken Thompson
There are two ways of constructing a software design: One way is to make it so simple
that there are obviously no deficiencies and the other way is to make it so complicated
that there are no obvious deficiencies.
— C.A.R. Hoare, The 1980 ACM Turing Award Lecture
ZyxTech
References
The Practice of Programming - Brian Kernighan, Rob Pike
Code Complete 2ed. - Steve McConnell
A Regular Expression Matcher - http://bit.ly/1hAUGzh by Brian Kernighan
Clean Code - Robert C Martin
ZyxTech
Contact Us
Visit us at http://www.zyxware.com/contact
Email us at info@zyxware.com
Connect with us at http://www.linkedin.com/company/zyxware-technologies
Like us at https://www.facebook.com/zyxware
Follow us at https://twitter.com/zyxware
ZyxTech
Thank You...

More Related Content

Similar to Code quality - aesthetics & functionality of writing beautiful code

Back to basics simple, elegant, beautiful code
Back to basics   simple, elegant, beautiful codeBack to basics   simple, elegant, beautiful code
Back to basics simple, elegant, beautiful codeAndrew Harcourt
 
Pin On Reluctant Homeschool Writers
Pin On Reluctant Homeschool WritersPin On Reluctant Homeschool Writers
Pin On Reluctant Homeschool WritersTonia Wallace
 
Code Quality Makes Your Job Easier
Code Quality Makes Your Job EasierCode Quality Makes Your Job Easier
Code Quality Makes Your Job EasierTonya Mork
 
Scaling Saved Searches at eBay Kleinanzeigen
Scaling Saved Searches at eBay KleinanzeigenScaling Saved Searches at eBay Kleinanzeigen
Scaling Saved Searches at eBay KleinanzeigenAndre Charton
 
The prestige of being a web developer
The prestige of being a web developerThe prestige of being a web developer
The prestige of being a web developerChristian Heilmann
 
The tao of programming
The tao of programmingThe tao of programming
The tao of programmingOlabode James
 
Deep Learning Class #0 - You Can Do It
Deep Learning Class #0 - You Can Do ItDeep Learning Class #0 - You Can Do It
Deep Learning Class #0 - You Can Do ItHolberton School
 
DL Classe 0 - You can do it
DL Classe 0 - You can do itDL Classe 0 - You can do it
DL Classe 0 - You can do itGregory Renard
 
Paco Viñoly, Designing in a Developer World, WarmGun 2013
Paco Viñoly, Designing in a Developer World, WarmGun 2013Paco Viñoly, Designing in a Developer World, WarmGun 2013
Paco Viñoly, Designing in a Developer World, WarmGun 2013500 Startups
 
Good vs. Great Design
Good vs. Great DesignGood vs. Great Design
Good vs. Great DesignCameron Moll
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering Inocentshuja Ahmad
 
Applied Computer Vision - a Deep Learning Approach
Applied Computer Vision - a Deep Learning ApproachApplied Computer Vision - a Deep Learning Approach
Applied Computer Vision - a Deep Learning ApproachJose Berengueres
 
Enterprise Architecture - A Matter of Perspective
Enterprise Architecture - A Matter of PerspectiveEnterprise Architecture - A Matter of Perspective
Enterprise Architecture - A Matter of PerspectiveTetradian Consulting
 
Same and different - architectures for mass-uniqueness
Same and different - architectures for mass-uniquenessSame and different - architectures for mass-uniqueness
Same and different - architectures for mass-uniquenessTetradian Consulting
 
Patterns for organic architecture codedive
Patterns for organic architecture codedivePatterns for organic architecture codedive
Patterns for organic architecture codedivemagda3695
 

Similar to Code quality - aesthetics & functionality of writing beautiful code (20)

Map your Mind, Your mind on a paper
Map your Mind, Your mind on a paperMap your Mind, Your mind on a paper
Map your Mind, Your mind on a paper
 
Back to basics simple, elegant, beautiful code
Back to basics   simple, elegant, beautiful codeBack to basics   simple, elegant, beautiful code
Back to basics simple, elegant, beautiful code
 
Pin On Reluctant Homeschool Writers
Pin On Reluctant Homeschool WritersPin On Reluctant Homeschool Writers
Pin On Reluctant Homeschool Writers
 
Code Quality Makes Your Job Easier
Code Quality Makes Your Job EasierCode Quality Makes Your Job Easier
Code Quality Makes Your Job Easier
 
Scaling Saved Searches at eBay Kleinanzeigen
Scaling Saved Searches at eBay KleinanzeigenScaling Saved Searches at eBay Kleinanzeigen
Scaling Saved Searches at eBay Kleinanzeigen
 
The prestige of being a web developer
The prestige of being a web developerThe prestige of being a web developer
The prestige of being a web developer
 
The tao of programming
The tao of programmingThe tao of programming
The tao of programming
 
Deep Learning Class #0 - You Can Do It
Deep Learning Class #0 - You Can Do ItDeep Learning Class #0 - You Can Do It
Deep Learning Class #0 - You Can Do It
 
DL Classe 0 - You can do it
DL Classe 0 - You can do itDL Classe 0 - You can do it
DL Classe 0 - You can do it
 
Paco Viñoly, Designing in a Developer World, WarmGun 2013
Paco Viñoly, Designing in a Developer World, WarmGun 2013Paco Viñoly, Designing in a Developer World, WarmGun 2013
Paco Viñoly, Designing in a Developer World, WarmGun 2013
 
Good vs. Great Design
Good vs. Great DesignGood vs. Great Design
Good vs. Great Design
 
Autoecoders.pptx
Autoecoders.pptxAutoecoders.pptx
Autoecoders.pptx
 
C programming guide new
C programming guide newC programming guide new
C programming guide new
 
Code Beauty
Code BeautyCode Beauty
Code Beauty
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering
 
Applied Computer Vision - a Deep Learning Approach
Applied Computer Vision - a Deep Learning ApproachApplied Computer Vision - a Deep Learning Approach
Applied Computer Vision - a Deep Learning Approach
 
Enterprise Architecture - A Matter of Perspective
Enterprise Architecture - A Matter of PerspectiveEnterprise Architecture - A Matter of Perspective
Enterprise Architecture - A Matter of Perspective
 
Same and different - architectures for mass-uniqueness
Same and different - architectures for mass-uniquenessSame and different - architectures for mass-uniqueness
Same and different - architectures for mass-uniqueness
 
Lunch & learn code monkey
Lunch & learn code monkeyLunch & learn code monkey
Lunch & learn code monkey
 
Patterns for organic architecture codedive
Patterns for organic architecture codedivePatterns for organic architecture codedive
Patterns for organic architecture codedive
 

More from Zyxware Technologies

Google Docs - Leverage the power of collaboration with shared documents
Google Docs - Leverage the power of collaboration with shared documentsGoogle Docs - Leverage the power of collaboration with shared documents
Google Docs - Leverage the power of collaboration with shared documentsZyxware Technologies
 
CETAA Vision 2025 - Making CETAA the best alumni association in India
CETAA Vision 2025 - Making CETAA the best alumni association in IndiaCETAA Vision 2025 - Making CETAA the best alumni association in India
CETAA Vision 2025 - Making CETAA the best alumni association in IndiaZyxware Technologies
 
Come, build your career at Zyxware Technologies
Come, build your career at Zyxware TechnologiesCome, build your career at Zyxware Technologies
Come, build your career at Zyxware TechnologiesZyxware Technologies
 
Personalized customer experience using ecommerce portal
Personalized customer experience using ecommerce portalPersonalized customer experience using ecommerce portal
Personalized customer experience using ecommerce portalZyxware Technologies
 
Web Application Performance Audit and Optimization
Web Application Performance Audit and OptimizationWeb Application Performance Audit and Optimization
Web Application Performance Audit and OptimizationZyxware Technologies
 
Setting in place a product development strategy
Setting in place a product development strategySetting in place a product development strategy
Setting in place a product development strategyZyxware Technologies
 
Debugging Drupal - How to Debug your Drupal Application
Debugging Drupal - How to Debug your Drupal ApplicationDebugging Drupal - How to Debug your Drupal Application
Debugging Drupal - How to Debug your Drupal ApplicationZyxware Technologies
 
Drupal Performance Audit and Optimization
Drupal Performance Audit and OptimizationDrupal Performance Audit and Optimization
Drupal Performance Audit and OptimizationZyxware Technologies
 
Drupal as a Rapid Application Development Framework for Non Profits / NGOs
Drupal as a Rapid Application Development Framework for Non Profits / NGOsDrupal as a Rapid Application Development Framework for Non Profits / NGOs
Drupal as a Rapid Application Development Framework for Non Profits / NGOsZyxware Technologies
 
An introduction to cyber forensics and open source tools in cyber forensics
An introduction to cyber forensics and open source tools in cyber forensicsAn introduction to cyber forensics and open source tools in cyber forensics
An introduction to cyber forensics and open source tools in cyber forensicsZyxware Technologies
 
Exploring Wider Collaboration Mechanisms in the Drupal Space
Exploring Wider Collaboration Mechanisms in the Drupal SpaceExploring Wider Collaboration Mechanisms in the Drupal Space
Exploring Wider Collaboration Mechanisms in the Drupal SpaceZyxware Technologies
 
The art of communication - managing digital communication
The art of communication - managing digital communicationThe art of communication - managing digital communication
The art of communication - managing digital communicationZyxware Technologies
 
Drupal ecosystem in India and Drupal's market potential in India
Drupal ecosystem in India and Drupal's market potential in IndiaDrupal ecosystem in India and Drupal's market potential in India
Drupal ecosystem in India and Drupal's market potential in IndiaZyxware Technologies
 
Drupal as a Rapid Application Development (RAD) Framework for Startups
Drupal as a Rapid Application Development (RAD) Framework for StartupsDrupal as a Rapid Application Development (RAD) Framework for Startups
Drupal as a Rapid Application Development (RAD) Framework for StartupsZyxware Technologies
 
Collaborative development using git, Session conducted at Model Engineering C...
Collaborative development using git, Session conducted at Model Engineering C...Collaborative development using git, Session conducted at Model Engineering C...
Collaborative development using git, Session conducted at Model Engineering C...Zyxware Technologies
 
Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26
Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26
Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26Zyxware Technologies
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Zyxware Technologies
 
ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...
ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...
ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...Zyxware Technologies
 

More from Zyxware Technologies (20)

Google Docs - Leverage the power of collaboration with shared documents
Google Docs - Leverage the power of collaboration with shared documentsGoogle Docs - Leverage the power of collaboration with shared documents
Google Docs - Leverage the power of collaboration with shared documents
 
CETAA Vision 2025 - Making CETAA the best alumni association in India
CETAA Vision 2025 - Making CETAA the best alumni association in IndiaCETAA Vision 2025 - Making CETAA the best alumni association in India
CETAA Vision 2025 - Making CETAA the best alumni association in India
 
Learn Drupal 8 Render Pipeline
Learn Drupal 8 Render PipelineLearn Drupal 8 Render Pipeline
Learn Drupal 8 Render Pipeline
 
Come, build your career at Zyxware Technologies
Come, build your career at Zyxware TechnologiesCome, build your career at Zyxware Technologies
Come, build your career at Zyxware Technologies
 
Personalized customer experience using ecommerce portal
Personalized customer experience using ecommerce portalPersonalized customer experience using ecommerce portal
Personalized customer experience using ecommerce portal
 
Web Application Performance Audit and Optimization
Web Application Performance Audit and OptimizationWeb Application Performance Audit and Optimization
Web Application Performance Audit and Optimization
 
Drupal is taking over Australia
Drupal is taking over AustraliaDrupal is taking over Australia
Drupal is taking over Australia
 
Setting in place a product development strategy
Setting in place a product development strategySetting in place a product development strategy
Setting in place a product development strategy
 
Debugging Drupal - How to Debug your Drupal Application
Debugging Drupal - How to Debug your Drupal ApplicationDebugging Drupal - How to Debug your Drupal Application
Debugging Drupal - How to Debug your Drupal Application
 
Drupal Performance Audit and Optimization
Drupal Performance Audit and OptimizationDrupal Performance Audit and Optimization
Drupal Performance Audit and Optimization
 
Drupal as a Rapid Application Development Framework for Non Profits / NGOs
Drupal as a Rapid Application Development Framework for Non Profits / NGOsDrupal as a Rapid Application Development Framework for Non Profits / NGOs
Drupal as a Rapid Application Development Framework for Non Profits / NGOs
 
An introduction to cyber forensics and open source tools in cyber forensics
An introduction to cyber forensics and open source tools in cyber forensicsAn introduction to cyber forensics and open source tools in cyber forensics
An introduction to cyber forensics and open source tools in cyber forensics
 
Exploring Wider Collaboration Mechanisms in the Drupal Space
Exploring Wider Collaboration Mechanisms in the Drupal SpaceExploring Wider Collaboration Mechanisms in the Drupal Space
Exploring Wider Collaboration Mechanisms in the Drupal Space
 
The art of communication - managing digital communication
The art of communication - managing digital communicationThe art of communication - managing digital communication
The art of communication - managing digital communication
 
Drupal ecosystem in India and Drupal's market potential in India
Drupal ecosystem in India and Drupal's market potential in IndiaDrupal ecosystem in India and Drupal's market potential in India
Drupal ecosystem in India and Drupal's market potential in India
 
Drupal as a Rapid Application Development (RAD) Framework for Startups
Drupal as a Rapid Application Development (RAD) Framework for StartupsDrupal as a Rapid Application Development (RAD) Framework for Startups
Drupal as a Rapid Application Development (RAD) Framework for Startups
 
Collaborative development using git, Session conducted at Model Engineering C...
Collaborative development using git, Session conducted at Model Engineering C...Collaborative development using git, Session conducted at Model Engineering C...
Collaborative development using git, Session conducted at Model Engineering C...
 
Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26
Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26
Introduction to Drupal, Training conducted at MES-AIMAT, Aluva on 2013-09-26
 
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
 
ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...
ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...
ICFOSS Interaction with Small and Medium Enterprises on IT Enabling SMEs with...
 

Recently uploaded

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Code quality - aesthetics & functionality of writing beautiful code

  • 1. Writing Beautiful Code Vimal Joseph Technical Architect Aesthetics of code and its relevance
  • 2. ZyxTech How do you define beauty? Image Courtesy: Indian People Collage by Jamie Furlong
  • 3. ZyxTech How do you define beauty? Guernica by Picasso
  • 4. ZyxTech How do you define beauty? Starry Night by VanGogh
  • 5. ZyxTech How do you define beauty? Water lilies, Nymphaea nouchali, Okavango Delta, Botswana
  • 6. ZyxTech How do you define beauty? Each of us will have a different opinion on what is beautiful Beauty is relative Beauty is a perception Beauty is structure Beauty is consistency Beauty is some thing that please our senses You may have some thing else to say... Is it possible to measure beauty? Can you identify anything common for beautiful things?
  • 7. ZyxTech How do you define beauty? BMW M5
  • 8. ZyxTech How do you define beauty? BMW M5
  • 9. ZyxTech How do you define beauty? Microprocessor
  • 10. ZyxTech How do you define beauty? /* match: search for regexp anywhere in text */ int match(char *regexp, char *text) { if (regexp[0] == '^') return matchhere(regexp+1, text); do { /* must look even if string is empty */ if (matchhere(regexp, text)) return 1; } while (*text++ != '0'); return 0; } /* matchhere: search for regexp at beginning of text */ int matchhere(char *regexp, char *text) { if (regexp[0] == '0') return 1; if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text); if (regexp[0] == '$' && regexp[1] == '0') return *text == '0'; if (*text!='0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1); return 0; } /* matchstar: search for c*regexp at beginning of text */ int matchstar(int c, char *regexp, char *text) { do { /* a * matches zero or more instances */ if (matchhere(regexp, text)) return 1; } while (*text != '0' && (*text++ == c || c == '.')); return 0; } http://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
  • 11. ZyxTech Beauty I have a friend who's an artist and has sometimes taken a view which I don't agree with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree. Then he says "I as an artist can see how beautiful this is but you as a scientist take this all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all, the beauty that he sees is available to other people and to me too, I believe. Although I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a flower.
  • 12. ZyxTech Beauty (contd...) At the same time, I see much more about the flower than he sees. I could imagine the cells in there, the complicated actions inside, which also have a beauty. I mean it's not just beauty at this dimension, at one centimeter; there's also beauty at smaller dimensions, the inner structure, also the processes. The fact that the colors in the flower evolved in order to attract insects to pollinate it is interesting; it means that insects can see the color. It adds a question: does this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which the science knowledge only adds to the excitement, the mystery and the awe of a flower. It only adds. I don't understand how it subtracts. – Richard P. Feynman
  • 13. ZyxTech Appreciating beauty... Context Familiarity Curiosity Quest for Knowledge Compassion Ever thought about the audience of your code? Code is also written for humans to read, not only for computers to execute. – Erkki Lindpere
  • 14. ZyxTech Rules that make things beautiful Proportions Integrity Clarity Standards
  • 15. ZyxTech The Zen of Python Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced.
  • 16. ZyxTech The Zen of Python (contd...) In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! by Tim Peters Example: http://bit.ly/dQzuxW
  • 17. ZyxTech What they said about beautiful code? Beautiful code is likely to be simple -- clear and easy to understand. Beautiful code is likely to be compact -- just enough code to do the job and no more -- but not cryptic, to the point where it cannot be understood. Beautiful code may well be general, solving a broad class of problems in a uniform way. One might even describe it as elegant, showing good taste and refinement. - Brian Kernighan
  • 18. ZyxTech What they said about beautiful code? (contd...) I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well. - Bjarne Stroustrup, inventor of C++
  • 19. ZyxTech Clean the code Always leave the campground cleaner than you found it. - The Boy Scout Rule Developers often get anxious to move on to the next feature and forget to clean up the trash that they have left lying around: forgetting to clean Duplicated code Poorly named functions and variables Huge functions Magic numbers Inappropriate combinations of differing levels of abstraction Tight coupling and the list goes on...
  • 20. ZyxTech Things to be taken care of... Names Expressions and Statements Consistency and Idioms Magic numbers Comments
  • 21. ZyxTech Bad Code, Good Code if (($country == SING) || ($country == BRNI) ||  ($country == POL) || ($country == ITALY)) {  // If the country is Singapore, Brunei or Poland then the current    // time is the answer time rather than the off hook time.  // Reset answer time and set day of week.  ... What relationship links Singapore, Brunei, Poland and Italy? Why  isn't Italy mention in the comment?
  • 22. ZyxTech Bad Code, Good Code - Names define(“ONE”, 1); define(“TEN”, 10); define(“TWENTY”, 20); define(“INPUT_MODE”, 1); define(“INPUT_BUFSIZE”, 10); define(“OUTPUT_BUFSIZE”, 20);
  • 23. ZyxTech Bad Code, Good Code - Names for ($the_element_index = 0; $the_element_index <  $number_of_elements;   the_element_index++) {   $element_array[$the_element_index] = $the_element_index; } for ($i = 0, $i < $nelems; $i++) {   elem[$i] = $i; }
  • 24. ZyxTech Bad Code, Good Code - Names class UserQueue {  public $no_of_elements_in_q = 10;  public $front_of_the_queue = 0;  public $queue_capacity = 20;  public function no_of_users_in_queue() {     ...  } } queue = new UserQueue; queue­>queue_capacity $queue = new UserQueue; $queue­>capacity++; $n = $queue­>nusers(); class UserQueue {  public $nitems = 10;  public $front = 0;  public $capacity = 20;  public function nusers() {     ...  } }
  • 25. ZyxTech Bad Code, Good Code - Names if (checkprime($n)) {   … } if (isprime($n)) {   … }
  • 26. ZyxTech Bad Code, Good Code - Names function intable($obj) {   $j = $this­>get_index($obj);//return a value between 0 and    //ntable – 1 if it find the string, and returns ntable if not.   return ($j == $ntable); } ­­ function smaller($s, $t) {   if (strcmp($s, $t) < 1) {     return 1;   }   else {     return 0;   } }
  • 27. ZyxTech Bad Code, Good Code - Expressions if (!($block_id < $actblks) || !($block_id >= $unblocks)) {   … } if (block_id >= actblks) || block_id < unblocks)) {   … }
  • 28. ZyxTech Bad Code, Good Code - Expressions $leap_yr = $y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0; $leap_yr = (($y % 4 == 0) && ($y % 100 != 0)) || ($y % 400 == 0);
  • 29. ZyxTech Bad Code, Good Code - Expressions $x += ($xp = (2 * $k < ($n ­ $m) ? $c[$k + 1] : $d[$k ­ 1])); if (2 * $k < ($n ­ $m)) {   $xp = $c[$k + 1]; } else {   $xp = $d[$k ­ 1]; } $x += $xp;
  • 30. ZyxTech Bad Code, Good Code - Expressions $length = ($length < BUFSIZE) ? $length : BUFSIZE; if ($length > BUFSIZE) {   $length = BUFSIZE; }
  • 31. ZyxTech Bad Code, Good Code - Expressions if ($month == FEB) {   if ($year % 4 == 0)     if ($day > 29)       $legal = FALSE;   else     if ($day > 28)       $legal = FALSE; } if ($month == FEB) {   $nday = 28;   if ((($year % 4 == 0) && ($year % 100 != 0))      || $year % 400 == 0) {     $nday = 29;   }   if ($day > $nday) {     $legal = FALSE;   } }
  • 32. ZyxTech Bad Code, Good Code - Idioms $i = 0; while ($i <= $n­1)   $array[$i++] = 1.0; – for ($i = 0; $i < $n;)   $array[$i++] = 1.0; – for ($i = n; $i = $i ­ 1 >=0;)   $array[$i] = 1.0; – for ($i = 0; i < n; i++)   $array[$i] = 1.0;
  • 33. ZyxTech Bad Code, Good Code - Idioms if (isset($f1) && isset($f2))   if (($fin = $fopen($f1, 'r')) != NULL)     if (($fout = fopen($f2, 'w')) != NULL) {       while (($c = getc(fin)) !== false)          fputs($c, $fout);        fclose($fin);        fclose($fout);     }     else       printf("Can't open output file %sn", f2);  else    printf("Can't open input file %sn", f1); else   printf("Incorrect arguments");
  • 34. ZyxTech Bad Code, Good Code - Idioms if (!isset($f1) || !isset($f2))   print 'Incorrect arguments'; else if (($fin = $fopen($f1, 'r')) == NULL)   printf("Can't open input file %sn", f1); else if (($fout = fopen($f2, 'w')) == NULL) {   printf("Can't open output file %sn", f2);     fclose($fin); } else {   while (($c = fgetc($fin) !== false) {     fputs($c, $fout);   }   fclose($fin);   fclose($fout); }
  • 35. ZyxTech Bad Code, Good Code – Magic Numbers /**  * Print a histogram of letter frequencies on a  * 24 lines by 80 columns screen  */ $fac = $lim / 20; //set scale factor if ($fac < 1)   $fac = 1; //generate histogram for ($i = 0, $col = 0; $i < 27; $i++) {   $col += 3;   $k = 21 ­ ($let[$i] / $fac);   $star = ($let[$i] == 0) ? ' ' : "*";   for ($j = $k; $j < 22; $j++)     draw($j, $col, $star); } draw(23, 2, ' '); //Label x axis for ($i = 'A'; $i <= 'Z'; $i++)   printf("%c ", $i);
  • 36. ZyxTech Bad Code, Good Code – Magic Numbers define(“MINROW”, 1);                   // Top edge define(“MINCOL”, 1);                   // Left edge define(“MAXROW”, 24);                  // Bottom edge (<=) define(“MAXCOL”, 80);                  // Right edge (<=) define(“LABELROW”, 1);                 // Position of labels define(“NLET”, 26);                    // Size of alphabet define(“HEIGHT”, MAXROW – 4);          // Height of bars define(“WIDTH”, (MAXCOL ­ 1) / NLET)   // Width of bars ...
  • 37. ZyxTech Bad Code, Good Code – Magic Numbers (contd...) ... $fac = ($lim + HEIGHT ­ 1) / HEIGHT; // Set scale factor if ($fac < 1)   $fac = 1; //generate histogram for ($i = 0; $i < NLET; $i++) {   if ($let[$i] == 0)     continue;   for ($j = HEIGHT ­ $let[$i] / $fac; $j < HEIGHT; $j++)     draw($j + 1 + LABELROW, ($i + 1) * WIDTH, '*'); } draw(MAXROW ­ 1, MINCOL + 1, ' '); //Label x axis for ($i = 'A'; $i <= 'Z'; $i++)   printf("%c ", $i);
  • 38. ZyxTech Bad Code, Good Code - Comments // default default:   break; // return SUCCESS return SUCCESS; $zerocount++; //increment zero entry counter $node­>total = $node­>number_received; // Initialize total to  number_received
  • 39. ZyxTech Bad Code, Good Code - Comments // string comparison routine returns ­1 if s1 is // above s2 in an ascending order list, 0 if equal // 1 if s1 below s2 function strcmp(s1, s2) {   … } // strcmp: return < 0 if sl < s2, > 0 if s1 > s2, 0 if equal function strcmp(s1, s2) {   … } if (n > MAX || n % 2 > 0) // test for even number The comment is incomplete; the code actually tests for a even  number or a number that is greater than MAX.
  • 40. ZyxTech Some food for thought... Quality is not an act, it is a habit First, solve the problem. Then, write the code. — John Johnson Incorrect documentation is often worse than no documentation. — Bertrand Meyer Controlling complexity is the essence of computer programming. — Brian Kernighan One of my most productive days was throwing away 1000 lines of code. — Ken Thompson There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies. — C.A.R. Hoare, The 1980 ACM Turing Award Lecture
  • 41. ZyxTech References The Practice of Programming - Brian Kernighan, Rob Pike Code Complete 2ed. - Steve McConnell A Regular Expression Matcher - http://bit.ly/1hAUGzh by Brian Kernighan Clean Code - Robert C Martin
  • 42. ZyxTech Contact Us Visit us at http://www.zyxware.com/contact Email us at info@zyxware.com Connect with us at http://www.linkedin.com/company/zyxware-technologies Like us at https://www.facebook.com/zyxware Follow us at https://twitter.com/zyxware