SlideShare a Scribd company logo
1 of 32
By Java Curiosities
Prologo ,[object Object]
Comparación ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Como vemos es recomendable usar primero las constantes en las comparaciones y de esta forma nos evitamos un posible NullPointerException.
Instanciación ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Usando los métodos valueOf de las clases Wrapper, se gana en performance ya que muchas veces se usan diversas técnicas de optimización.
Concatenación ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Cuando pensamos concatenar varios String es recomendable usar la clase StringBuilder o StringBuffer que hacen esta tarea con mayor performance. Debemos considerar que usar los Builder debe aplicar donde tenemos gran cantidad de concatenaciones.
Comparación ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Si queremos saber si un String es igual a “” es recomendable usar el método length() ya que se nota una leve mejora de performance en este.
Exceptions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Cuando capturamos excepciones debemos considerar como mínimo loquear la información y arrojar la misma excepción o arrojar alguna otra excepción mas relacionada con las lógica de negocio. “Si tenemos varios bloques catch habría que tenerlos acomodados de formas de mas especifica hacia menos especifico.”
Check Null ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Debemos chequear los objetos que nos retorna un método para ver si no han vuelto en Null así de esta manera evitamos un posible NullPointerException.
Program to an interface, not an implementations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Es mejor referirse a interfaces ya que es mucho mas genérico y además nos permite cambiar la implementación, si a esto le sumamos DI (Inyección de Dependencia) logramos un código mucho mas desacoplado.
Iterate Map with Entry ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Cuando iteramos un Map es mejor iterar sobre los Entry del mismo y de este modo ya poseemos la key y el value encapsulado en ese objeto de manera que ahorramos algunas operaciones y ganamos performance.
Try – Catch Performance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Siempre que se pueda evitar los try – catch dentro de un loop es recomendable hacerlo ya que así ganaremos un poco mas de performance del código.
A Method – An Action ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Como veremos en las convecciones de Sun es recomendable que el nombre de un método sea un verbo + sustantivo para representar su acción, aquí vemos un ejemplo donde un método cumple dos acciones las cuales podrían ser separadas para su mayor compresión.
Restrict Arguments - Enums ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities De esta manera conseguimos restringir nuestros métodos para que solo reciban la información que pueden manejar si recibimos un int este podría ser cualquier valor en cambio al recibir el Enum solo podremos manejar los que estén definidos.
Compile Regular Expressions Once ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Si utilizamos la clase Matcher notaremos una gran diferencia de performance al momento de chequear las coincidencias de los textos.
Self - encapsulation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Algunas veces puede ser útil usar la auto - encapsulación para poder sincronizar los atributos, hacer inicializaciones perezosas, permitir a los subclases que sobreescriban cierto comportamiento.
Avoid Raw Types ,[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Es recomendable usar Parameterezid Type ya que no necesitan casteo y también brindan auto documentación además de brindar un tipado seguro. Los Raw Types fueron conservados por un tema de compatibilidad pero esto no quiere decir que debamos usarlos.
Use final liberally ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Al usar el keyword final estamos asegurando que esta referencia nunca se cambiaria durante ese bloque de código y esto genera menos trabajo de chequeo para el compilador.
Use static imports rarely ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Los static import muchas veces son útil pero puede restar legibilidad al código, son recomendables para el que los usamos con constantes, que ahí facilitan la lectura pero en el caso de ejecución de métodos pasa al contrario porque puede llevar a suponer cosas incorrectas.
Validate methods argument ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Se recomienda validar los argumentos de los métodos públicos en base a NullPointerException, IllegalArgumentException o IllegalStateException que son subclases de RuntimeException, en cambio para los métodos privados se puede usar assert ya que estos al ser llamados desde dentro de la clase deberían llegar con los parámetros correctos.
Stop threads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Cuando queremos frenar un Thread poseemos los metodos stop o suspend pero estos estan deprecados y no deben usarse, en cambio hay que usar una variable privada con sus metodos sincronizados para poder saber si debemos detener el Thread.
Class for constants ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities Usualmente creamos nuestras constantes en una interface o una clase, pero para poder realizar bien esta practica deberíamos usar una clase que sea final y tenga su constructor privado además de esta manera es una muy buena candidata para el uso de static import.
Collections ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Package by feature, not layer ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
BigDecimal + Precision ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities RoundingMode
Equals y HashCode ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Clean Code ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Do not break portability ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Use Javadoc ,[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Convenciones Java Sun I ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Convenciones Java Sun II ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Convenciones Java Sun III ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Best Practices – Java Curiosities
Fin ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

More Related Content

What's hot

Control Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptxControl Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptx
BansalShrivastava
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

What's hot (20)

Preprocessors
Preprocessors Preprocessors
Preprocessors
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
File system node js
File system node jsFile system node js
File system node js
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
Control Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptxControl Structure in JavaScript (1).pptx
Control Structure in JavaScript (1).pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Open source apm scouter를 통한 관제 관리 jadecross 정환열 수석
Open source apm scouter를 통한 관제  관리 jadecross 정환열 수석Open source apm scouter를 통한 관제  관리 jadecross 정환열 수석
Open source apm scouter를 통한 관제 관리 jadecross 정환열 수석
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in Java
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Linker and loader upload
Linker and loader   uploadLinker and loader   upload
Linker and loader upload
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
File handling in c
File handling in c File handling in c
File handling in c
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Zio in real world
Zio in real worldZio in real world
Zio in real world
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

Similar to Best Practices

Junit y Jmock
Junit y JmockJunit y Jmock
Junit y Jmock
kaolong
 
Guia demanejodeexcepcionesaserciones
Guia demanejodeexcepcionesasercionesGuia demanejodeexcepcionesaserciones
Guia demanejodeexcepcionesaserciones
jbersosa
 
Unit Testing - GTUG
Unit Testing - GTUGUnit Testing - GTUG
Unit Testing - GTUG
Jordi Gerona
 
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
Videoconferencias UTPL
 

Similar to Best Practices (20)

métodos procedimimientos estructuras de control java
métodos procedimimientos estructuras de control javamétodos procedimimientos estructuras de control java
métodos procedimimientos estructuras de control java
 
Junit y Jmock
Junit y JmockJunit y Jmock
Junit y Jmock
 
¿Cómo mantener tu javascript?: Buenas prácticas
¿Cómo mantener tu javascript?: Buenas prácticas¿Cómo mantener tu javascript?: Buenas prácticas
¿Cómo mantener tu javascript?: Buenas prácticas
 
Jyoc java-cap02 bifurcaciones
Jyoc java-cap02 bifurcacionesJyoc java-cap02 bifurcaciones
Jyoc java-cap02 bifurcaciones
 
Java argumentos variables
Java argumentos variablesJava argumentos variables
Java argumentos variables
 
Manuales ...
Manuales ...Manuales ...
Manuales ...
 
Guia demanejodeexcepcionesaserciones
Guia demanejodeexcepcionesasercionesGuia demanejodeexcepcionesaserciones
Guia demanejodeexcepcionesaserciones
 
6 Upv Solo Pruebas 2009
6 Upv Solo Pruebas 20096 Upv Solo Pruebas 2009
6 Upv Solo Pruebas 2009
 
SCJP, Clase 6: Collections
SCJP, Clase 6: CollectionsSCJP, Clase 6: Collections
SCJP, Clase 6: Collections
 
Java básico
Java  básicoJava  básico
Java básico
 
Metodos,variables, pasodeparametros
Metodos,variables, pasodeparametrosMetodos,variables, pasodeparametros
Metodos,variables, pasodeparametros
 
Unit Testing - GTUG
Unit Testing - GTUGUnit Testing - GTUG
Unit Testing - GTUG
 
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
 
Java 8 introducción a expresiones lambdas y api stream
Java 8  introducción a expresiones lambdas y api streamJava 8  introducción a expresiones lambdas y api stream
Java 8 introducción a expresiones lambdas y api stream
 
02 Bases Del Lenguaje Java
02   Bases Del Lenguaje Java02   Bases Del Lenguaje Java
02 Bases Del Lenguaje Java
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
 
Java
JavaJava
Java
 
Unidad 5: Excepciones Ejercicio 3
Unidad 5: Excepciones Ejercicio 3Unidad 5: Excepciones Ejercicio 3
Unidad 5: Excepciones Ejercicio 3
 
sentenciareturnymetodos
sentenciareturnymetodossentenciareturnymetodos
sentenciareturnymetodos
 
Programación Java
Programación JavaProgramación Java
Programación Java
 

More from Luis Miguel De Bello

More from Luis Miguel De Bello (20)

Java Web Services - REST
Java Web Services - RESTJava Web Services - REST
Java Web Services - REST
 
Java Web Services - SOAP Temas Adicionales
Java Web Services - SOAP Temas AdicionalesJava Web Services - SOAP Temas Adicionales
Java Web Services - SOAP Temas Adicionales
 
Java Web Services - SOAP Binding
Java Web Services - SOAP BindingJava Web Services - SOAP Binding
Java Web Services - SOAP Binding
 
Java Web Services - Introduccion
Java Web Services - IntroduccionJava Web Services - Introduccion
Java Web Services - Introduccion
 
Java Web - JSF
Java Web - JSFJava Web - JSF
Java Web - JSF
 
Java Web - Struts
Java Web - StrutsJava Web - Struts
Java Web - Struts
 
Java Web - JSP
Java Web - JSPJava Web - JSP
Java Web - JSP
 
Java Web - Servlet
Java Web - ServletJava Web - Servlet
Java Web - Servlet
 
Base de datos - Clase 2
Base de datos - Clase 2Base de datos - Clase 2
Base de datos - Clase 2
 
Base de datos - Clase 3
Base de datos - Clase 3Base de datos - Clase 3
Base de datos - Clase 3
 
Base de datos - Clase 1
Base de datos - Clase 1Base de datos - Clase 1
Base de datos - Clase 1
 
Base de datos - Clase 4
Base de datos - Clase 4Base de datos - Clase 4
Base de datos - Clase 4
 
Java Web - Session
Java Web - SessionJava Web - Session
Java Web - Session
 
Java Web - Introduccion
Java Web - IntroduccionJava Web - Introduccion
Java Web - Introduccion
 
Sockets TCP
Sockets TCPSockets TCP
Sockets TCP
 
Sockets UDP
Sockets UDPSockets UDP
Sockets UDP
 
Thread 02
Thread 02Thread 02
Thread 02
 
Thread 01
Thread 01Thread 01
Thread 01
 
Log4J
Log4JLog4J
Log4J
 
Administración de memoria en java
Administración de memoria en javaAdministración de memoria en java
Administración de memoria en java
 

Recently uploaded

redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
nicho110
 

Recently uploaded (12)

PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxPROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
 
investigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXIinvestigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXI
 
Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvana
 
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptxEL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
EL CICLO PRÁCTICO DE UN MOTOR DE CUATRO TIEMPOS.pptx
 
Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
 
Buenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptxBuenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptx
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estos
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.
 
redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
 

Best Practices

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.