wtf per lineofcode

50
Measuring Code Quality: WTF/Minute Real word examples of code that could give you a stroke and some advices to not replicate them

Upload: david-gomez-garcia

Post on 10-May-2015

998 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Wtf per lineofcode

Measuring Code Quality: WTF/Minute

Real word examples of code that could give you a strokeand some advices to not replicate them

Page 3: Wtf per lineofcode

Code quality related concepts

Page 4: Wtf per lineofcode

Code Quality: WTFs/lines of code

http://www.osnews.com/story/19266/WTFs_m

Page 5: Wtf per lineofcode

Code smells

A surface indication that usually

corresponds to a deeper problem in

the system

Term coined by Kent Beck

Page 6: Wtf per lineofcode

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

Page 7: Wtf per lineofcode

Examples of real code from the real world

Page 8: Wtf per lineofcode

Health warning!

Page 9: Wtf per lineofcode

CommentsComments are useful, but

only if the add or explain the code.

Don’t describe what the code is doing

Explain why (pre/post-Conditions)

Use cases (for methods/types/functions)

Page 10: Wtf per lineofcode

Unuseful information

Page 11: Wtf per lineofcode

Unuseful comments

/** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { // We will get back to the implementation detail // More fun later }

Page 12: Wtf per lineofcode

Unuseful comments

  /**  Atributo  codCircuito.  */   private  String  codCircuito;

  /**    *  Método  get  codCircuito.    *      *  @return  String    */   public  String  getCodCircuito()  {     return  codCircuito;   }

Page 13: Wtf per lineofcode

Remember to sign your code

////////////////////////ManuelaLogger  log  =  LoggerFactory.getLogger(MyClass.class.getName());////////////////////////

Page 14: Wtf per lineofcode

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(){

Page 15: Wtf per lineofcode

Fooling the reader with comments

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));

Fool the reader by commenting out only the if check

*For the trick to work out, keep the indentation

Page 16: Wtf per lineofcode

Exceptions/ErrorsExceptions are just that: Excepctions

Catch only if you can handle it

Don’t use for

Flow Control

State demarcation (Except error)

Page 17: Wtf per lineofcode

Simply retrhowing exceptions

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;        }}

Page 18: Wtf per lineofcode

NPE Paranoia

It’s better to check twice in order to avoid a NullPointerException

  while  (session  !=  null)  {     numSessions++  ;     if  (session  !=  null)  {

    ...}...

}    

Page 19: Wtf per lineofcode

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 NullPointerException

Extra points if you add Dead code to an else block

Page 20: Wtf per lineofcode

NamingUse descriptive names

Describe what a Class/Function/method does, not what it means

Describe what a variable/attribute holds

Don’t use abreviations

Code for readability

Page 21: Wtf per lineofcode

What does this method do?

       if(  p  !=  null){                applyBusinessLogic(p,estado,manager);        }  else  {

       }

  public  void  onButtonPressed(ActionEvent  e)  {     FormData  formData  =  parseFromEvent(e);     theAlgorithm(formData);   }

Page 22: Wtf per lineofcode

Unnecesary Code

Developers should be lazy

Don’t write code you don’t need

Don’t repeat yourself

Page 23: Wtf per lineofcode

Wrapping well know APIs

public  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);   }

Page 24: Wtf per lineofcode

¿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;

Page 25: Wtf per lineofcode

¿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?

Page 26: Wtf per lineofcode

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 * * 2030

2K 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 * * ? 2030

NODO 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

Page 27: Wtf per lineofcode

SOO - String oriented Programning

/** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { if (numeroPuestos == 0) return "No"; else return "Si"; }

Page 28: Wtf per lineofcode

Taking advice too seriously

Don’t push the recommendations to the limits

StringBuffer 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

Page 29: Wtf per lineofcode

The indentation madness

                                 }                             });                           }                         }                     });                      }                 });               }             }           ]         }       },          ]   });});

Page 30: Wtf per lineofcode

Design principles

Page 31: Wtf per lineofcode

Keep It Simple Stupid!

Page 32: Wtf per lineofcode

Don’t Repeat Yourself

Page 33: Wtf per lineofcode

Separation of Concerns

Page 34: Wtf per lineofcode

1:1Separation Of ConcernsDon’t Repeat Yourself

Page 35: Wtf per lineofcode

Tell, Don’t Ask

Page 36: Wtf per lineofcode

Ensuring Code QualityThe Quality Cycle

Page 37: Wtf per lineofcode

The Quality Cycle

Page 38: Wtf per lineofcode

Checks at intermediary points

Page 39: Wtf per lineofcode

Checks at intermediary points

Page 40: Wtf per lineofcode

Tools: Measure

Page 41: Wtf per lineofcode

Define bussiness key points

Page 42: Wtf per lineofcode

Define alarms

Page 43: Wtf per lineofcode

Get a Dashboard

Page 44: Wtf per lineofcode

Added value

Page 45: Wtf per lineofcode

Some final advices

Page 46: Wtf per lineofcode

Clean  CodeRobert  Mar.n(@unclebob)

John F. Woods, September 1991

Read! Keep your brain healty!

Page 48: Wtf per lineofcode

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

Code for readability

Page 49: Wtf per lineofcode

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

Code for readability

////////////////////////ManuelaLogger  log  =  LogFactory.getLogger(MyClass.class.getName());////////////////////////

(Specially if you have your code signed)

Page 50: Wtf per lineofcode

Q&A