Measuring Code Quality in WTF/min.
-
Upload
david-gomez-garcia -
Category
Technology
-
view
1.503 -
download
2
description
Transcript of 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!
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�2
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�3
Quality CODE RELATED CONCEPTS
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�4
http://www.osnews.com/story/19266/WTFs_m
@dgomezg
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
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
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
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
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
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�7
Examples of real code from the real world
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�8
@dgomezg
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)
/* */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)
/* */Measuring Code Quality: WTF/min
Leganés!6-7 Febrero 2014
COMMENTS: Unuseful info
@dgomezg
/* */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 }
/* */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; }
/* */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()); ////////////////////////
/* */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(){
/* */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
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)
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; } }
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
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
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!
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
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); }
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
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)); }
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); }
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;
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);
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
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
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!!!
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�32
UnNecessary code: The indentation MADNESS
@dgomezg
} }); } } }); } }); } } ] } }, ] }); });
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�33
DESIGN PRICIPLES
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�34
KEEP IT SIMPLE STUPID!
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�35
Don’t Repeat Yourself
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�36
Separation OF Concerns
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�37
I: I
!
!
!
!
!
SEPARATION OF CONCERNS DON’T REPEAT YOURSELF
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�38
ENSURING CODE QUALITY: THE QUALITY CYCLE
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�39
@dgomezg
Default Quality Cycle
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�40
@dgomezg
Add Intermediate Quality Checks
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�41
@dgomezg
Automate Intermediate Checks
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�42
@dgomezg
Measure with tools
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�43
@dgomezg
Define Business Key Indicators
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�44
@dgomezg
Define Alarms
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�45
@dgomezg
Get a Dashboard
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�46
@dgomezg
Added Value: keeping everybody happy
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�47
SOME FINAL ADVICES
@dgomezg
Measuring Code Quality: WTF/minLeganés!6-7 Febrero 2014
�48
Read! Keep your brain healthy
@dgomezg
Clean Code:
Robert Martin (@unclebob)
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
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!!
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
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
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()); ////////////////////////