code quality - aesthetics & functionality of writing beautiful code

43
Writing Beautiful Code Vimal Joseph Technical Architect Aesthetics of code and its relevance

Upload: zyxware-technologies

Post on 21-May-2015

735 views

Category:

Technology


0 download

DESCRIPTION

A presentation on the aesthetics and functionality on writing beautiful code. Thoughts on some of the differents aspects of writing beautiful code. The presentation was taken as a part of a workshop on code quality

TRANSCRIPT

Page 1: Code quality - aesthetics & functionality of writing beautiful code

Writing Beautiful Code

Vimal JosephTechnical Architect

Aesthetics of code and its relevance

Page 2: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

Image Courtesy: Indian People Collage by Jamie Furlong

Page 3: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

Guernica by Picasso

Page 4: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

Starry Night by VanGogh

Page 5: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

Water lilies, Nymphaea nouchali, Okavango Delta, Botswana

Page 6: Code quality - aesthetics & functionality of writing beautiful code

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?

Page 7: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

BMW M5

Page 8: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

BMW M5

Page 9: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

How do you define beauty?

Microprocessor

Page 10: Code quality - aesthetics & functionality of writing beautiful code

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

Page 11: Code quality - aesthetics & functionality of writing beautiful code

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.

Page 12: Code quality - aesthetics & functionality of writing beautiful code

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

Page 13: Code quality - aesthetics & functionality of writing beautiful code

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

Page 14: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

Rules that make things beautiful

Proportions

Integrity

Clarity

Standards

Page 15: Code quality - aesthetics & functionality of writing beautiful code

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.

Page 16: Code quality - aesthetics & functionality of writing beautiful code

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

Page 17: Code quality - aesthetics & functionality of writing beautiful code

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

Page 18: Code quality - aesthetics & functionality of writing beautiful code

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++

Page 19: Code quality - aesthetics & functionality of writing beautiful code

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...

Page 20: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

Things to be taken care of...

Names

Expressions and Statements

Consistency and Idioms

Magic numbers

Comments

Page 21: Code quality - aesthetics & functionality of writing beautiful code

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?

Page 22: Code quality - aesthetics & functionality of writing beautiful code

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);

Page 23: Code quality - aesthetics & functionality of writing beautiful code

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;}

Page 24: Code quality - aesthetics & functionality of writing beautiful code

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() {    ... }}

Page 25: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

Bad Code, Good Code - Namesif (checkprime($n)) {  …}

if (isprime($n)) {  …}

Page 26: Code quality - aesthetics & functionality of writing beautiful code

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;  }}

Page 27: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

Bad Code, Good Code - Expressionsif (!($block_id < $actblks) || !($block_id >= $unblocks)) {  …}

if (block_id >= actblks) || block_id < unblocks)) {  …}

Page 28: Code quality - aesthetics & functionality of writing beautiful code

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);

Page 29: Code quality - aesthetics & functionality of writing beautiful code

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;

Page 30: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

Bad Code, Good Code - Expressions$length = ($length < BUFSIZE) ? $length : BUFSIZE;

if ($length > BUFSIZE) {  $length = BUFSIZE;}

Page 31: Code quality - aesthetics & functionality of writing beautiful code

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;  }}

Page 32: Code quality - aesthetics & functionality of writing beautiful code

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;

Page 33: Code quality - aesthetics & functionality of writing beautiful code

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");

Page 34: Code quality - aesthetics & functionality of writing beautiful code

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);}

Page 35: Code quality - aesthetics & functionality of writing beautiful code

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);

Page 36: Code quality - aesthetics & functionality of writing beautiful code

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...

Page 37: Code quality - aesthetics & functionality of writing beautiful code

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);

Page 38: Code quality - aesthetics & functionality of writing beautiful code

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

Page 39: Code quality - aesthetics & functionality of writing beautiful code

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.

Page 40: Code quality - aesthetics & functionality of writing beautiful code

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

Page 41: Code quality - aesthetics & functionality of writing beautiful code

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

Page 42: Code quality - aesthetics & functionality of writing beautiful code

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

Page 43: Code quality - aesthetics & functionality of writing beautiful code

ZyxTech

Thank You...