sábado, 6 de agosto de 2011

Replace Parameter with Method

el proceso entero con comentarios se puede seguir mediante el archivo de MoonEdit (programa muy chulo , gratis y sin peso apenas) replace parameter with method
CODIGO INICIAL
public double getPrice()
{
int basePrice = _quantity * _itemPrice;
int discountLevel;
if (_quantity > 300) discountLevel = 3;
else if (_quantity > 200) discountLevel = 2;
else discountLevel = 1;
double finalPrice = discountedPrice (basePrice, discountLevel);
return finalPrice;
}

private double discountedPrice (int basePrice, int discountLevel)
{
if (discountLevel == 2) return basePrice * 0.1;
elseif (discountLevel == 3) return basePrice * 0.2;
else return basePrice * 0.05;
}


CODIGO FINAL
public double getPrice()
{
if (Discount.isEnoughQuantityForPlatinum(_quantity))
return getBasePrice() * Discount.PLATINUM.getPercentage();
elseif (Discount.isEnoughQuantityForPlus(_quantity))
return getBasePrice() * Discount.PLUS.getPercentage();
else
return getBasePrice() * Discount.NORMAL.getPercentage();
}
private int getBasePrice()
{
return _quantity * _itemPrice;
}
class Discount
{
static final int MIN_QUANTITY_FOR_PLATINUM = 300;
static final int MIN_QUANTITY_FOR_PLUS = 200;

static final int PLATUNUM_LEVEL = 3;
static final int PLUS_LEVEL = 2;
static final int NORMAL_LEVEL = 1;
static final float PLATINUM__PERCENTAGE = 0.2;
static final float PLUS__PERCENTAGE = 0.1;
static final float NORMAL_PERCENTAGE = 0,05;
public static final Discount NORMAL = new Discount (NORMAL_LEVEL , NORMAL_PERCENTAGE);
public static final Discount PLUS = new Discount (PLUS_LEVEL , PLUS_PERCENTAGE);
public static final Discount PLATINUM = new Discount (PLATINUM_LEVEL , PLATINUM_PERCENTAGE);
private final int _level;
private final float _percentage;

private Discount(int level,float percentage)
{
_level = level;
_percentage = percentage;
}
public getLevel()
{
return _level;
}
public getPercentage()
{
return _percentage;
}
public boolean isEnoughQuantityForPlus(quantity)
{
if (quantity > MIN_QUANTITY_FOR_PLUS) return true;
return false;
}
public boolean isEnoughQuantityForPlatinum(quantity)
{
if (quantity > MIN_QUANTITY_FOR_PLATINUM) return true;
return false;
}


bad Smell: getPrice() -- long method , finalPrice variable is always the discount Calculated Price
refactoring used :
replace parameter with method <- making methods calls simpler
invented name refactor (i don´t know if its a current name for this)
introduce multible return points <- simplifying Conditional Expressions
inline method <- componsing methods
replace Magic Number with Symbolic constant <- organizing data
replace type code with class <- organizing data
move method <- move features between objects
consolidate conditional expression <- simplifying conditional expressions

No hay comentarios:

Publicar un comentario