簡體   English   中英

結果附加或異常

[英]Result attached or exception

假設我有一個 function f應該通過調用g返回attached T 但是, g返回一個detachable T 如果g導致 Void,我想引發這樣的異常:

f: T
  do
    if attached g as res then
      Result := res
    else
      raise
    end
  end
  
raise
  do
    (create {DEVELOPER_EXCEPTION}).raise
  end

在此設置中,EiffelStudio 給了我一個錯誤VEVI: Variable is not properly set. Variable: Result VEVI: Variable is not properly set. Variable: Result f末尾的結果。

實際上, Result 可以在f的末尾為 Void 但在這種情況下執行不應到達f的末尾,應該引發異常。

如何重構代碼以獲得類似的結果?

如果引發異常的類型無關緊要,則可以使用以下代碼:

f: T
    do
        Result := g
        check is_g_attached: attached Result then end
    end

如果引發異常的類型很重要,則可以使用表示該特性永遠不會返回的后置條件False來增加特性raise 然后,代碼看起來像

f: T
    do
        Result := g
        if not attached Result then
            raise
        end
    end

raise
    do
        (create {DEVELOPER_EXCEPTION}).raise
    ensure
        False
    end

剛剛發現在這種情況下可以使用check

f: T
  do
    if attached g as res then
      Result := res
    else
      raise
    end
    check attached Result then end
  end

但是,我想知道是否有更清潔的方法。

我認為你可以逃脫:

f:T
   do
      check has_g: attached g then Result := g end
   end

如果attached g不是True ,代碼自然會中斷。 請注意,當我想確保附加諸如g之類的功能時,我會使用此構造。

我還將其編碼為:

f:T
   do
      check has_g: attached g as al_result then Result := al_result end
   end

所以,你可能會問:這有什么不同,“al_”前綴是什么?

  1. 第一個示例沒有as ____的混亂,這使它更容易閱讀和理解(恕我直言)。
  2. “al_”前綴是我遵循的命名約定,其中“al”表示“附件本地”。 作為我的代碼的讀者,我可以查看變量名並知道變量的聲明位置。
  • 如果變量沒有前綴,則它是 class 本身的特征參考。

  • 如果前綴是“l_?”,那么我會查看功能local聲明。

  • 如果是“al_”,那么我會查看checkif.. then或其他塊as關鍵字。

  • 我也將它用於跨循環,其中ic_? 是一個“迭代游標”本地 object。 我也將此命名約定應用於符號循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM