Wtf per lineofcode

Post on 10-May-2015

983 views 1 download

Tags:

transcript

Measuring Code Quality: WTF/Minute

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

Code quality related concepts

Code Quality: WTFs/lines of code

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

Code smells

A surface indication that usually

corresponds to a deeper problem in

the system

Term coined by Kent Beck

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

Examples of real code from the real world

Health warning!

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)

Unuseful information

Unuseful comments

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

Unuseful comments

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

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

Remember to sign your code

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

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

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

Exceptions/ErrorsExceptions are just that: Excepctions

Catch only if you can handle it

Don’t use for

Flow Control

State demarcation (Except error)

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

NPE Paranoia

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

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

    ...}...

}    

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

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

What does this method do?

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

       }

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

Unnecesary Code

Developers should be lazy

Don’t write code you don’t need

Don’t repeat yourself

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

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

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

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

SOO - String oriented Programning

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

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

The indentation madness

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

Design principles

Keep It Simple Stupid!

Don’t Repeat Yourself

Separation of Concerns

1:1Separation Of ConcernsDon’t Repeat Yourself

Tell, Don’t Ask

Ensuring Code QualityThe Quality Cycle

The Quality Cycle

Checks at intermediary points

Checks at intermediary points

Tools: Measure

Define bussiness key points

Define alarms

Get a Dashboard

Added value

Some final advices

Clean  CodeRobert  Mar.n(@unclebob)

John F. Woods, September 1991

Read! Keep your brain healty!

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

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)

Q&A