Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Clean Code
Search
Gustavo Barbosa
June 20, 2012
Programming
140
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Clean Code
Talk given to my colleagues at Quatix.
Gustavo Barbosa
June 20, 2012
More Decks by Gustavo Barbosa
See All by Gustavo Barbosa
Arquitetura de Apps em Cenários Offline
barbosa
2
380
Diet View Controllers
barbosa
0
230
CocoaPods: The dependency manager for Objective-C projects
barbosa
0
68
Parse
barbosa
0
140
Introduction to Object
barbosa
0
78
git-flow: a successful branching model
barbosa
4
110
Git: The fast version control system
barbosa
0
250
Other Decks in Programming
See All in Programming
残高管理から台帳サービスへの進化
artoy
1
200
ハーネス設計入門 〜 基礎知識の整理から実務へのステップアップ 〜
kinopeee
28
32k
Simple Storage Service(S3) is not simple
iwatsukayura
0
290
JAWS-UG 東京支部が始める、JAWS-UG支部コラボ / JAWS-UG lunchtime LT Collaboration
y0hgi
0
270
Verilogで学ぶCPU自作入門
uyuki234
8
4.1k
[Dev Group Paris Octobre 26] Agentforce, SIforce, Claudeforce, Slackbot… on s'y retrouve ?
nabondance
0
110
設計次第でAIコードの読む量は減らせる / designing-for-code-reading
minodriven
35
17k
複雑なUIコンポーネントとの ⻑い付き合い⽅:波及するバグからテスト戦略を経て、安全な再設計へ
mixplace
0
410
気持ちぃ〜角丸 Squircle
ryu1013
0
310
IBM Bob でAI駆動開発『QC-Playbook』
ichirokano2
0
110
C#の現在地 進化の歴史と、AI時代の.NET Everywhere
neuecc
5
5.2k
npm との違いを手がかりにGo の依存管理を理解したい
optim
0
290
Featured
See All Featured
Facilitating Awesome Meetings
lara
57
7.2k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.6k
Building Better People: How to give real-time feedback that sticks.
wjessup
370
20k
Conquering PDFs: document understanding beyond plain text
inesmontani
PRO
4
3.2k
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
2
2.9k
Building the Perfect Custom Keyboard
takai
2
910
Scaling GitHub
holman
464
140k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.6k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
280
Building a Modern Day E-commerce SEO Strategy
aleyda
45
9.3k
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
730
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
1
630
Transcript
CLEAN CODE escrevendo código limpo
DISCLAIMER
OVERVIEW
SOBRE O QUE FALAREI • nomenclaturas • funções • classes
• formatação • comentários • objetos • estrutura de dados • tratamento de exceções • boundaries • unit testing
SOBRE O QUE NÃO FALAREI • dependency injection • TDD
• refactoring • emergência • concorrência • frameworks de teste • JUnit
fonte: http://www.osnews.com/story/19266/WTFs_m
O QUE É UM CÓDIGO LIMPO? • direto ao ponto
• mínimas dependências • sem duplicação • fácil manutenção • padrões definidos • de fácil leitura/entendimento • coberto de testes • elegante
“NÃO SOU UM EXCELENTE DESENVOLVEDOR. SOU APENAS UM DESENVOLVEDOR MEDIANO
QUE SEGUE À RISCA AS BOAS PRÁTICAS DE UM CÓDIGO LIMPO.” (um dev muito famoso)
NOMES SIGNIFICATIVOS !
NOMES SIGNIFICATIVOS
USEM NOMES QUE REVELEM A INTENÇÃO
NOMES SIGNIFICATIVOS
USEM NOMES PRONUNCIÁVEIS
NOMES SIGNIFICATIVOS
USEM NOMES BUSCÁVEIS
NOMES SIGNIFICATIVOS
TAMBÉM NOMEAMOS CLASSES E MÉTODOS
NOMES SIGNIFICATIVOS CLASSES MÉTODOS em geral, classes devem ser representadas
por substantivos, não verbos. bons exemplos: Cliente, Perfil, Estoque, etc. em geral, métodos devem ser representadas por verbos ou frases verbais bons exemplos: enviarPagamento, removerPagina, salvar, etc. (prefira o infinitivo)
NÃO SEJA PIADISTA :)
FUNÇÕES !
SEJA PEQUENO
•menos é sempre mais! •extraia trechos em métodos privados •lembre-se
dos nomes significativos ;) •vá direto ao ponto FUNÇÕES
FUNÇÕES
FAÇA UMA ÚNICA COISA
•repare a endentação (sim, é assim que escreve ;) •muitos
níveis ~= muita responsabilidade •o método deve fazer uma única coisa, e bem! •dá para extrair? está fazendo mais de uma coisa FUNÇÕES
LEIA O CÓDIGO DE CIMA PARA BAIXO
•seu código deve ser lido como uma narrativa •temos sujeitos,
verbos e predicados :) •narrativas são frases com uma ordem coerente •lembre-se disso ao extrair em métodos privados FUNÇÕES
FUNÇÕES E SEUS ARGUMENTOS
•muitos argumentos ~= code smell •existem algumas regras para qtd
de argumentos •argumentos booleanos em geral não são bons •ex: FUNÇÕES
FUNÇÕES
EVITE OS SIDE EFFECTS
FUNÇÕES
EXCEÇÕES SÃO MELHORES QUE CÓDIGOS DE ERRO
FUNÇÕES
DRY (DON’T REPEAT YOURSELF)
COMENTÁRIOS !
COMENTÁRIOS NÃO AJUDAM UM CÓDIGO SUJO
•em geral, servem para explicar um código ruim •um bom
código é auto-documentado COMENTÁRIOS •extraia para um método que faça o que diz!
COMENTÁRIOS ACEITÁVEIS
•comentários sobre licença •comentários informativos •necessidade de explicação de intenção
(negócio) COMENTÁRIOS
COMENTÁRIOS RUINS
•por falta do que escrever •redundantes •doc em APIs não-públicas
•dizendo algo que o próprio código deveria dizer •código comentado :/ COMENTÁRIOS
COMENTÁRIOS
FORMATAÇÃO !
O QUE VALE É A REGRA DO TIME
MAS EXISTEM ALGUNS PADRÕES DE LINGUAGENS
PYTHON: PEP8
E JAVASCRIPT?
LIMITES HORIZONTAIS
ENDENTAÇÃO, QUEBRA DE LINHAS E TERNÁRIOS
E O IDIOMA?
OBJETOS E ESTRUTRA DE DADOS
ABSTRAÇÃO DE DADOS
None
None
•objetos expõem comportamentos e escondem dados •estruturas de dados expõem
seus dados e não têm comportamentos significativos OBJETOS E ESTRUTURAS DE DADOS
A LEI DE DEMETER
•um método f de uma classe C só conhece: •métodos
de C •objetos criados por f •objetos passados como argumentos para f •objetos em variáveis de instância de C OBJETOS E ESTRUTURAS DE DADOS
None
TRATAMENTO DE ERRO
EXCEÇÕES AO INVÉS DE CÓDIGO DE ERRO ;)
TRATAMENTO DE EXCEÇÃO É UMA DAS COISAS QUE UMA FUNÇÃO/MÉTODO
FAZ
None
NÃO USE EXCEÇÕES GENÉRICAS
VOCÊ TAMBÉM PODE CRIAR EXCEÇÕES!
NÃO RETORNE NULL
None
NÃO PASSE NULL
CLASSES !
BASICAMENTE AS MESMAS DICAS DE FUNÇÕES ;)
PARTIU ALMOÇAR? ! :D
MUITO OBRIGADO @gustavocsb