Code Beauty
-
Upload
daniel-cukier -
Category
Technology
-
view
1.339 -
download
0
Transcript of Code Beauty
1
Code Beauty
Prof. Fabio Kon
Department of Computer ScienceInstitute of Mathematics and Statistics
University of São Paulo
SugarLoafPLoP'2010 - 24/9/2010Salvador, Brazil
2
Agenda
● Definition of Beauty● Is Code Beauty important for Software
Development?● What is Code Beauty
3
Beauty - Ancient View● pre-socratic (e.g., Pythagoras): strong
connection among Beauty and Mathematics; objects with proportions following the golden ratio are more attractive to the human brain
● two quantities are in the golden ratio if the ratio of the sum of the quantities to the larger quantity is equal to the ratio of the larger quantity to the smaller one. The golden ratio is an irrational mathematical constant, approximately 1.6180339887
● greek architecture is based on symmetry and on the golden ratio
4
Beauty - Romantic View
● works do not need to be harmoniously proportioned and constitute a well-rounded whole to be beautiful; on the contrary, dissonance and fragmentation is beautiful
● more precisely: dissonance and fragmentation allude to a harmony and wholeness that is not in the work
5
Beauty - Modernist View
● architect Mies van der Rohe: “Less is More”
~ 1940
● designer Buckminster Fuller (geodesic dome) adopted the engineer's goal of “Doing more with less”
● writer Antoine de Saint Exupéry (1939) “perfection is attained not when there is nothing more to add, but when there is nothing more to remove”
6
Beauty: Post-modernist view
● architect Robert Venturi: “Less is a Bore”, let's do whatever people like
7
the greek and modernist views of beauty provide us with a good basis for approaching Beauty in Science and Technology
8
Science
make everything as simple as possible, but not simpler
9
Technology
Conceptual integrity– the architect or team of architects should
develop an idea of what the system should do and make sure this vision is understood by the rest of the team
– to ensure a user-friendly system, a system may deliberately provide fewer features than it is capable of
10
Beauty dictionary definition
the quality that gives pleasure to the mind or senses and is associated with such properties as
– harmony of form or color,
– excellence of artistry,
– truthfulness,
– and originality.
The American Heritage Dictionary of the English Language, 4th Edition, 2000.
11
Does it matter?
Why are we talking about Code Beauty on a “serious” Software Conference???
● personally, I have two reasons...
12
● there has been a strong movement towards managing software development projects as any other production process/system
● many cases of managers that have never written a single line of code
● is it possible to have a good Chef de Cuisine that has never cooked in his life?
13
● scientists/engineers/practitioners sometimes tend to overestimate the power of science and mathematics
● can science and engineering provide all what's needed to explain life? and software development?
14
What is Software Development?– Modeling (Jacobsen)– Engineering (Meyer)– Discipline (Humphreys)– Poetry (Cockburn)– Craft (Knuth)– Art (Gabriel)
(from from Alistair Cockburn)
● Common mistake: look at software as only one of the above items.
15
● our goal here, is to bring attention to a few important aspects of software development that are neglected in some software engineering communities
● we'll look at the most important deliverable on a software project:
The Code
16
Beauty is fundamentalvinicius de morais
Beautiful code– brings pleasure to the reader
– makes the writer happy
– makes working in groups fun
This leads to – fewer bugs
– maintainability
– team productivity
– in other words, Quality
17
In Software Development,
Beauty
Leads to
Quality
18
What is Beauty in Software Development?
sources:● Robert C. Martin. Clean Code - A Handbook of Agile
Software Craftsmanship. Prentice Hall. 2008.● Andy Oram and Greg Wilson. Beautiful Code.
O'Reilly. 2007.
● beaute(code) art exhibit by Bob Hanmer, Karen Hanmer, and Andrea Polli.
● exchange with experts
19
Rebecca Wirfs-Brock's code beauty ● it is a common recognition that these idioms and those structures and those ways of doing things are of value
● it is important that a project or a team have the same sense of aesthetics or there will be clashes of will
● keeping of every step in a method at the same level of abstraction/intention; it reads much more like prose that way
● characteristics that are "normally" present in beautiful code are balance, effectiveness, expressiveness, and profoundly doing well what it was designed to do.
20
Rebecca's example of a beautiful code
● the Smalltalk class collection
● provide all the built in behavior by requiring subclasses to implement three methods:
●add: anObject●remove: anObject ifAbsent: exceptionBlock●do: aBlock
● methods in the abstract class collection to add, remove, check for emptiness, inclusion, occurrences, and to step through a collection in different ways accumulating values…are all implemented use these abstract building blocks or invoking other defined behaviors that depend on these implementation; elegant, beautiful reuse!
21
Joe Yoder's code beauty● I think it is important to most of us who live there; it is like cleaning up our living area, having clean code or beautiful code can make life much better
● however let's face it, BBoM still thrive and exist and are successful
● it matters, but is not necessary and sufficient for successful software projects. If so, then Clean Code would become the norm
● those of us who care strive for it because we believe it is the right thing to do and it will help us in the long run...but certain forces are in play that can make clean code or beautiful code a goal that is very hard to achieve
22
Joe's example of a beautiful code
● also the Smalltalk class collection● you see a certain beauty and elegance in the system as it was easy to understand and extend
● (it's also my favorite piece of code :-)
● design patterns can help with this as well; if a system is clean and well designed by implementing some of the best known principles and practices one can see certain beauty in the system
23
W h a t is C le a n C ode ?
Bjarne StroustrupInventor of C++
“I like m y code to be e l egant a nd effi c i ent . Th e logic sh ould be
stra i gh forward to m a ke it h a rd for bugs to h ide , th e dependenc i es mi n imal to ease mai ntenance , error hand l i ng compl ete a ccording to a n a rticula ted stra tegy, a nd performance c l ose to opt imal so a s not to tem pt p e op le to m a ke th e code m e ssy w ith unp rincip led optim iza tions. Cl ean code does one th i ng wel l .”
24
W h a t is C le a n C ode ?
Grady BoochAuthor of Object Oriented Analysis and
Design with Applications
“C le a n code is s imp l e a nd d i rec t . C le a n code reads l i k e wel l -wri t ten prose . C le a n code ne ver obscure s th e designe r's intent but rath e r is full of crisp [cle a rly de fined] a bstra ctions a nd stra i gh forward lines of control. ”
25
W h a t is C le a n C ode ?
Dave ThomasFounder of OTI, godfather of
the Eclipse Strategy
“Cl ean code can be read , a nd enh a nced by a develop e r oth e r th a n its origina l a uth or. I t has un i t and acceptance tests . It h a s
meani ngfu l names . It p rovides
one way ra th e r th a n m a ny w a ys
for doing one th ing. It h a s mi n imal dependenc i es , w h ich a re exp licitly de fined, a nd p rovide s a cle a r a nd mi n imal API . C ode
sh ould be l i te rate since de p e nding on th e la ngua ge , not a ll ne ce ssa ry inform a tion ca n be e xp ressed cle a rly in code a lone . ”
26
W h a t is C le a n C ode ?
Michael FeathersAuthor of Working Effectively
With Legacy Code
“I could list a ll of th e qua litie s th a t I notice in cle a n code , but th e re is one ove ra rch ing qua lity th a t le a ds to a ll of th em . Cl ean code always l ook s i t was wri tten by someone who cares . There i s noth i ng obvi ous that you can do to make i t better . A ll of th ose th ings w ere th ough t a bout by th e code 's a uth or, a nd if you try to im a gine im p rovem ents, you're le d ba ck to w h e re you a re , sitting in a p p re cia tion of th e code som e one le ft for you – code l e ft by someone who cares deep l y about the c raft . ”
27
W h a t is C le a n C ode ?
Ron JeffriesAuthor of Extreme
Programming Installed
“In re ce nt ye a rs I be gin, a nd ne a rly end, w ith B e ck's rules of sim p le code . In p riority order, sim p le code : • Runs al l tests• Conta i ns no dup l i c at i on• Expresses al l the des i gn i deas th a t a re in th e system• Mi n imi zes the number of ent i t i es such a s cla sses, m eth ods, functions, a nd th e like .”
28
W h a t is C le a n C ode ?
Ward CunninghamInventor of Wiki, Fit and much more
”Godfather of all those who care about code”
You know you a re w orking on cle a n code w h en each rout i ne you read turns out to be pretty much what you expec ted . Y ou
ca n ca ll it beaut i fu l code w h e n th e
codes a lso makes i t l ook l i k e the l anguage was made for the probl em . ”
29
W h a t is C le a n C ode ?
S im p le
S tra igh tforw a rd
E fficie nt
E xp re ssive
R uns a ll tests
L itera l
Turns out to be w h a t you e xp e cted
M inim a l
C onta ins no dup lica tions
F ull of m e a ning
W ith out obvious im p rovem ents
W ritten by som eone w h o
ca res
R e a ds w e ll
Beaut i fu l : when the l anguage was made for the probl em
30
language may influence
/* C Language */#include <stdio.h>#define NumLines 10 /* number of lines */main(argc,argv) int argc; char **argv;{ int tri[NumLines][NumLines], /* triangle */ r,c,i; /* row, column, misc index */
/* initialize array */ for (r=0;r<NumLines;r++) { tri[r][0]=1; for (c=1;c<NumLines;c++) { tri[r][c]=0; }; /* generate triangle */ tri[0][0]=1; for (r=1;r<NumLines;r++){ for (c=1;c<NumLines;c++) { tri[r][c]=tri[r-1][c] + tri[r-1][c-1]; } }; /* print triangle */ for (r=0;r<NumLines;r++){
for (i=0;i < ((NumLines-r-1)/2);i++) printf(" ");if (r%2 == 0) printf(" ");
for (c=0;c<NumLines;c++){ if (tri[r][c] != 0) printf("%3d ",tri[r][c]); }; printf("\n"); }}
source: http://www.andreapolli.com/beaute%28code%29/good_bad_ugly/pascal.html
31
let's get a little more technical
32
Meani ngfu l Names
33
M e a ningful N a m es
● C ode is ba sica lly na m es a nd rese rved w ords
● C h oosing good na m es ta kes tim e but sa ves
m ore th a n it ta kes
● N a m es sh ould be e xp ressive a nd sh ould
a nsw er questions
Names are vi ta l !
34
M e a ningful N a m es
public List<int[]> getThem() {List<int[]> list1 = new ArrayList<int[]>();for (int[] x : theList)
if(x[0] == 4)list1.add(x);
return list1;}
Exampl e
35
M e a ningful N a m es
public List<int[]> getThem() {List<int[]> list1 = new ArrayList<int[]>();for (int[] x : theList)
if(x[0] == 4)list1.add(x);
return list1;}
Exampl e
M a ny doubts a rise . . .
1 . W h a t does th is m eth od get?
2 . W h a t kinds of th ings a re in th e L ist?
3. W h a t is th e im p orta nce of th e zeroth p osition?
4. W h a t is th e significa nce of th e va lue 4?
36
M e a ningful N a m es
public List<int[]> getThem() {List<int[]> list1 = new ArrayList<int[]>();for (int[] x : theList)
if(x[0] == 4)list1.add(x);
return list1;}
Exampl e
public List<int[]> getFlaggedCells() {List<int[]> flaggedCells = new ArrayList<int[]>();for (int[] cell : gameBoard)
if(cell[STATUS_VALUE] == FLAGGED)flaggedCells.add(cell);
return flaggedCells;}
W h a t a bout th is code ?
37
M e a ningful N a m es
Exampl e
public List<int[]> getFlaggedCells() {List<int[]> flaggedCells = new ArrayList<int[]>();for (int[] cell : gameBoard)
if(cell[STATUS_VALUE] == FLAGGED)flaggedCells.add(cell);
return flaggedCells;}
P roblem solved!
1 . W h a t does th is m eth od get? It gets a ll fla gged ce lls!
2 . W h a t kinds of th ings a re in th e L ist? th e L ist is a ga m eB oa rd filled w ith
ce lls!
3. W h a t is th e im p orta nce of th e ze roth p osition? Th a t's th e S ta tus Va lue !
4. W h a t is th e significa nce of th e va lue 4? It m e a ns it is fla gged!
38
M e a ningful N a m es
Exampl epublic List<int[]> getFlaggedCells() {
List<int[]> flaggedCells = new ArrayList<int[]>();for (int[] cell : gameBoard)
if(cell[STATUS_VALUE] == FLAGGED)flaggedCells.add(cell);
return flaggedCells;}
G oing furth er. . .
public List<Cell> getFlaggedCells() {List<Cell> flaggedCells = new ArrayList<Cell>();for (Cell cell : gameBoard)
if(cell.isFlagged())flaggedCells.add(cell);
return flaggedCells;}
Th i s i s pretty much what
you expec ted !
39
● Use Readab l e names● X Y Z C ontrollerH a ndlingO fS trings != X Y Z C ontrolle rS tora ge O fS trings
● Use Searchab l e names
● Use the Language Standards● Use Sol ut i on Domai n names
● U se p a ttern a nd a lgorith m na m es, m a th te rm s, …
● Use Prob l em Domai n names
● Don 't confuse the reader● U se th e ”O ne W ord P e r C once pt” rule● D on't use jokes, m ind m a p p ings, h unga ria n nota tion, . . .
Changes shou l d be easy!
To m a ke ch a nges, w e ne ed to understa nd th e
code !
40
M e a ningful N a m es
● it is e a sy to sa y th a t na m es sh ould re ve a l intent. W h a t
w e w a nt to im p ress up on you is th a t w e a re s e rio us a bout
th is
● sh ort na m es a re gene ra lly better th a n longer one s, so
long a s th e y a re cle a r (do not p rom ote obscurity to sa ve a
coup le of ke ystrokes)
● i f you fi nd a bad name , change i t now !
Conc l us i on
41
Func t i ons
42
F unctions
● func t i ons shou l d have few l i nes● e a ch of th em sh ould be obvious a nd e a sy to understa nd
● func t i ons shou l d not hol d nested struc tures● if, w h ile , e lse blocks sh ould be stra igh tforw a rd
(p roba bly a function ca ll)
● th e conditiona l sh ould p roba bly be a function ca ll th a t e nca p sula te s it
Func t i ons shou l d be smal l !
43
F unctions
● func t i ons that do one th i ng can 't be d i vi ded i n to sec t i ons
● two ways to i dent i fy whether a func t i on does One Th i ng● if a function does only th ose step s th a t a re one le ve l be low th e sta ted
na m e of th e functions, th e n th e functions is do ing one th ing
● If you ca n't extra ct a noth er function from it w ith a na m e th a t is not
m ere ly a re sta tem ent of its im p lem enta tion, th e n it's doing one th ing
One Th i ng !F unctions sh ould do one th ing.
Th e y sh ould do it w e ll.
Th e y sh ould do it only.
44
public void pay() {for (Employee e : employees) {
if (e.isPayday()) {Money pay = e.calculatePay();e.deliverPay(pay);
}}
}
Exampl e
It doe s m ore th a n one th ing. . .
1 . it loop s ove r a ll th e em p loye e s
2 . ch e cks to se e w h eth e r e a ch em p loye e ough t to be
p a yed
3. p a ys th e em p loye e
45
public void pay() {for (Employee e : employees)
payIfNecessary(e);}
private void payIfNecessary(Employee e) {if (e.isPayday())
calculateAndDeliverPay();}
private void calculateAndDeliverPay(Employee e) {
Money pay = e.calculatePay();e.deliverPay(pay);
}
Refac tored Exampl e
It just itera tes ove r th e em p loye es
C h e cks w h eth e r a n em ploye e ough t to be p a id
P a ys th e em p loye e
is this exaggerated?
46
F unctions
● statements wi th i n a func t i on shou l d be al l i n the same l eve l
● mi x i ng l eve l s i s confus i ng● once deta ils a re m ixe d w ith e ssentia l conce pts, m ore a nd m ore
deta ils tend to a ccrete w ith in th e functions
● it's th e first ste p tow a rds th e cre a tion of big functions!
● the Stepdown ru l e● we w a nt code to re a d like a top -dow n na rra tive
One l eve l of Abstrac t i on
47
F unctions
● func t i ons shou l d mi n imi ze the number of arguments
● a rgum ents a re h a rd from a te sting p o int of view
● too m a ny a rgum ents = th e function doe s m ore th a n one th ing
● too m a ny a rgum ents = th e function is used in m a ny diffe rent w a ys
● don 't use fl ag arguments
● it loudly p rocla im s th a t th e functions is doing m ore th a n one th ing
Func t i on arguments
48
F unctions
● func t i ons shou l d not have s i de effec ts● th e y usua lly cre a te tem p ora l coup ling
● it sh ould cre a te a e ffe ct on th e obje ct or return som eth ing
● Don 't Repeat Yourse l f (DRY)● dup lica tion m a y be th e root of a ll e vil in softw a re
Last but not l east
functions sh ould be sh ort, w e ll na m ed a nd nice ly orga nized
49
Comments
”N oth ing ca n be quite so h e lp ful a s a w e ll-p la ced com m ent. N oth ing ca n clutter up a m odule th a n frivolous dogm a tic com m ents. N oth ing ca n be quite so da m a ging a s a n old crufty com m ent th a t p rop a ga tes lie s a nd m isinform a tion. ”
50
C om m ents
● comments are , at best , necessary evi l● th e p rop e r use of com m ents is to com p ensate for our fa ilure to
e xp ress ourself in code ; note th a t I used th e w ord failure; I m e a nt it
● they l i e !● p rogra m m ers ca n't re a listica lly m a inta in th em
● com m ents don't a lw a ys follow th e code ch a nges
● th e y re quire a m a inte na nce e ffort th a t ta kes tim e
● truth ca n only be found in one p la ce : th e code
The probl em wi th comments
51
C om m ents
Code i s the onl y truth
52
C om m ents
● l ega l comments
● informat i ve comments
● C om m enting re gula r e xp ressions ca n be quite use ful
● exp l anat i on of i n tent and c l ar i fi c at i ons● som e de cisions a ren't im p lem e nta tion de cisions
● we h a ve to use libra rie s th a t a re n't so exp ressive
● Ampl i fi c at i on
● e xp la in h ow im p orta nt a n e lem ent is
● TODO Comments and Javadoc s i n Publ i c API
Good Comments
53
54
why should we write beautiful code?
to feel good with ourselves
55
Bibliography
● Wikipedia definition for Beauty, Golden Ratio, Minimalism. 2010.
● Fred Brooks. The Mythical Man-Month: Essays on Software Engineering. 1975.
● Dorthe Jørgensen. The Metamorphosis of Beauty. 2002.
● The American Heritage Dictionary of the English Language, 4th Edition, 2000.
56
Bibliography
● Robert C. Martin. Clean Code - A Handbook of Agile Software Craftsmanship. Prentice Hall. 2008.
● Andy Oram and Greg Wilson. Beautiful Code. O'Reilly. 2007.
● beaute(code) art exhibit by Bob Hanmer, Karen Hanmer, and Andrea Polli. Some material available at http://karenhanmer.com/gallery/?gallery=beautecode and http://www.andreapolli.com/beaute(code)
● Interviews with experts
● slides by João Machini de Miranda - IME/USP