Wtf per lineofcode

1,502 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,502
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Wtf per lineofcode

  1. 1. Measuring Code Quality:WTF/MinuteReal word examples of code that could give you a strokeand some advices to not replicate them
  2. 2. About the speakerDavid GómezSw Architect & Trainerdgomezg@autentia.com@dgomezg
  3. 3. Code quality relatedconcepts
  4. 4. Code Quality:WTFs/lines of codehttp://www.osnews.com/story/19266/WTFs_m
  5. 5. Code smellsA surface indicationthat usuallycorresponds to adeeper problem inthe systemTerm coined by Kent Beck
  6. 6. Some misconceptionsYou write code for a computer to readYou write code to be read by a developer maintaining yourcode.The computer reads the compiled codeWriting smart code, you will improve performanceDevelopers spend most of the time writing codeDevelopers spend most of time reading code
  7. 7. Examples of real codefrom the real world
  8. 8. Health warning!
  9. 9. CommentsComments are useful, butonly if the add or explain the code.Don’t describe what the code is doingExplain why (pre/post-Conditions)Use cases (for methods/types/functions)
  10. 10. Unuseful information
  11. 11. Unuseful comments /** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() {// We will get back to the implementation detail// More fun later }
  12. 12. Unuseful comments   /**  Atributo  codCircuito.  */   private  String  codCircuito;   /**    *  Método  get  codCircuito.    *      *  @return  String    */   public  String  getCodCircuito()  {     return  codCircuito;   }
  13. 13. Remember to sign your code////////////////////////ManuelaLogger  log  =  LoggerFactory.getLogger(MyClass.class.getName());////////////////////////
  14. 14. Comments as 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.hispersonaldomain.com/)**/reset: function(){
  15. 15. Fooling the reader with commentsProducto 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));Fool the reader by commenting out only the if check*For the trick to work out, keep the indentation
  16. 16. Exceptions/ErrorsExceptions are just that: ExcepctionsCatch only if you can handle itDon’t use forFlow ControlState demarcation (Except error)
  17. 17. Simply retrhowing exceptionspublic  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;        }}
  18. 18. NPE ParanoiaIt’s better to check twice in order to avoid a NullPointerException   while  (session  !=  null)  {     numSessions++  ;     if  (session  !=  null)  {     ...}...}    
  19. 19. NPE Paranoia while (session != null) { numSessions++ ; if (session != null) { //.... } else { log.warn("Null session detected.” +“ Starting session Synchronization"); //.... dead code follows... } }It’s better to check twice in order to avoid a NullPointerExceptionExtra points if you add Dead code to an else block
  20. 20. NamingUse descriptive namesDescribe what a Class/Function/methoddoes, not what it meansDescribe what a variable/attribute holdsDon’t use abreviationsCode for readability
  21. 21. What does this method do?        if(  p  !=  null){                applyBusinessLogic(p,estado,manager);        }  else  {        }   public  void  onButtonPressed(ActionEvent  e)  {     FormData  formData  =  parseFromEvent(e);     theAlgorithm(formData);   }
  22. 22. Unnecesary CodeDevelopers should be lazyDon’t write code you don’t needDon’t repeat yourself
  23. 23. Wrapping well know APIspublic  static  String  substringBefore(String  str,String  separator)  {        return  (org.apache.commons.lang.StringUtils.substringBefore(str,  separator));}   public  String  getPropiedad(String  clave)  {     return  wrappedCacheAdmin.getProperty(clave);   }     public  void  setClaseAlgoritmo(String  clase)  {     wrappedCacheAdmin.setAlgorithmClass(clase);   }
  24. 24. ¿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;
  25. 25. ¿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;     System.out.println(DOS  *  TRES);Could you tell what will print the following code?
  26. 26. NODO 4# Planificacion Procesos Batch# (Formato ss mm hh dd MM yyyy)#cron.sync=0 00 12 * * ?cron.download=0 00 12 * * 2030cron.reports=0 00 12 * * 20302K Effect - We miss you!NODO 3# Planificacion Procesos Batch# (Formato ss mm hh dd MM yyyy)#cron.sync=0 00 16 * * ?cron.download=0 00 03 * * ? 2030cron.reports=0 00 03 * * ? 2030NODO 1# Planificacion Procesos Batch# (Formato ss mm hh dd MM yyyy)#cron.sync=0 00 15 * * ?cron.download=0 00 23 * * ? 2030cron.reports=0 00 23 * * ? 2030
  27. 27. SOO - String oriented Programning /** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { if (numeroPuestos == 0) return "No"; else return "Si"; }
  28. 28. Taking advice too seriouslyDon’t push the recommendations to the limitsStringBuffer hql =new StringBuffer("select distinct config from Config config "); Query query = session.createQuery(hql.toString()) ;String concatenation in Java is not recommended,Use StringBuffer (or StringBuilder) instead
  29. 29. The indentation madness                                  }                             });                           }                         }                     });                      }                 });               }             }           ]         }       },          ]   });});
  30. 30. Design principles
  31. 31. Keep It Simple Stupid!
  32. 32. Don’t Repeat Yourself
  33. 33. Separation of Concerns
  34. 34. 1:1Separation Of ConcernsDon’t RepeatYourself
  35. 35. Tell,Don’t Ask
  36. 36. Ensuring Code QualityThe Quality Cycle
  37. 37. The Quality Cycle
  38. 38. Checks at intermediary points
  39. 39. Checks at intermediary points
  40. 40. Tools: Measure
  41. 41. Define bussiness key points
  42. 42. Define alarms
  43. 43. Get a Dashboard
  44. 44. Added value
  45. 45. Some final advices
  46. 46. Clean  CodeRobert  Mar.n(@unclebob)John F. Woods, September 1991Read! Keep your brain healty!
  47. 47. Be conscious, Be consequenthttp://www.adictosaltrabajo.com/detalle-noticia.php?noticia=356No monkeys, no lizards
  48. 48. 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 1991Code for readability
  49. 49. 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 1991Code for readability////////////////////////ManuelaLogger  log  =  LogFactory.getLogger(MyClass.class.getName());////////////////////////(Specially if you have your code signed)
  50. 50. Q&A

×