You are on page 1of 28

Test-driven Development

Refactoring

sistemas de informao I

Tiago Massoni
problema

Bradman 99.94
Pollock 60.97
Headley 60.83

Escreva 3 testes para o um mtodo Reader.readChar(), que


l caracteres do arquivo acima e retorna um char, lanando
exceo EOFException quando estiver no final do arquivo.
Test Driven Development

If you cant write a test for what


you are about to code, then you
shouldnt even be thinking
about coding
Test Driven Development

If you cant write a test for what


you are about to code, then you
shouldnt even be thinking
about coding
coding dojo

Crivo de Eratosthenes
problema de design?
void imprimeDivida () {
Iterator i = dividas.iterator();
double divida = 0.0;
// imprime cabealho
System.out.println (**Dvidas do Cliente**);
// calcula dvidas
while (i.hasNext()){
Divida d =(Divida)i.next();
divida += d.valor();
}
// imprime detalhes
System.out.println (**Divida total**: + divida);
}
como melhorar?
void imprimeDivida () {
Iterator i = dividas.iterator();
double divida = 0.0;
// imprime cabealho
System.out.println (**Dvidas do Cliente**);
// calcula dvidas
while (i.hasNext()){
Divida d =(Divida)i.next();
divida += d.valor();
}
// imprime detalhes
System.out.println (**Divida total**: + divida);
}
passo 1
void imprimeDivida () {
Iterator i = dividas.iterator();
double divida = 0.0;
imprimeCabecalho ();
// calcula dvidas
while (i.hasNext()){
Divida d =(Divida)i.next();
divida += d.valor();
}
// imprime detalhes
System.out.println (**Divida total**: + divida);
}
void imprimeCabecalho () {
System.out.println (**Dvidas do Cliente**);
}
passo 2
void imprimeDivida () {
Iterator i = dividas.iterator();
double divida = 0.0;
imprimeCabecalho ();
// calcula dvidas
while (i.hasNext()){
Divida d =(Divida)i.next();
divida += d.valor();
}
imprimeDetalhes (divida);
}

void imprimeDetalhes (divida){


System.out.println (**Divida total**:+ divida);
}
passo 3
void imprimeDivida () {
imprimeCabecalho ();
double divida = calculaDivida ();
imprimeDetalhes (divida);
}

double calculaDivida (){


Iterator i = dividas.iterator();
double divida = 0.0;
while (i.hasNext()){
Divida d =(Divida)i.next();
divida += d.valor();
}
return divida;
}
bad smells
(mau cheiro)
Estudos empricos mostram
maioria dos smells esto em mdulos desde a criao
destes
maioria dos smells adicionados ao desenvolver novos
recursos
Novatos no necessariamente introduzem mais bad
smells; h uma forte relao de introduo de smells e
aumento de carga de trabalho e presso de
lanamento de produtos
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = "Rental Record for " + name() + "\n";

while (rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental) rentals.nextElement();
// determine amounts for each line
switch (each.tape().movie().priceCode()) {
case Movie.REGULAR:
thisAmount += 2;
if (each.daysRented() > 2)
thisAmount += (each.daysRented() - 2) * 1.5;
break;
case Movie.NEW_RELEASE:
thisAmount += each.daysRented() * 3;
break;
case Movie.CHILDRENS:
thisAmount += 1.5;
if (each.daysRented() > 3)
thisAmount += (each.daysRented() - 3) * 1.5;
break;
}


totalAmount += thisAmount;
// add frequent renter points
frequentRenterPoints++;
// add bonus for a two day new release rental
if ((each.tape().movie().priceCode() == Movie.NEW_RELEASE) &&
each.daysRented() > 1)
frequentRenterPoints++;
// show figures for this rental
result += "\t" + each.tape().movie().name() + "\t" +
String.valueOf(thisAmount) + "\n";
}
// add footer lines
result += "Amount owed is " + String.valueOf(totalAmount) + "\n";
result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent
renter points";
return result;

que smell voc sente aqui?


Long Method

The longer the procedure, the more difficult it


is to understand"
void imprimirDevedores(){
ArrayList<Pedido> e = pedidos.elementos();
double valorTotal = 0.0;

//imprimir banner
System.out.println("********************");
System.out.println("*****Clientes Devedores************");
System.out.println("********************");

//calcular devedores
for (Pedido cada: e){
valorTotal += cada.getValor();
}

//imprimir detalhes
System.out.println("name: "+ nome);
System.out.println("Total: "+ valorTotal);
}
Divergent Change

quando um mdulo modificado muitas vezes


por diferentes motivos
Mal Cheiros (Bad Smells)
Cdigo duplicado
Mtodos, subclasses
Classes muito grandes
Preocupaes diferentes
Listas de parmetros muito longas
Objetos podem ser agrupados
Inveja de recursos
Classes que se preocupam demais com outras
Classe Preguiosa
Se no faz nada, no deve ser necessria
uma transformao foi feita

Se funcionava tem que manter funcionando


refactoring

melhorar o
projeto sem
mudar o
comportamento
original do
programa
Extract Method
Quando refatorar

Antes de adicionar uma funcionalidade


Ao tentar corrigir um defeito
Durante a atividade de reviso de cdigo
Extract Class
passos (mechanics)
Decidir o que ser dividido dentro da classe
Criar uma nova classe

Definir o relacionamento entre elas


Compilar e testar
Mover cada atributo escolhido
Compilar e testar
Copiar cada mtodo para a nova classe (implementar a delegao)
Compilar e testar
exerccio
public class ComponenteDaLinha {
protected List partes= new LinkedList();
}

public class PlacaMae extends ComponenteDaLinha {


public void adicionarComponentes (USB porta){
partes.add(porta);
}
}

public class PlacaRede extends ComponenteDaLinha{


public void addPartes(Object any){
partes.add(any);
}
}
indicaes ps-aula

https://refactoring.userecho.com
Test-driven
Development
Refactoring
sistemas de informao I

Tiago Massoni

You might also like