Replace Parameter with Method

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(New page: == Motivation == ''Refactoring'' Martin Fowler 1999 states that: "If a method can get a value that is passed in as a parameter by another means, it should." == Example == An object ...)
 
(Motivation)
Line 2: Line 2:
  
 
''Refactoring'' [[Martin Fowler 1999]] states that: "If a method can get a value that is passed in as a parameter by another means, it should."
 
''Refactoring'' [[Martin Fowler 1999]] states that: "If a method can get a value that is passed in as a parameter by another means, it should."
 +
 +
In some cases, this could lead to a violation of [[Tell, don't ask]].  This would occur where these method calls are occurring between different classes rather than within one class.
  
 
== Example ==
 
== Example ==

Revision as of 21:34, 14 October 2009

Motivation

Refactoring Martin Fowler 1999 states that: "If a method can get a value that is passed in as a parameter by another means, it should."

In some cases, this could lead to a violation of Tell, don't ask. This would occur where these method calls are occurring between different classes rather than within one class.

Example

An object invokes a method, then passes the result as a parameter for a method. The receiver can also invoke this method. So the best idea is to remove the parameter and let the receiver invoke the method.

int basePrice = quantity * itemPrice;
discountLevel = getDiscountLevel();
double finalPrice = discountedPrice(basePrice, discountLevel);

Above we have some code, but lets remove the discountLevel parameter from discountedPrice(basePrice, discountLevel). Now we have:

int basePrice = quantity * itemPrice;
double finalPrice = discountedPrice(basePrice);

The discountedPrice(basePrice) method now looks like:

discountedPrice(basePrice)
{
    int discountLevel = getDiscountLevel();
    //does calculation type stuff here
    
    return discountedPrice;
}
Personal tools