SlideShare uma empresa Scribd logo
1 de 50
Baixar para ler offline
Measuring Code Quality:
WTF/Minute
Real word examples of code that could give you a stroke
and some advices to not replicate them
About the speaker
David Gómez
Sw Architect & Trainer
dgomezg@autentia.com
@dgomezg
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!
Comments
Comments 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
////////////////////////Manuela
Logger	
  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/Errors
Exceptions 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
Naming
Use 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 * * 2030
cron.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 * * ? 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
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:1
Separation Of Concerns
Don’t RepeatYourself
Tell,
Don’t Ask
Ensuring Code Quality
The 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	
  Code
Robert	
  Mar.n
(@unclebob)
John F. Woods, September 1991
Read! Keep your brain healty!
Be conscious, Be consequent
http://www.adictosaltrabajo.com/detalle-noticia.php?
noticia=356
No monkeys, no lizards
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
////////////////////////Manuela
Logger	
  log	
  =	
  LogFactory.getLogger(MyClass.class.getName());
////////////////////////
(Specially if you have your code signed)
Q&A

Mais conteúdo relacionado

Mais procurados

Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 
Perl exceptions lightning talk
Perl exceptions lightning talkPerl exceptions lightning talk
Perl exceptions lightning talkPeter Edwards
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
C++ exception handling
C++ exception handlingC++ exception handling
C++ exception handlingRay Song
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2ppd1961
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Sharon Levy
 
Elegant Ways of Handling PHP Errors and Exceptions
Elegant Ways of Handling PHP Errors and ExceptionsElegant Ways of Handling PHP Errors and Exceptions
Elegant Ways of Handling PHP Errors and ExceptionsZendCon
 

Mais procurados (20)

Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Clean code
Clean codeClean code
Clean code
 
Listen afup 2010
Listen afup 2010Listen afup 2010
Listen afup 2010
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Perl exceptions lightning talk
Perl exceptions lightning talkPerl exceptions lightning talk
Perl exceptions lightning talk
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
C++ exception handling
C++ exception handlingC++ exception handling
C++ exception handling
 
$Cash
$Cash$Cash
$Cash
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2Handling Exceptions In C & C++ [Part B] Ver 2
Handling Exceptions In C & C++ [Part B] Ver 2
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
 
Exception handling
Exception handlingException handling
Exception handling
 
Elegant Ways of Handling PHP Errors and Exceptions
Elegant Ways of Handling PHP Errors and ExceptionsElegant Ways of Handling PHP Errors and Exceptions
Elegant Ways of Handling PHP Errors and Exceptions
 

Semelhante a Wtf per lineofcode

Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)David Gómez García
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniqueAndrey Karpov
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Rapita Systems Ltd
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob Paulin
 
Your Own Metric System
Your Own Metric SystemYour Own Metric System
Your Own Metric SystemErin Dees
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindAndreas Czakaj
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded cBenux Wei
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone CivettaCocoaHeads France
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio
 
Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentKetan Raval
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
 
Raising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code QualityRaising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code QualityThomas Moulard
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
How to drive a malware analyst crazy
How to drive a malware analyst crazyHow to drive a malware analyst crazy
How to drive a malware analyst crazyMichael Boman
 

Semelhante a Wtf per lineofcode (20)

Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage"
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Your Own Metric System
Your Own Metric SystemYour Own Metric System
Your Own Metric System
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
Clean code
Clean codeClean code
Clean code
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
Clean code
Clean codeClean code
Clean code
 
Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application Development
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Raising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code QualityRaising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code Quality
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
How to drive a malware analyst crazy
How to drive a malware analyst crazyHow to drive a malware analyst crazy
How to drive a malware analyst crazy
 

Mais de David Gómez García

Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022David Gómez García
 
Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...David Gómez García
 
Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...David Gómez García
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
 
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021David Gómez García
 
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationCdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationDavid Gómez García
 
What's in a community like Liferay's
What's in a community like Liferay'sWhat's in a community like Liferay's
What's in a community like Liferay'sDavid Gómez García
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
 
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRDavid Gómez García
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring SessionDavid Gómez García
 
