+ All Categories
Home > Technology > Measuring Code Quality in WTF/min.

Measuring Code Quality in WTF/min.

Date post: 10-May-2015
Category:
Upload: david-gomez-garcia
View: 1,502 times
Download: 2 times
Share this document with a friend
Description:
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.
Popular Tags:
56
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 2013
Transcript
Page 1: Measuring Code Quality in WTF/min.

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 2013!

Page 2: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�2

@dgomezg

Page 3: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�3

Quality CODE RELATED CONCEPTS

@dgomezg

Page 4: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�4

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

@dgomezg

Page 5: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�5

A surface indication that usually

corresponds to a deeper problem in the

system

Term coined by Kent Beck

CODE SMELL

@dgomezg

Page 6: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�6

You write code for a computer to read

Some Misconceptions

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

@dgomezg

Page 7: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�6

You write code for a computer to read

Some Misconceptions

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

@dgomezg

Page 8: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�6

You write code for a computer to read

Some Misconceptions

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

@dgomezg

Page 9: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�6

You write code for a computer to read

Some Misconceptions

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

@dgomezg

Page 10: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�7

Examples of real code from the real world

@dgomezg

Page 11: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�8

@dgomezg

Page 12: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�9

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

Page 13: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

�10

Comments are useful, butCOMMENTS

@dgomezg

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)

Page 14: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

COMMENTS: Unuseful info

@dgomezg

Page 15: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

COMMENTS: Unuseful info

@dgomezg

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

Page 16: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

COMMENTS: Unuseful info

@dgomezg

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

Page 17: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

COMMENTS: Remember to sign your code

@dgomezg

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

Page 18: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

COMMENTS: A good marketing tool

@dgomezg

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

Page 19: Measuring Code Quality in WTF/min.

/*        */Measuring Code Quality: WTF/min

Leganés!6-7 Febrero 2014

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

Page 20: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�17

Exceptions are just that: ExceptionsExceptions

@dgomezg

Catch only if you can handle it

Declare the exact type

Don’t use for: Flow Control

State demarcation (other than Error)

Page 21: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

Exceptions: Simply retrowing

@dgomezg

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 22: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

Exceptions: NPE PARANOIA

@dgomezg

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

}    

It’s better to check twice to avoid a NullPointerException

Page 23: Measuring Code Quality in WTF/min.

while (session != null) { numSessions++ ; if (session != null) { //.... } else { log.warn("Null session detected.” +

“ Starting session Synchronization"); //.... dead code follows... } }

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

Exceptions: NPE PARANOIA

@dgomezg

It’s better to check twice to avoid a NullPointerException

extra points if you add ‘dead code’ to the else block

Page 24: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

Exceptions: Flow Control

@dgomezg

public  class  ProcesoTerminadoCorrectamenteException                            extends  Exception  {  !}  

Man! When a process which right ends is an exception… That’s a good confidence in your system!

Page 25: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�22

NAMING

@dgomezg

Use descriptive names

Describe what a Class/function/method does, not what it means Describe what a variable/attribute holdsDon’t use abbreviations

Code for readability

Page 26: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�23

NAMING: What does this method do?

@dgomezg

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

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

Page 27: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�24

UnNecessary code

@dgomezg

Developers should be lazy

Don’t write code you don’t need

Don’t repeat yourself

Page 28: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�25

UnNecessary code: Wrapping well-known APIs

@dgomezg

public  static  String  substringBefore(String  str,String  separator)  {          return  (org.apache.commons.lang.StringUtils  

.substringBefore(str,  separator));  }  

Page 29: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�26

UnNecessary code: Wrapping well-known APIs

@dgomezg

  public  String  getPropiedad(String  clave)  {       return  wrappedCacheAdmin.getProperty(clave);     }         public  void  setClaseAlgoritmo(String  clase)  {       wrappedCacheAdmin.setAlgorithmClass(clase);     }  

Page 30: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�27

UnNecessary code: Clever? Code

@dgomezg

       /**  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 31: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�28

UnNecessary code: Clever? Code

@dgomezg

Challenge: Could you tell what will print the following code?

    System.out.println(DOS  *  TRES);

Page 32: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�29

2K Effect… We miss you!

@dgomezg

NODO 4 !!# Planificacion Procesos Batch # (Formato ss mm hh dd MM yyyy) # cron.sync=0 00 12 * * ? cron.download=0 00 12 * * 2030 cron.reports=0 00 12 * * 2030

NODO 3 !# Planificacion Procesos Batch # (Formato ss mm hh dd MM yyyy) # cron.sync=0 00 16 * * ? cron.download=0 00 03 * * ? 2030 cron.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 * * ? 2030 cron.reports=0 00 23 * * ? 2030

Page 33: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�30

UnNecessary code: SOP

@dgomezg

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

Introducing SOP: String Oriented Programming

Page 34: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�31

UnNecessary code: TAKING ADVICE TOO SERIOUSLY

@dgomezg

String concatenation in Java is not recommended. Use StringBuffer or StringBuilder insteadStringBuffer hql = new StringBuffer("select distinct config from Config config ");

Query query = session.createQuery(hql.toString()) ;

Don’t push the recommendations to the limits!!!

Page 35: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�32

UnNecessary code: The indentation MADNESS

@dgomezg

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

Page 36: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�33

DESIGN PRICIPLES

@dgomezg

Page 37: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�34

KEEP IT SIMPLE STUPID!

@dgomezg

Page 38: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�35

Don’t Repeat Yourself

@dgomezg

Page 39: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�36

Separation OF Concerns

@dgomezg

Page 40: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�37

I: I

!

!

!

!

!

SEPARATION OF CONCERNS DON’T REPEAT YOURSELF

@dgomezg

Page 41: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�38

ENSURING CODE QUALITY: THE QUALITY CYCLE

@dgomezg

Page 42: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�39

@dgomezg

Default Quality Cycle

Page 43: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�40

@dgomezg

Add Intermediate Quality Checks

Page 44: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�41

@dgomezg

Automate Intermediate Checks

Page 45: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�42

@dgomezg

Measure with tools

Page 46: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�43

@dgomezg

Define Business Key Indicators

Page 47: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�44

@dgomezg

Define Alarms

Page 48: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�45

@dgomezg

Get a Dashboard

Page 49: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�46

@dgomezg

Added Value: keeping everybody happy

Page 50: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�47

SOME FINAL ADVICES

@dgomezg

Page 51: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�48

Read! Keep your brain healthy

@dgomezg

Clean Code:

Robert Martin (@unclebob)

Page 52: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�49

No Monkeys, No Lizards

@dgomezg

Be concious, be consequent

www.adictosaltrabajo.com/detalle-­‐noticia.php?noticia=356

Page 53: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�50

@dgomezg

THe Software RUSTING principleThe software degrades slowly and slightly as time passes…

Sometimes is not slowly neither slightly!!

Page 54: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�51

@dgomezg

The boy scout ruleTry 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

Page 55: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�52

@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

Page 56: Measuring Code Quality in WTF/min.

Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014

�53

@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());  ////////////////////////


Recommended