Measuring code quality:WTF/min by @dgomezg
Upcoming SlideShare
Loading in...5
×
 

Measuring code quality:WTF/min by @dgomezg

on

  • 338 views

David Gómez: "With code examples from the real world that could give you a stroke. ...

David Gómez: "With code examples from the real world that could give you a stroke.

The slides I used on my talk at t3chFest Madrid 2014.

A talk about Code Quality, Clean Code, and good and bad practices when writing code. A fun walk through the experiences from the real world with some advices and introducing some principles that will help you to write better code."

Statistics

Views

Total Views
338
Views on SlideShare
338
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Measuring code quality:WTF/min by @dgomezg Measuring code quality:WTF/min by @dgomezg Presentation Transcript

  • Leganés! 6-7 Febrero 2013! David Gómez G. @dgomezg Measuring Code Quality: WTF/min Code from the real world that could give you a stroke and some advices to not replicate them. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0/
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg 2
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Quality CODE RELATED CONCEPTS 3
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg 4 http://www.osnews.com/story/19266/WTFs_m
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg CODE SMELL A surface indication that usually corresponds to a deeper problem in the system Term coined by Kent Beck 5
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Some Misconceptions You write code for a computer to read You write code to be read by a developer maintaining your code. The computer reads the compiled code Writing smart code, you will improve performance Developers spend most of the time writing code Developers spend most of time reading code 6
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Some Misconceptions You write code for a computer to read You write code to be read by a developer maintaining your code. The computer reads the compiled code Writing smart code, you will improve performance Developers spend most of the time writing code Developers spend most of time reading code 6
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Some Misconceptions You write code for a computer to read You write code to be read by a developer maintaining your code. The computer reads the compiled code Writing smart code, you will improve performance Developers spend most of the time writing code Developers spend most of time reading code 6
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Some Misconceptions You write code for a computer to read You write code to be read by a developer maintaining your code. The computer reads the compiled code Writing smart code, you will improve performance Developers spend most of the time writing code Developers spend most of time reading code 6
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Examples of real code from the real world 7
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg 8
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg The following code has been modified slightly to protect anonymity of authors ! but always respect the original idea (although it could be difficult to believe) 9
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg COMMENTS Comments are useful, but /*        */ Only if they add information or if they explain the code Don’t describe what the code is doing Explain why (pre/post-conditions) Use cases (for methods/types/functions) 10
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min COMMENTS: Unuseful info @dgomezg /*        */
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg COMMENTS: Unuseful info /*        */ /** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { // // } We will get back to the implementation detail More fun later
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min COMMENTS: Unuseful info @dgomezg /*        */     !                 /**  Atributo  codCircuito.  */   private  String  codCircuito;   /**    *  Método  get  codCircuito.    *      *  @return  String    */   public  String  getCodCircuito()  {     return  codCircuito;   }  
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg COMMENTS: Remember to sign your code /*        */ ////////////////////////Manuela   Logger  log  =  LoggerFactory.getLogger(MyClass.class.getName());   ////////////////////////
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg COMMENTS: A good marketing tool /*        */ /** * This method removes all selected files * * Returns a jQuery collection of all affected elements. * * @name reset * @type jQuery * @author Daniel B. ( http://www.visit-my-web.com/) * */ reset: function(){
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min COMMENTS: FOOL THE code READEr @dgomezg /*        */ // Producto p = null; List prod = null; List listaElementos = new ArrayList(); if (nElements > 80) { cmd.setOrden(Producto.SELECT_POR_TIPO); l = new ListParam(); l.add(new Integer(idTipoProducto)); l.add(new Integer(idCategoria)); * for the trick to work out, keep the indentation
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Exceptions Exceptions are just that: Exceptions Catch only if you can handle it Declare the exact type Don’t use for: Flow Control State demarcation (other than Error) 17
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Exceptions: Simply retrowing public  static  Class  cargaClase(java.lang.String  pnombreClase)                  throws  ClassNotFoundException  {          ClassLoader  oloader  =  new  ClasesUtil().getClass()   .getClassLoader();          try  {                  return  oloader  !=  null  ?                       oloader.loadClass(pnombreClase)                       :  Class.forName(pnombreClase);          }  catch  (ClassNotFoundException  x)  {                                        throw  x;          }   }
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min Exceptions: NPE PARANOIA @dgomezg It’s better to check twice to avoid a NullPointerException       while  (session  !=  null)  {     numSessions++  ;     if  (session  !=  null)  {       ...   }   ...   }    
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Exceptions: NPE PARANOIA It’s better to check twice to avoid a NullPointerException while (session != null) { numSessions++ ; if (session != null) { //.... } else { log.warn("Null session detected.” + “ Starting session Synchronization"); //.... dead code follows... } } extra points if you add ‘dead code’ to the else block
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Exceptions: Flow Control public  class  ProcesoTerminadoCorrectamenteException                            extends  Exception  {   ! }   Man! When a process which right ends is an exception… That’s a good confidence in your system!
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg NAMING Use descriptive names Describe what a Class/function/method does, not what it means Describe what a variable/attribute holds Don’t use abbreviations Code for readability 22
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg NAMING: What does this method do?        if(  p  !=  null){                  applyBusinessLogic(p,estado,manager);          }         public  void  onButtonPressed(ActionEvent  e)  {     FormData  formData  =  parseFromEvent(e);     theAlgorithm(formData);   }   23
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code Developers should be lazy Don’t write code you don’t need Don’t repeat yourself 24
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code: Wrapping well-known APIs public  static  String  substringBefore(String  str,String  separator)  {          return  (org.apache.commons.lang.StringUtils   .substringBefore(str,  separator));   }   25
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code: Wrapping well-known APIs               public  String  getPropiedad(String  clave)  {     return  wrappedCacheAdmin.getProperty(clave);   }     public  void  setClaseAlgoritmo(String  clase)  {     wrappedCacheAdmin.setAlgorithmClass(clase);   }   26
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code: Clever? Code        /**  La  constante  CERO.  */          public  static  final  int  CERO=0;                    /**  La  constante  UNO.  */          public  static  final  int  UNO=1;                    /**  La  constante  DOS.  */          public  static  final  int  DOS=2;                    /**  La  constante  TRES.  */          public  static  final  int  TRES=3;   27
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code: Clever? Code Challenge: Could you tell what will print the following code?     System.out.println(DOS  *  TRES); 28
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg 2K Effect… We miss you! NODO 1 ! # Planificacion Procesos Batch # (Formato ss mm hh dd MM yyyy) NODO 3 # cron.sync=0 00 15 * * ? ! # Planificacion Procesos Batch cron.download=0 00 23 * * ? 2030 NODO 4 # (Formato ss mm hh dd MM yyyy) cron.reports=0 00 23 * * ? 2030 ! # ! cron.sync=0 00 16 * * ? # Planificacion Procesos Batch cron.download=0 00 03 * * ? 2030 # (Formato ss mm hh dd MM yyyy) cron.reports=0 00 03 * * ? 2030 # cron.sync=0 00 12 * * ? cron.download=0 00 12 * * 2030 cron.reports=0 00 12 * * 2030 29
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code: SOP Introducing SOP: String Oriented Programming /** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { if (numeroPuestos == 0) return "No"; else return "Si"; } 30
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg UnNecessary code: TAKING ADVICE TOO SERIOUSLY String concatenation in Java is not recommended. Use StringBuffer or StringBuilder instead StringBuffer hql = new StringBuffer( "select distinct config from Config config "); Query query = session.createQuery(hql.toString()) ; Don’t push the recommendations to the limits!!! 31
  • Leganés! 6-7 Febrero 2014 @dgomezg Measuring Code Quality: WTF/min UnNecessary code: The indentation MADNESS                                                                                  ]     });   });                         },                       }                     ]                   }                 }                            }   });                   });            }       });     }   }   32
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg DESIGN PRICIPLES 33
  • Leganés! 6-7 Febrero 2014 @dgomezg Measuring Code Quality: WTF/min K IS S EEP T IMPLE TUPID! 34
  • Leganés! 6-7 Febrero 2014 @dgomezg Measuring Code Quality: WTF/min D R Y on’t epeat ourself 35
  • Leganés! 6-7 Febrero 2014 @dgomezg Measuring Code Quality: WTF/min S OC eparation F oncerns 36
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min I:I @dgomezg ! ! ! ! ! SEPARATION OF CONCERNS DON’T REPEAT YOURSELF 37
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg ENSURING CODE QUALITY: THE QUALITY CYCLE 38
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Default Quality Cycle 39
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Add Intermediate Quality Checks 40
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Automate Intermediate Checks 41
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Measure with tools 42
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Define Business Key Indicators 43
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Define Alarms 44
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Get a Dashboard 45
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Added Value: keeping everybody happy 46
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg SOME FINAL ADVICES 47
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Read! Keep your brain healthy Clean Code: Robert Martin (@unclebob) 48
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg No Monkeys, No Lizards Be concious, be consequent www.adictosaltrabajo.com/detalle-­‐noticia.php?noticia=356 49
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg THe Software RUSTING principle The software degrades slowly and slightly as time passes… Sometimes is not slowly neither slightly!! 50
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg The boy scout rule Try and leave this world a little better than you found it, and when your turn comes to die you can die happy in feeling that at any rate you have not wasted your time but have done your best. Robert Stephenson Smyth Baden-Powell 51
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. John F. Woods, September 1991 52
  • Leganés! 6-7 Febrero 2014 Measuring Code Quality: WTF/min @dgomezg Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. John F. Woods, September 1991 ////////////////////////Manuela   Logger  log  =  LogFactory.getLogger(MyClass.class.getName());   //////////////////////// 53