midiendo la calidad de código en wtf/min (revisado eui abril 2014)
Post on 10-May-2015
212 Views
Preview:
TRANSCRIPT
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.
Measuring Code Quality: WTF/min
2
@dgomezg
3
Quality CODE RELATED CONCEPTS
http://www.osnews.com/story/19266/WTFs_m
+
@dgomezg
Measuring Code Quality: WTF/min
5
A surface indication that usually
corresponds to a deeper problem in the
system
Term coined by Kent Beck
CODE SMELL
@dgomezg
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
7
Examples of real code from the real world
8
9
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)
/* */10
Comments are useful, butCOMMENTS
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)
/* */COMMENTS: Unuseful info
@dgomezg
/* */COMMENTS: Unuseful info
/** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { // We will get back to the implementation detail // More fun later }
@dgomezg
/* */COMMENTS: Unuseful info /** Atributo codCircuito. */ private String codCircuito; ! /** * Método get codCircuito. * * @return String */ public String getCodCircuito() { return codCircuito; }
@dgomezg
/* */COMMENTS:
Remember to sign your code////////////////////////Manuela Logger log = LoggerFactory.getLogger(MyClass.class.getName()); ////////////////////////
@dgomezg
/* */COMMENTS:
A good 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.visit-my-web.com/) * */ reset: function(){
@dgomezg
/* */COMMENTS:
FOOL THE code READEr 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@dgomezg
17
Exceptions are just that: ExceptionsExceptions
Catch only if you can handle it
Declare the exact type
Don’t use for: Flow Control
State demarcation (other than Error)
Exceptions: Simply retrowingpublic 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; } }
@dgomezg
Exceptions: NPE PARANOIA
while (session != null) { numSessions++ ; if (session != null) { ... } ...
}
It’s better to check twice to avoid a NullPointerException
@dgomezg
while (session != null) { numSessions++ ; if (session != null) { //.... } else { log.warn("Null session detected.” +
“ Starting session Synchronization"); //.... dead code follows... } }
Exceptions: NPE PARANOIAIt’s better to check twice to avoid a NullPointerException
extra points if you add ‘dead code’ to the else block
@dgomezg
Exceptions: Flow Controlpublic class ProcesoTerminadoCorrectamenteException extends Exception { !}
Man! When a process which right ends is an exception… That’s a good confidence in your system!
@dgomezg
22
NAMINGUse 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
23
NAMING: What does this method do? if( p != null){ applyBusinessLogic(p,estado,manager); }
public void onButtonPressed(ActionEvent e) { FormData formData = parseFromEvent(e); theAlgorithm(formData); }
@dgomezg
24
UnNecessary code
Developers should be lazy
Don’t write code you don’t need
Don’t repeat yourself
25
UnNecessary code: Wrapping well-known APIs
public static String substringBefore(String str,String separator) { return (org.apache.commons.lang.StringUtils
.substringBefore(str, separator)); }
@dgomezg
26
UnNecessary code: Wrapping well-known APIs
public String getPropiedad(String clave) { return wrappedCacheAdmin.getProperty(clave); } public void setClaseAlgoritmo(String clase) { wrappedCacheAdmin.setAlgorithmClass(clase); }
@dgomezg
27
UnNecessary code: 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;
@dgomezg
28
UnNecessary code: Clever? CodeChallenge: Could you tell what will print the following code?
System.out.println(DOS * TRES);
@dgomezg
29
2K Effect… We miss you!
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
@dgomezg
30
UnNecessary code: SOP
/** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { if (numeroPuestos == 0) return "No"; else return "Si"; }
Introducing SOP: String Oriented Programming
@dgomezg
31
UnNecessary code: TAKING ADVICE TOO SERIOUSLY
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!!!@dgomezg
32
UnNecessary code: The indentation MADNESS
} }); } } }); } }); } } ] } }, ] }); });
@dgomezg
33
UnNecessary code: PROTECT YOUR CODE
static OSStatus SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa, SSLBuffer signedParams, uint8_t *signature, UInt16 signatureLen) { OSStatus err; ... ! if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0) goto fail; if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) goto fail; goto fail; if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0) goto fail; ... } // https://www.imperialviolet.org/2014/02/22/applebug.html
34
DESIGN PRICIPLES
35
KEEP IT SIMPLE STUPID!
@dgomezg
36
Don’t Repeat Yourself
@dgomezg
37
Separation OF Concerns
@dgomezg
38
I: I
!
!
!
!
!
SEPARATION OF CONCERNS DON’T REPEAT YOURSELF
@dgomezg
39
ENSURING CODE QUALITY: THE QUALITY CYCLE
40
Default Quality Cycle
@dgomezg
41
Add Intermediate Quality Checks
@dgomezg
42
Automate Intermediate Checks
@dgomezg
43
Measure with tools
@dgomezg
44
Define Business Key Indicators
@dgomezg
45
Define Alarms
@dgomezg
46
Get a Dashboard
@dgomezg
47
Added Value: keeping everybody happy
@dgomezg
48
TOOLS
49
descriptor file +
source code +
Dependency Manager =
Artifact
Automated Build process
50
TDD
http://reddevnews.com/articles/2007/11/01/testdriven-development-tdd.aspx
http://www.doolwind.com/blog/page/3/
51
Jenkins Jobs to automate the build process: - On Events (commit) - Scheduled (cron expression) - Manually (upon request) !
Lots of plugins: - Release - Deploy - Customize dashboard - Trigger other checks
52
SONARQbe (aka SONAR)
53
SOME FINAL ADVICES
54
Read! Keep your brain healthy
Clean Code:
Robert Martin (@unclebob)
55
No Monkeys, No LizardsBe concious, be consequent
www.adictosaltrabajo.com/detalle-‐noticia.php?noticia=356
56
THe Software RUSTING principleThe software degrades slowly and slightly as time passes…
Sometimes is not slowly neither slightly!!
57
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
58
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
59
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()); ////////////////////////
top related