2012-07-26 6 views
0

이 샘플 코드 조각Null 반환 메서드가 호출되는 메서드에서 null 값을 처리하는 방법은 무엇입니까?

public OperationResult beforeEverything(BDDObject savingObject) { 

    String checkAssetRole = doCheckAssetRole(savingObject); 

    if (checkAssetRole != null && !checkAssetRole.equals("MissingAssetRole")) { 
    return new OperationResult(new OperationExecutionError("SIP-37006", 
           new String[] {"Duplicate asset roles have been defined: " + checkAssetRole}, 
           getLocalizationGate())); 
    } 
    ArrayList<String> warnings = new ArrayList<String>(); 
    boolean showWarning = false; 

    if (checkAssetRole != null && checkAssetRole.equals("MissingAssetRole")) { 
    mLogger.debug("Warning of Asset role"); 
    warnings.add(new String(
       "Asset role is missing. Do you want to save the record?")); 
    showWarning = true; 
    } 
    return OperationResult.OK; 
} 

것은이 doCheckAssetRole 방법은 null을 반환이다. 어떻게 beforeEverything() 메서드에서 처리 할 수 ​​있습니다. 할 몇 가지 예외 처리가 있습니까? 그렇다면 어떻게?

답변

1

null 수표를 넣은 다음 RuntimeExceptionmessage으로 지정합니다.

if(checkAssetRole==null) 
     throw new RuntimeException ("AssetRole value is NULL."); 

그리고 코드는 다음과 같습니다.

String checkAssetRole = doCheckAssetRole(savingObject); 

if(checkAssetRole==null) 
     throw new RuntimeException ("AssetRole value is NULL."); 

if (checkAssetRole != null && !checkAssetRole.equals("MissingAssetRole")) { 
return new OperationResult(new OperationExecutionError("SIP-37006", 
          new String[] {"Duplicate asset roles have been defined: " + checkAssetRole}, 
          getLocalizationGate())); 
} 
+1

선택'IllegalArgumentException'입니다 이 경우에는 RuntimeException보다 더 좋다. 이것을 강조 표시하려면 – assylias

+0

+1. 그것의 더 특정한. – amicngh

+0

1. 다음 if 조건에서도 null 체크를 제거해야합니다. 더 이상 필요하지 않기 때문입니다. 2. IllegalArgumentException은 더 구체적이지 않습니다 - 모든 오류가 불법 인수로 인한 것이 아니기 때문에 생각합니다. 삼.checkAssetRole에 대한 null 체크를 모두 제거하면 NullPointerException이 발생합니다. 이제 이것이 내가 부르는 것입니다. – Axel

0

null은 일반적인 방법입니다. 발신자가 확인해야합니다. 귀하의 경우에는 수표로 조치를 취할 수 있습니다. 던지기와 예외를 원한다면 그렇게 할 수 있습니다.

public OperationResult beforeEverything(BDDObject savingObject) { 

    String checkAssetRole = doCheckAssetRole(savingObject); 

    if (checkAssetRole == null) { 
     // DO SOMETHING HERE. eg. throw new RuntimeException("Asset Role should not be null"); 
     // or simply return null; 

    } 
+0

던진 후에 RuntimeException을 처리해야하는지 여부를 알려줄 수 있습니까? 내 말은, try-catch 블록이 필요하다는 거지? – dev

+0

런타임 예외는 try/catch 블록을 필요로하지 않습니다. 웹 앱을 제작하는 경우 해당 오류로 수행 할 작업을 결정해야합니다. 사용자 고유의 예외 클래스 (하위 클래스 RuntimeException)를 작성한 후 더 이상 catch하고 사용자에게 메시지를 표시 할 수 있습니다. – jasop

0

null이 반환 될 때 수행 할 작업에 따라 다릅니다. doCheckAssetRole에서 null이 반환 될 때 NotOK 값을 반환하려면이 부분을 사용할 수 있습니다.

public OperationResult beforeEverything(BDDObject savingObject) { 

    String checkAssetRole = doCheckAssetRole(savingObject); 

    if (checkAssetRole == null) { 
    return OperationResult.NotOK; // Or something else that indicates to the calling method what happened. 
    else { 
    if (!checkAssetRole.equals("MissingAssetRole")) { 
     return new OperationResult(new OperationExecutionError("SIP-37006", 
           new String[] {"Duplicate asset roles have been defined: " + checkAssetRole}, 
           getLocalizationGate())); 
    } 
    ArrayList<String> warnings = new ArrayList<String>(); 
    boolean showWarning = false; 

    if (checkAssetRole.equals("MissingAssetRole")) { 
     mLogger.debug("Warning of Asset role"); 
     warnings.add(new String(
        "Asset role is missing. Do you want to save the record?")); 
     showWarning = true; 
    } 
    return OperationResult.OK; 
    } 
} 
1

그것은 doCheckAssetRole가 null의 경우 비즈니스 로직이 무엇인지 당신이 원하는 따라 달라집니다

  • 이 경우에 반환 할 해당 OperationResult 개체가 그래서, 유효한 비즈니스 사용 사례에 해당한다, 그래서 당신은 뭔가를 할 것입니다

    if (checkAssetRole == null) 
        return new NoAssetRoleOperationResult(); 
    

    그리고 호출 코드는 이런 종류의 결과를 처리 할 것입니다.

  • 사용자가 실수를 한 경우를 제외하고는 결코 발생하지 않을 것으로 확인 된 다음에 검사 예외가 발생합니다.

    if (checkAssetRole == null) 
        throw new NoAssetRoleException(yourMessage); 
    

    당신은 당신의 메소드 선언 throws NoAssetRoleExeption을합니다. 그런 다음 호출 코드가이 오류를 사용자에게 전달합니다.

  • 환경 오류 (원격 서버가 다운 됨)로 인해 실패했습니다. RuntimeException과 같은 확인되지 않은 예외가 발생하면 최상위 코드가이를 감지하여 환경 오류가 있음을 나타냅니다.

  • 이 때문에 개발 오류 (한다면 이론적이 코드는 null를 돌려해서는 안) 실패

    는, 당신은 주장 :

    assert checkAssetRole != null : "assetRole should not be null" 
    

귀하의 경우 : 내가 생각

+0

첫 번째 경우'return new NoAssetRoleOperationResult();'NoAssetRoleOperationResult()'가 원하는 객체 유형으로 형변환되어야합니다. – Prince

관련 문제