if(StringUtil.isEmpty(username))thrownewICRClientException("username can not be null");if(StringUtil.isEmpty(password))thrownewICRClientException("password can not be null");if(udto==null)thrownewICRClientException("ICRUploadDTO can not be null");
重構之后:
1234567891011
//將原來的地方替換為checkStringParamEmpty(username,"username");checkStringParamEmpty(password,"password");checkStringParamEmpty(udto.getUrlPath(),"urlPath");...//新增一個方法privatevoidcheckStringParamEmpty(Stringvalue,Stringname)throwsICRClientException{if(StringUtil.isEmpty(value)){thrownewICRClientException(name+" can not be null");}}
原代碼中不止這3個參數的校驗,還有很多,越多參數的校驗,我們重構后的復雜度就會越低。
代碼復雜度變化:原來是3,修改后為1。
多String值判斷
123
if(!udto.getPriority().equals("0")&&!udto.getPriority().equals("1")&&!udto.getPriority().equals("2")&&!udto.getPriority().equals("3"))thrownewICRClientException("priority must be 0/1/2/3");
重構之后:
123456789
//將原來代碼替換為checkValueWithinList(udto.getPriority());...//新增一個方法:privatevoidcheckValueWithinList(Stringpriority)throwsICRClientException{if(!Arrays.asList("0","1","2","3").contains(priority)){thrownewICRClientException("priority must be 0/1/2/3");}}
代碼復雜度變化:原來是4,修改后為1。
對list的非空判斷
12
if(list==null||list.size()==0)thrownewICRClientException("list can not be null");
重構之后:
1234567
//將原來的代碼替換為checkValueWithinList(udto.getPriority());...//新增一個方法privatevoidcheckListNoNull(Listlist)throwsICRClientException{if(list.isEmpty())thrownewICRClientException("list can not be null");}