Construccion de proyectos con gradle
Construccion de proyectos con gradleConstruccion de proyectos con gradle
Construccion de proyectos con gradleDavid Gómez García
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. David Gómez García
 
El poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaEl poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaDavid Gómez García
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingDavid Gómez García
 
A real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbA real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbDavid Gómez García
 

Mais de David Gómez García (20)

Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022
 
Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...
 
Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
 
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationCdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
 
What's in a community like Liferay's
What's in a community like Liferay'sWhat's in a community like Liferay's
What's in a community like Liferay's
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Construccion de proyectos con gradle
Construccion de proyectos con gradleConstruccion de proyectos con gradle
Construccion de proyectos con gradle
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min.
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
Gradle como alternativa a maven
Gradle como alternativa a mavenGradle como alternativa a maven
Gradle como alternativa a maven
 
El poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaEl poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesanía
 
Geo-SentimentZ
Geo-SentimentZGeo-SentimentZ
Geo-SentimentZ
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript Scripting
 
A real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbA real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodb
 

Wtf per lineofcode

  • 1. Measuring Code Quality: WTF/Minute Real word examples of code that could give you a stroke and some advices to not replicate them
  • 2. About the speaker David Gómez Sw Architect & Trainer dgomezg@autentia.com @dgomezg
  • 4. Code Quality:WTFs/lines of code http://www.osnews.com/story/19266/WTFs_m
  • 5. Code smells A surface indication that usually corresponds to a deeper problem in the system Term coined by Kent Beck
  • 6. 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
  • 7. Examples of real code from the real world
  • 9. Comments Comments 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)
  • 11. Unuseful comments /** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { // We will get back to the implementation detail // More fun later }
  • 12. Unuseful comments   /**  Atributo  codCircuito.  */   private  String  codCircuito;   /**    *  Método  get  codCircuito.    *      *  @return  String    */   public  String  getCodCircuito()  {     return  codCircuito;   }
  • 13. Remember to sign your code ////////////////////////Manuela Logger  log  =  LoggerFactory.getLogger(MyClass.class.getName()); ////////////////////////
  • 14. 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(){
  • 15. 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
  • 16. Exceptions/Errors Exceptions are just that: Excepctions Catch only if you can handle it Don’t use for Flow Control State demarcation (Except error)
  • 17. 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;        } }
  • 18. NPE Paranoia It’s better to check twice in order to avoid a NullPointerException   while  (session  !=  null)  {     numSessions++  ;     if  (session  !=  null)  {     ... } ... }    
  • 19. 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
  • 20. Naming Use 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
  • 21. What does this method do?        if(  p  !=  null){                applyBusinessLogic(p,estado,manager);        }  else  {        }   public  void  onButtonPressed(ActionEvent  e)  {     FormData  formData  =  parseFromEvent(e);     theAlgorithm(formData);   }
  • 22. Unnecesary Code Developers should be lazy Don’t write code you don’t need Don’t repeat yourself
  • 23. 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);   }
  • 24. ¿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;
  • 25. ¿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?
  • 26. 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 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 * * ? 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
  • 27. SOO - String oriented Programning /** * Método get Disponibilidad. * * @return Returns the disponibilidad. */ public String getDisponibilidad() { if (numeroPuestos == 0) return "No"; else return "Si"; }
  • 28. 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
  • 29. The indentation madness                                  }                             });                           }                         }                     });                      }                 });               }             }           ]         }       },          ]   }); });
  • 31. Keep It Simple Stupid!
  • 36. Ensuring Code Quality The Quality Cycle
  • 46. Clean  Code Robert  Mar.n (@unclebob) John F. Woods, September 1991 Read! Keep your brain healty!
  • 47. Be conscious, Be consequent http://www.adictosaltrabajo.com/detalle-noticia.php? noticia=356 No monkeys, no lizards
  • 48. 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
  • 49. 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 ////////////////////////Manuela Logger  log  =  LogFactory.getLogger(MyClass.class.getName()); //////////////////////// (Specially if you have your code signed)
  • 50. Q&A