2013-03-13 31 views
2

我正在通過發送DeadStore警告Findbugs on int i below。由於可讀性,我不想寫一行。有沒有更好的方法來寫這個,以便沒有死亡存儲到,但可讀?FindBugs Dead Store Warning - 我應該重組代碼還是忽略警告

if (aqForm.getId() != null) { 
     try { 
      int i = Integer.parseInt(aqForm.getId()); 
      aqForm.setId(aqForm.getId().trim()); 
     } catch (NumberFormatException nfe) { 
      result.rejectValue("id", "error.id", "Please enter an integer."); 
      foundError = true; 
     } 
    } 

回答

3

您不必分配到i。你可以只調用parseInt()而忽略結果:

if (aqForm.getId() != null) { 
     try { 
      Integer.parseInt(aqForm.getId()); // validate by trying to parse 
      aqForm.setId(aqForm.getId().trim()); 
     } catch (NumberFormatException nfe) { 
      result.rejectValue("id", "error.id", "Please enter an integer."); 
      foundError = true; 
     } 
    } 

這就是說,我將創建一個輔助函數:

public static boolean isValidInteger(String str) { 
     ... 
    } 

和重寫你的代碼片段,像這樣:

String id = aqForm.getId(); 
    if (id != null) { 
     if (isValidInteger(id)) { 
     aqForm.setId(id.trim()); 
     } else { 
     result.rejectValue("id", "error.id", "Please enter an integer."); 
     foundError = true; 
     } 
    } 
+0

@EdgeCase:不是。事實上,這是我最初的想法,但後來被編輯出來了。我的理由是,我所顯示的代碼在功能上與您的代碼不一樣(您的代碼默默接受'null',而我的代碼會抱怨它)。 – NPE 2013-03-13 17:08:24

5

只需調用該方法,而忽略結果,最好是使用註釋解釋爲什麼:

// Just validate 
Integer.parseInt(aqForm.getId()); 

目前還不清楚爲什麼你修剪你沒有驗證,而不是版本你的版本,介意你。我更喜歡:

String id = aqForm.getId(); 
if (id != null) { 
    try { 
     id = id.trim(); 
     // Validate the ID 
     Integer.parseInt(id); 
     // Store the "known good" value, post-trimming 
     aqForm.setId(id); 
    } catch (NumberFormatException nfe) { 
     result.rejectValue("id", "error.id", "Please enter an integer."); 
     foundError = true; 
    } 
} 
+0

我認爲, ,但是Netbeans對於將parseInt()分配給一個變量感到困擾。我想我會忽略Netbeans而不是FindBugs。 – EdgeCase 2013-03-13 17:01:56