Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Clean Code
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
370
Diet View Controllers
barbosa
0
230
CocoaPods: The dependency manager for Objective-C projects
barbosa
0
65
Parse
barbosa
0
140
Introduction to Object
barbosa
0
74
git-flow: a successful branching model
barbosa
4
100
Git: The fast version control system
barbosa
0
250
Other Decks in Programming
See All in Programming
AI時代の仕事技芸論 — ソフトウェア開発で「遊ぶように働く」職人的熟達のすすめ
kuranuki
2
680
ECSアプリログをFireLensでコスト削減しようとしたけど諦めた話 in Fargate×Node.js
akihisaikeda
2
4.2k
タクシーアプリ『GO』の バックエンド開発のおける AI利活用と若者のすべて
pyama86
3
2k
IBM Bobを活用したレガシーアプリの最新化
oniak3ibm
PRO
1
200
「なぜそう決めたのか」を残し続ける仕組み ― Notion AI カスタムエージェント × Slack連携による設計判断の自動記録 - NIKKEI Tech Talk #47
niftycorp
PRO
0
170
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.7k
ローカルLLMを使ってB2Bサービスを作っていての学び
yaotti
0
170
AIで効率化できた業務・日常
ochtum
0
130
JavaDoc 再入門
nagise
1
350
The NotImplementedError Problem in Ruby
koic
1
780
技術記事、AIに書かせるか、自分で書くか? 〜それでも私が自分の手で書く理由〜 / #QiitaConference
jnchito
2
1.4k
Datadog × OpenTelemetry 入門と実践のあいだ
kn_to_maxpno
1
160
Featured
See All Featured
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.2k
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
420
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.3k
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
1
3.6k
ラッコキーワード サービス紹介資料
rakko
1
3.6M
Leading Effective Engineering Teams in the AI Era
addyosmani
9
2k
Test your architecture with Archunit
thirion
1
2.3k
Mobile First: as difficult as doing things right
swwweet
225
10k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
360
30k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.5k
AI in Enterprises - Java and Open Source to the Rescue
ivargrimstad
0
1.3k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.5k
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