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