SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
1
CLEAN CODE
El BUEN código es importante
La única forma de cumplir la
entrega -la única forma de ir
rápido- es mantener el código
tan limpio como sea posible
• Código que se lee como si fuera una historia (como
prosa)

• Código que se nota que ha sido escrito con cariño

• Código que (SIMPLE CODE):

• PASA LOS TESTS

• NO TIENE DUPLICIDAD

• EXPRESA LAS IDEAS

• MINIMIZA EL CÓDIGO
El ratio de lectura respecto al de escritura es 10:1

Constantemente leyendo código como parte del
esfuerzo de escribir nuevo código
• Para ir rápido

• Para que el código sea rápido de escribir

• TIENE QUE SER RÁPIDO DE LEER
LA REGLA DEL BOY
SCOUT
Base de código que cada vez es mejor
[PAIR PROGRAMING]
Dos personas un mismo ordenador
El teclado no es el Problema
DRIVER
Escribe
Piensa en alto
NAVIGATOR
No interrumpir
Foco en el objetivo
Ir cambiando
Cansancio
Pérdida de foco
Interrumpir
2
NOMBRES CON SENTIDO
Se da nombre a todo
• Variables

• Funciones

• Argumentos

• Clases

• Paquetes

• Directorios

• Ficheros
Un nombre tiene que tener sentido en si mismo. Por
qué existe y cómo se usa

Si un nombre necesita un comentario entonces no es lo
suficientemente revelador
Qué se mide y cómo se
mide
daysSinceCreation
timeSpanInSeconds
No desinformar
userList
hp para hypotenuse
Conceptos similares de la
misma forma
Series de números
Palabras que añaden ruido
ProductInfo ProductData
Redundantes(variable, table, string, boolean)
Distinguir nombres de tal manera que el lector sepa
qué los diferencia
PALABRAS
Pronunciables
Recordables
Discutibles
genymdhms => generationTimestamp
modymdhms => modificationTimestamp
Nombres buscables
largos

de una letra solo como variable local en métodos pequeños

el tamaño debería ir acorde a su ámbito
NOTACIÓN HÚNGARA
PREFIJOS PARA MIEMBROS
INTEFACES E
IMPLEMENTACIÓN
Nunca -interfaz. Como mucho -impl

La interfaz el concepto (abstracción) -> Implementación la
concreción
CLASES => NOMBRES (NO VERBOS)

EVITAR	MANAGER,	PROCESSOR,	DATA,	INFO	
MÉTODOS => VERBOS (NO VERBOS)

POSTPAYMENT,	DELETEPAYMENT,	SAVE	
GET,	SET,	IS	
VARIOS CONSTRUCTORES => NOMBRES
DESCRIPTIVOS

ARGUMENTOS,	DOMINIO
UNA PALABRA POR CONCEPTO
FETCH,	GET,	FIND,	RETRIEVE	
NO USAR LA MISMA PALABRA PARA DOS
PROPÓSITOS DIFERENTES
CONSISTENCIA
ADD,	INSERT
EL LECTOR NO TIENE QUE TRADUCIR EL
NOMBRE AL CONCEPTO QUE CONOCE
NOMBRES	EN	EL	DOMINIO	DEL	PROBLEMA	
O	
NOMBRES	EN	EL	DOMINIO	DE	LA	SOLUCIÓN
USAR EL CONTEXTO
NO AÑADIR CONTEXTO GRATUITAMENTE
SOCIALUSER	
SCREENPAINTER	
-

NOMBRES CORTOS MEJOR QUE LARGOS.
NO AÑADIR MÁS CONTEXTO/INFORMACIÓN
QUE LA NECESARIA
3
FUNCIONES
PEQUEÑAS
CONTRA MÁS PEQUEÑAS MEJOR
150 LETRAS POR LÍNEA

MÁXIMO 100 LÍNEAS

RECOMENDADO MÁXIMO 20 LÍNEAS

MENOS MEJOR
RECOMENDADO 1 LÍNEA POR BLOQUE

LLAMADA A FUNCIÓN

NIVEL DE INDEXACIÓN COMO MUCHO 2 DENTRO
DE UNA FUNCIÓN

1 MEJOR
Bloques e indentación
HACER UNA SOLA COSA
HACERLA BIEN
HACER SOLO ESO
Extraer funciones hasta que el nombre de la función sea la
descripción de la implementación
Código que se lee como una
narrativa arriba-abajo
Cada vez que bajamos leyendo las funciones, deberíamos
descender un nivel de abstracción

Conjuntos de párrafos TO
SWITCH
Evitarlos. Sino solo llamadas a funciones
Viola SRP y OCP
Polimorfismo y Factorías
NOMBRES
DESCRIPTIVOS
Cambiar tantas veces como haga falta
No importa que sean largos
Que exprese lo que hace, aumentando el nivel de
abstracción
ARGUMENTOS
Cuantos menos mejor

Dificulta entendimiento

MÁXIMO	3	
EVITAR	ARGUMENTOS	DE	SALIDA	
(SI	TIENE	QUE	MODIFICAR	ALGO	QUE	SEA	SU	
PROPIO	CONTENIDO	->	CLASE	O	SE	DEVUELVA)
EVITAR ARGUMENTOS
FLAG
La función hace dos cosas sí o sí
Dificulta entendimiento
Dos funciones
ARGUMENTOS QUE SON OBJETOS
LISTADO DE ARGUMENTOS
FUNCIONES SON VERBOS
ARGUMENTOS SON NOMRES
Tratar que la función explique los
argumentos
EVITAR EFECTOS
COLATERALES
Coupling temporal
Nombre que no transmite el efecto
SEPARACIÓN DE COMANDOS
Y CONSULTAS
O hace algo or responde algo
Sino, hace dos cosas
Mejor dos métodos
EXCEPCIONES MEJOR QUE
RESULTADOS DE ERROR
Código de error: Obliga a manejarlo inmediatamente
Excepciones permiten ser manejadas independientemente
EXCEPCIONES MEJOR QUE
RESULTADOS DE ERROR
Código de error: Obliga a manejarlo inmediatamente
Excepciones permiten ser manejadas independientemente
Manejo de errores en su función propia
NO REPETIR [DRY]
Estructuras (Algoritmos)
Conceptos
VARIOS RETURNS POR FUNCIÓN
No es un problema y ayudan
Si las funciones son pequeñas
ESCRIBIR EL CÓDIGO Y LUEGO REFACTORIZAR
Incluso a veces viene bien recuperar una función muy larga
y volverla a trocear
TESTS

Más contenido relacionado

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

CódigoLimpioImportancia