2009年2月5日 星期四

第36題

Given:
public class Doubler{
public static int doubleMe(Holder h){
return h.getAmount() * 2;
}
}
and:
public class Holder {
int amount = 10;
public void doubleAmount(){amount = Doubler.doubleMe(this);}
public in getAmount(){return amount;}
//more code here
}
Place the code framgmets in position to reduce the coupling between Doubler and Holder.
public class Doubler{
public static int doubleMe( Place here h){
return Place here * 2;
}
}
public class Holder {
int amount = 10;
public void doubleAmount(){amount = Doubler.doubleMe( Place here );}


public in getAmount(){return amount;}
//more code here
}
Code Fragments
void
Holder
int
Doubler
h.getAmount()

h
this
amount
-----------------------------------------------------------------------------------------
答案:

public class Doubler{


public static int doubleMe( int h){

return h * 2;


}
}

public class Holder{

int amount = 10;

public void doubleAmount(){amount = Doubler.doubleMe( amount );}

public int getAmount(){return amount;}
//more code here

}

參考:6-2 Java方法

原code傳入物件,目的只是為了計算 amount
public void doubleAmount(){amount = Doubler.doubleMe(this);}
...
return h.getAmount() * 2;

修改後code,只需傳入amount即可降低相依性

沒有留言:

張貼留言