今天我偶然發現了一個我在項目中看到的代碼,並且很擔心地看着它。我不知道爲什麼他們將這些作爲靜態方法,因爲它們改變了對象的狀態。下面靜態方法改變狀態對象
是代碼
@Controller
CruiseController{
getCruiseSearchResults(){
//prepare cruise serach request, static method in CruiseHelper
CruiseSearchRequest cruiseReq = CruiseHelper.prepareRequest();
...futher impl
}
/** my helper class which has utlity methods */
CruiseHelper{
public static CruiseSearchRequest prepareRequest(){
CruiseSearchRequest cruiseRequest = new CruiseSearchRequest();
// all below methods are static
setCruiseTypeandDestination(cruiseRequest)
setStartAndEndDate(cruiseRequest)
setShipAndDeparturePort(cruiseRequest)
setDurationAndAccesiblity(cruiseRequest)
setPromoType(cruiseRequest)
setResultPreferences(cruiseRequest)
return cruiseSearchCriteriaDTO
}
static void setCruiseTypeandDestination(CruiseSearchRequest cruiseRequest){
/** changing the state of object in static method */
cruiseRequest.setCruiseType("ABC");
cruiseRequest.setCruiseType("Alaska");
}
//.... further static methods as above, all of them
//change the state of cruiseRequest
}
,所以我知道的是,上述方法不應是靜態的,因爲他們都有每個請求的性質。但是代碼正在工作,並且在執行任何負載測試時未失敗。
我的一個重要問題是:「上面的代碼可以考慮嗎?」和「如果是的話,這可能會失敗,那麼在什麼情況下?」