Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Code Beauty

1,908 views

Published on

Published in: Technology
  • Be the first to comment

Code Beauty

  1. 1. Code Beauty Prof. Fabio Kon Department of Computer Science Institute of Mathematics and Statistics University of São Paulo SugarLoafPLoP'2010 - 24/9/2010 Salvador, Brazil 1
  2. 2. Agenda ● Definition of Beauty ● Is Code Beauty important for Software Development? ● What is Code Beauty 2
  3. 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 3
  4. 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 4
  5. 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” 5
  6. 6. Beauty: Post-modernist view ● architect Robert Venturi: “Less is a Bore”, let's do whatever people like 6
  7. 7. the greek and modernist views of beauty provide us with a good basis for approaching Beauty in Science and Technology 7
  8. 8. Science make everything as simple as possible, but not simpler 8
  9. 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 9
  10. 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. 10
  11. 11. Does it matter? Why are we talking about Code Beauty on a “serious” Software Conference??? ● personally, I have two reasons... 11
  12. 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? 12
  13. 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? 13
  14. 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. 14
  15. 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 15
  16. 16. Beauty is fundamental vinicius 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 16
  17. 17. In Software Development, Beauty Leads to Quality 17
  18. 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 18
  19. 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. 19
  20. 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! 20
  21. 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 21
  22. 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 22
  23. 23. W h a tis C l a n C ode ? e “I l m y co de t be e l e g a n t a nd ike o e ffi c i e n t. Th e l gic sh o ul be o d s t ra i g h forw a rd t m a ke it h a rd o fo r bugs to h ide , te h dependenc i es mi ni mal to ease mai ntenanc e, e rror h a n d l i n g c om p l e t e a cco rding t o an a rt a t d icul e st t gy, ra e a nd p e rform a n c e c l os e to op t i m a l so a s not t t m p t p e op l t m a ke o e e o t e co de m e ssy w it unp rincip l d h h e op t iza t im ions. Cl e a n c od e d oe s on e t h i n g w e l l .” Bjarne Stroustrup Inventor of C++ 23
  24. 24. W h a tis C l a n C ode ? e “C l a n co de is s i m p l e a nd d i re c t. e C l a n co de re a d s l i k e w e l l - e w ri t te n p ros e . C l a n code ne ve r e obscure s t e de signe r's int nt but h e ra t e r is ful o f crisp [cl a rl de fine d] h l e y a bst ct ns a nd s tra i g h forw a rd ra io l s o f co nt l ” ine ro . Grady Booch Author of Object Oriented Analysis and Design with Applications 24
  25. 25. W h a tis C l a n C ode ? e “Cl e a n c od e c a n b e re ad , a nd e nh a nce d by a de ve l p e r o t e r t a n o h h it origina l a ut or I t h a s u n i t a n d s h . ac c eptanc e tests. It h a s m e a n i n g fu l n am e s . It p rovide s on e w a y ra t e r t a n m a ny w a ys h h fo r do ing o ne t ing. It h a s m i n i m a l h dependenc i es, w h ich a re e xp l l de fine d, a nd p ro vide s a icity cl a r a nd m i n i m a l AP I . C ode e sh o ul be l i te ra t e since de p e nding d on t e l ngua ge , not a l ne ce ssa ry h a l info rm a t n ca n be e xp re sse d io Dave Thomas cl a rl in code a l ne . ” e y o Founder of OTI, godfather of the Eclipse Strategy 25
  26. 26. W h a tis C l a n C ode ? e “I co ul l a l o f t e qua l ie s t a t I d ist l h it h no t ice in cl a n code , but t e re is e h one ove ra rch ing qua l y t a t l a ds t it h e o a l o f t e m . Cl e a n c od e a l w a ys l h l ook s i t w a s w ri t t e n b y s om e on e w h o c a re s . Th e re i s n ot h i n g obvi ou s t h a t you c a n d o t o m a k e i t b e tt e r. A l of l t o se t ings w e re t o ugh t a bo ut by h h h t e co de 's a ut or a nd if you t t h h , ry o im a gine im p ro ve m e nt yo u're l d s, e ba ck t w h e re you a re , siting in o t a p p re cia t n o f t e code som e one io h l ft fo r yo u – c od e l e ft b y e Michael Feathers Author of Working Effectively s om e on e w h o c are s d e e p l y With Legacy Code a b ou t th e c ra ft. ” 26
  27. 27. W h a tis C l a n C ode ? e “In re ce ntye a rs I be gin, a nd ne a rl y e nd, w it B e ck's rul s of sim p l h e e co de . In p rio rit o rde r, sim p l code : y e • R u n s al l t e s t s • Con ta i n s n o d u p l i c a t i on • E x p re s s e s al l t h e d e s i g n i d e a s t a ta re in t e syst m h h e • Mi n i m i ze s th e n u m b e r of e n t i ti e s such a s cl sse s, m e t o ds, a h funct ions, a nd t e l . ” h ike Ron Jeffries Author of Extreme Programming Installed 27
  28. 28. W h a tis C l a n C ode ? e Y o u kno w you a re w orking on cl a n e co de w h e n e a c h rou ti n e you re a d tu rn s ou t t o be p re t t y m u c h w h at you e x p e c t e d . Y o u ca n ca l it b e a u t i fu l code w h e n t e l h co de s a l m a k e s i t l ook l i k e so t h e l a n g u a g e w a s m a d e for t h e p rob l e m . ” Ward Cunningham Inventor of Wiki, Fit and much more ”Godfather of all those who care about code” 28
  29. 29. W h a tis C l a n C ode ? e W it outo bvio us h S im p le im p rove m e nt s E fficie nt S t igh t rw a rd ra fo E xp re ssive C o nt ins no a Turns outt be w h a t o dup l t ica ions you e xp e ct d e R uns a l t st le s F ul o f m e a ning l L it ra l e R e a ds w e ll B e a u t i fu l : when M inim a l th e l anguage was W rite n by t made for th e som e one w h o p rob l e m ca re s 29
  30. 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 30
  31. 31. let's get a little more technical 31
  32. 32. Me an i n g fu l Names 32
  33. 33. M e a ningful N a m e s N a m e s are vi t a l ! ● C ode is ba sica ly na m e s a nd re se rve d w o rds l ● C h o o sing go od na m e s t ke s t e butsa ve s a im m o re t a n itt ke s h a ● N a m e s sh oul be e xp re ssive a nd sh o ul d d a nsw e r que st ns io 33
  34. 34. M e a ningful N a m e s E xampl e public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if(x[0] == 4) list1.add(x); return list1; } 34
  35. 35. M e a ningful N a m e s E xampl e public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if(x[0] == 4) list1.add(x); return list1; } M a ny do ubt a rise . . . s 1 . W h a tdoe s t is m e t od ge t h h ? 2 . W h a tkinds o f t ings a re in t e L ist h h ? 3. W h a tis t e im p ort nce of t e ze rot p osit h a h h ion? 4. W h a tis t e significa nce o f t e va l 4? h h ue 35
  36. 36. M e a ningful N a m e s E xampl e public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if(x[0] == 4) list1.add(x); return list1; } W h a ta bo utt is h code ? public List<int[]> getFlaggedCells() { List<int[]> flaggedCells = new ArrayList<int[]>(); for (int[] cell : gameBoard) if(cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell); return flaggedCells; } 36
  37. 37. M e a ningful N a m e s E xampl 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 robl m e sol d! ve 1 . W h a tdo e s t is m e t o d ge t Itge t a l fl gge d ce ls! h h ? s l a l 2 . W h a tkinds o f t ings a re in t e L ist t e L istis a ga m e B oa rd file d w it h h ? h l h ce ls! l 3. W h a tis t e im p o rt nce of t e ze rot p osit n? Th a t t e S t t Va l ! h a h h io 's h a us ue 4. W h a tis t e significa nce o f t e va l 4? Itm e a ns itis fl gge d! h h ue a 37
  38. 38. M e a ningful N a m e s E xampl 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; } G oing furt e r . . h . 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 p re t ty } muc h wh at you e x p e c te d ! 38
  39. 39. Ch a n g e s s h ou l d b e e as y! To m a ke ch a nge s, w e ne e d t unde rst nd t e o a h ● Us e R e a d ab l e n am e s co de ! ● X Y Z C o nt l rH a ndl role ingO fS trings != X Y Z C ont le rS t ge O fS t ro l ora rings ● Us e Se a rc h a b l e n am e s ● Us e t h e L an g u ag e St an d a rd s ● Us e Sol u t i on Dom a i n n a m e s ● U se p a te rn a nd a l t gorit m na m e s, m a t t rm s, … h h e ● Us e P rob l e m Dom a i n n a m e s ● Don 't c on fu s e t h e re a d e r ● U se t e ”O ne W ord P e r C o nce p t rul h ” e ● D o n'tuse j s, m ind m a p p ings, h unga ria n no t t oke a ion, . . . 39
  40. 40. M e a ningful N a m e s Con c l u s i on ● itis e a sy t sa y t a tna m e s sh oul re ve a l int nt W h a t o h d e . w e w a ntt im p re ss up o n yo u is t a tw e a re s e rio us a bo ut o h t is h ● sh o rtna m e s a re ge ne ra ly be te r t a n l nge r o ne s, so l t h o l ng a s t e y a re cl a r (do notp ro m o t obscurit t sa ve a o h e e y o co up l o f ke yst ke s) e ro ● i f you fi n d a b a d n a m e , c h a n g e i t n ow ! 40
  41. 41. Fu n c t i on s 41
  42. 42. F unct ions Fu n c ti on s s h ou l d b e smal l ! ● fu n c t i on s s h ou l d h a ve fe w l i n e s ● e a ch of t e m sh oul be o bvio us a nd e a sy t unde rst nd h d o a ● fu n c t i on s s h ou l d n ot h ol d n e s te d s t ru c t u re s ● if, w h il , e l bl cks sh o ul be st igh t e se o d ra forw a rd (p roba bl a funct ca l) y ion l ● t e condit na l sh oul p roba bl be a funct n ca l t a te nca p sul t s it h io d y io lh a e 42
  43. 43. F unct ions On e Th i n g ! F unct ions sh oul do one t ing. d h Th e y sh oul do itw e l. d l Th e y sh o ul do itonl d y. ● fu n c ti on s t h a t d o on e t h i n g c an 't b e d i vi d e d i n t o s e c t i on s ● t w o w a ys t o i d e n t i fy w h e th e r a fu n c t i on d oe s On e Th i n g ● if a funct do e s onl t ose st p s t a ta re one l ve l be l w t e st t d ion y h e h e o h a e na m e of t e funct h ions, t e n t e funct ns is do ing one t ing h h io h ● If you ca n'te xt cta no t e r funct n from itw it a na m e t a tis no t ra h io h h m e re l a re st t m e ntof it im p l m e nt t y a e s e a ion, t e n it doing o ne t ing h 's h 43
  44. 44. E xampl e public void pay() { for (Employee e : employees) { if (e.isPayday()) { Money pay = e.calculatePay(); e.deliverPay(pay); } } } Itdoe s m ore t a n one t ing. . . h h 1 . itl op s ove r a l t e e m p l e s o lh oye 2 . ch e cks t se e w h e t e r e a ch e m p l e ough tt be o h oye o p a ye d 3. p a ys t e e m p l ye e h o 44
  45. 45. R e fa c t ore d E xampl e public void pay() { for (Employee e : employees) Itj it ra t s ove r ust e e payIfNecessary(e); t e em pl es h oye } private void payIfNecessary(Employee e) { C h e cks w h e t e r a n h if (e.isPayday()) calculateAndDeliverPay(); e m p l e o ugh tt be p a id oye o } private void P a ys t e h calculateAndDeliverPay(Employee e) { Money pay = e.calculatePay(); e m p l ye e o e.deliverPay(pay); } is this exaggerated? 45
  46. 46. F unct ions On e l e ve l of Ab s t ra c t i on ● s t a t e m e n t s w i th i n a fu n c t i on s h ou l d b e a l l i n th e s a m e l e ve l ● m i x i n g l e ve l s i s c on fu s i n g ● o nce de t il a re m ixe d w it e sse nt l conce p t m ore a nd m ore a s h ia s, de t il t nd t a ccre t w it in t e funct a s e o e h h ions ● it t e firstst p t a rds t e cre a t of big funct 's h e ow h ion ions! ● t h e St e p d ow n ru l e ● w e w a ntcode t re a d l a t -do w n na rra t o ike op ive 46
  47. 47. F unct ions Fu n c ti on a rg u m e n t s ● fu n c ti on s s h ou l d m i n i m i ze t h e n u m b e r of a rg u m e n ts ● a rgum e nt a re h a rd from a t st p o into f vie w s e ing ● t o m a ny a rgum e nt = t e funct doe s m o re t a n o ne t ing o s h ion h h ● t o m a ny a rgum e nt = t e funct is use d in m a ny diffe re ntw a ys o s h ion ● d on 't u s e fl ag arg u m e n t s ● itloudl p ro cl im s t a tt e funct y a h h ions is doing m o re t a n one t ing h h 47
  48. 48. F unct ions L as t b u t n ot l e a s t ● fu n c ti on s s h ou l d n ot h a ve s i d e e ffe c t s ● t e y usua ly cre a t t m p ora l co up l h l e e ing ● itsh o ul cre a t a e ffe cton t e obj ctor re t so m e t ing d e h e urn h ● Don 't R e p e a t You rs e l f (DR Y) ● dup l t n m a y be t e rooto f a l e vil in soft a re ica io h l w functions sh o ul be sh ort w e l na m e d a nd nice l orga nize d d , l y 48
  49. 49. Com m e n t s ”N o t ing ca n be quit so h e l ful a s a w e l-p l ce d com m e nt h e p l a . N o t ing ca n cl t r up a m odul t a n frivo l h ute e h ous do gm a t ic co m m e nt N ot ing ca n be quit so da m a ging a s a n ol cruft s. h e d y co m m e ntt a tp rop a ga t s l s a nd m isinfo rm a t ” h e ie ion. 49
  50. 50. C o m m e nt s Th e p rob l e m w i th c om m e n t s ● c om m e n t s are , a t b e s t , n e c e s s ary e vi l ● t e p ro p e r use o f com m e nt is t co m p e nsa t for our fa il h s o e ure t o e xp re ss o urse l in code ; no t t a tI use d t e w ord failure; I m e a ntit f e h h ● th ey l i e! ● p ro gra m m e rs ca n'tre a l ica ly m a int in t e m ist l a h ● co m m e nt do n'ta l a ys folow t e code ch a nge s s w l h ● t e y re quire a m a int na nce e ffo rtt a tt ke s t e h e h a im ● t h ca n o nl be found in o ne p l ce : t e code rut y a h 50
  51. 51. C o m m e nt s Cod e i s t h e on l y tru th 51
  52. 52. C o m m e nt s Good Com m e n ts ● l e g a l c om m e n t s ● in form a ti ve c om m e n t s ● C o m m e nt re gul r e xp re ssions ca n be quit use ful ing a e ● e x p l an at i on of i n t e n t an d c l a ri fi c at i on s ● som e de cisions a re n'tim p l m e nt t de cisions e a ion ● w e h a ve t use l rie s t a ta re n'tso e xp re ssive o ibra h ● Am p l i fi c a ti on ● e xp l in h ow im p o rt nta n e l m e ntis a a e ● TODO Com m e n t s an d J avad oc s i n P u b l i c AP I 52
  53. 53. 53
  54. 54. why should we write beautiful code? to feel good with ourselves 54
  55. 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. 55
  56. 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 56

×