Code quality - aesthetics & functionality of writing beautiful code
-
Upload
zyxware-technologies -
Category
Technology
-
view
732 -
download
0
description
Transcript of Code quality - aesthetics & functionality of writing beautiful code
Writing Beautiful Code
Vimal JosephTechnical 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 Codeif (($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 - Namesdefine(“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 - Namesfor ($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 - Namesclass 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 - Namesif (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 - Expressionsif (!($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 - Expressionsif ($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 <= $n1) $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 - Idiomsif (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 %s\n", f2); else printf("Can't open input file %s\n", 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 %s\n", f1);else if (($fout = fopen($f2, 'w')) == NULL) { printf("Can't open output file %s\n", 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 factorif ($fac < 1) $fac = 1;//generate histogramfor ($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 axisfor ($i = 'A'; $i <= 'Z'; $i++) printf("%c ", $i);
ZyxTech
Bad Code, Good Code – Magic Numbers
define(“MINROW”, 1); // Top edgedefine(“MINCOL”, 1); // Left edgedefine(“MAXROW”, 24); // Bottom edge (<=)define(“MAXCOL”, 80); // Right edge (<=)define(“LABELROW”, 1); // Position of labelsdefine(“NLET”, 26); // Size of alphabetdefine(“HEIGHT”, MAXROW – 4); // Height of barsdefine(“WIDTH”, (MAXCOL 1) / NLET) // Width of bars...
ZyxTech
Bad Code, Good Code – Magic Numbers (contd...)
...$fac = ($lim + HEIGHT 1) / HEIGHT; // Set scale factorif ($fac < 1) $fac = 1;//generate histogramfor ($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 axisfor ($i = 'A'; $i <= 'Z'; $i++) printf("%c ", $i);
ZyxTech
Bad Code, Good Code - Comments// defaultdefault: break;// return SUCCESSreturn 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 s2function strcmp(s1, s2) { …}
// strcmp: return < 0 if sl < s2, > 0 if s1 > s2, 0 if equalfunction 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 habitFirst, 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
ReferencesThe 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 UsVisit us at http://www.zyxware.com/contact
Email us at [email protected]
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...