O documento discute princípios de escrita de código limpo, incluindo a importância de nomes significativos, funções focadas em uma única tarefa, uso apropriado de comentários, e formatação de código para melhor legibilidade.
9. Utilize nomes que revelem a intenção
Escrevendo Código Limpo | LidianeTaquehara
int d; // tempo decorrido em dias
int tempoDecorridoEmDias;
int diasAposCriacao;
int diasAposModificacao;
10. Faça distinções significativas
Escrevendo Código Limpo | LidianeTaquehara
public static void copiarCaracteres(char
a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
}
11. Faça distinções significativas
Escrevendo Código Limpo | LidianeTaquehara
public static void copiarCaracteres(char
origem[], char destino[]) {
for (int i = 0; i < origem.length;
i++) {
destino[i] = origem[i];
}
}
12. Escrevendo Código Limpo | LidianeTaquehara
Funções
Devem executar uma ação
Devem executá-la bem
Devem executar somente isso
13. Funções devem executar uma única ação
Escrevendo Código Limpo | LidianeTaquehara
public static String
renderizarPaginaComConfiguracoes(PageDate
pageData, boolean isSuite) throws Exception
{
if (eUmaPaginaTeste(pageData))
incluirConfiguracoes(pageData, isSuite);
return pageData.getHTML();
}
14. Comentários
Escrevendo Código Limpo | LidianeTaquehara
“Não comente código ruim – reescreva-o.”
- BrianW. Kernighan e P. J. Plaugher
Comentários servem para compensar o nosso
fracasso ao nos expressarmos em código.
15. Se expresse em código
Escrevendo Código Limpo | LidianeTaquehara
// Checar se o funcionário é elegível
// para receber benefícios
if (funcionario.flags & FLAG_HORA) &&
(salario.idade > 65)
if (funcionario.eElegivelParaBeneficios())
16. Escrevendo Código Limpo | LidianeTaquehara
Comentários Legais
Comentários Informativos
Explicação de intenção
Esclarecimento
Aviso de Consequência
Comentários Bons
Amplificação
Javadocs em APIs públicas
17. Comentários Legais
Escrevendo Código Limpo | LidianeTaquehara
// Copyright (C) 2003 , 2004, 2005 by Object Mentor,
// Inc. All rights reserved.
// Release under the terms of the GNU General Public
// License version 2 or later.
Comentários Informativos
// formato kk:mm:ss EEE, MMM dd, YYYY
Pattern timeMatcher = Pattern.compile(
“d*:d*:d* w*, w* d*, d*”);
18. Escrevendo Código Limpo | LidianeTaquehara
Esclarecimento
public void test CompareTo() throws Exception
{
WikiPagePath a = PathParser.parse(“PageA”);
WikiPagePath b = PathParser.parse(“PageB”);
assertTrue (a.compareTo(a) == 0); // a == a
assertTrue (a.compareTo(b) != 0); // a != b
assertTrue (a.compareTo(b) == -1); // a < b
assertTrue (b.compareTo(a) == 1); // b > a
}
19. Escrevendo Código Limpo | LidianeTaquehara
Comentários Redundantes
Marcadores de posição
Encerramento de chaves
Código comentado
Comentários HTML
Comentários Ruins
Informações em excesso
Cabeçalhos de função
20. Escrevendo Código Limpo | LidianeTaquehara
Comentários redundantes
// Método utilitário que retorna quando
// this.close é verdadeiro.
// Lança uma exceção em caso de timeout.
public synchronized void waitForClose (final
long timeoutMilis) throws Exception {
if (!closed) {
wait(timeoutMilis);
if (!closed)
throw new Exception(“MockResponseSender
não pôde ser encerrado”);
}
}
21. Marcadores de posição
Escrevendo Código Limpo | LidianeTaquehara
// Ações //////////////////////////////
Código comentado
InputStreamResponse response = new InputStreamResponse();
response.setBody(formatter.getResulStream(),
formatter.getByteCount())
// InputStream resultsStream = formatter.getResultStream();
// StreamReader reader = new StreamReader(resultsStream);
//response.setContent(reader.read(formatter.getByteCount()));
23. Escrevendo Código Limpo | LidianeTaquehara
package fitnesse.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extends ParentWidget {
public static final String REGEXP = “ ‘’’.+?’’’ ”;
private static final Pattern pattern =
Pattern.compile(“ ‘’’ (.+?) ‘’’ ”,
Pattern.MULTILINE + Pattern.DOTALL);
public BoldWidget (ParentWidget parent, String
text) throws Exception {
super(parent);
Matcher match = pattern.matcher(text);
match.find();
addChildWidgets(match.group(1));}
}
EspaçoVertical Entre Conceitos
24. Escrevendo Código Limpo | LidianeTaquehara
EspaçoVertical Entre Conceitos
package fitnesse.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extends ParentWidget {
public static final String REGEXP = “ ‘’’.+?’’’ ”;
private static final Pattern pattern =
Pattern.compile(“ ‘’’ (.+?) ‘’’ ”,
Pattern.MULTILINE + Pattern.DOTALL
);
public BoldWidget (ParentWidget parent, String text)
throws Exception {
super(parent);
Matcher match = pattern.matcher(text);
match.find();
addChildWidgets(match.group(1));
}
}
25. Escrevendo Código Limpo | LidianeTaquehara
DensidadeVertical
public class ReporterConfig {
/**
* The class name of the reporter listener
*/
private String m_className;
/**
* The properties of the reporter listener
*/
private List<Property> m_properties = new
ArrayList<Property>();
public void addProperty(Property property) {
m_properties.add(property);
}
}
26. Escrevendo Código Limpo | LidianeTaquehara
DensidadeVertical
public class ReporterConfig {
private String m_className;
private List<Property> m_properties = new
ArrayList<Property>();
public void addProperty(Property property) {
m_properties.add(property);
}
}