代码之家  ›  专栏  ›  技术社区  ›  Paul Farry

如何在开发人员错误使用属性时强制异常

  •  1
  • Paul Farry  · 技术社区  · 16 年前

    我试图在一些代码中设置一些使我陷入困境的修复程序,并试图在开发人员试图访问未满足规则的属性时抛出一些异常。

    铌。为了清楚起见,这门课很多都被省略了。

    myobject = new POSTerminalList(mCommonManagers)
    
    ' This should throw an error which it does but is out of scope. 
    Log.Write(myobject.Current.Description)
    

    目前我正在抛出一个异常,但这会丢失调用函数(这就是问题所在)。

    是否有某种方法来保护这样的属性,以便如果开发人员不正确地使用该属性,您知道应该在哪里查找而不是在这个类中查找。

    虽然这段代码是vb.net,但我对设计方法而不是语言感兴趣,所以c实现也对我有用。

    <DebuggerDisplay("{mCode}", Name:="{mDescription}")> _
    Public Class POSTerminalList
    Inherits SortedList(Of Integer, POSTerminal)
    
        Private mCurrentTerminal As POSTerminal
        Private mCurrentTerminalNumber As Integer
    
        Private Sub New()
            mFullList = New SortedList(Of Integer, POSTerminal)
        End Sub
    
        Public Sub New(ByVal theManagers As IPSBusiness.CommonManagers)
            Me.New()
        End Sub
    
        ''Internal thread that is assessing things and calling this method.
        Private Sub SetCurrentTerminal()
            If mCurrentTerminalNumber = 0 Then
                mCurrentTerminal = Nothing
            Else
                If Me.ContainsKey(mCurrentTerminalNumber) Then
                    mCurrentTerminal = me.Item(mCurrentTerminalNumber)
                Else
                    mCurrentTerminal = Nothing
                End If
            End If
        End Sub
    
        Public ReadOnly Property Current() As POSTerminal
            Get
                If mCurrentTerminal Is Nothing Then 
                    Throw New POSTerminalMissingException(
                        "Attempt to use the Current Terminal without a " +
                        "valid current terminal. This is a developer error.")
                Return mCurrentTerminal
            End Get
        End Property
    
    End Class
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   casperOne    16 年前

    首先,我建议您不要通过description属性抛出异常。当您认为它超出了范围时,实际上是当前的属性失败了,并且通过description属性公开它,您最终会误导代码的使用者,使其认为其他地方出了问题。

    这就是说,如果您真的想这样做,您应该基本上向postTerminal类公开代理,在postTerminal类中,属性委托调用由current公开的postTerminal实例上的相同属性。这样,当代理上的属性被调用时,如果它们失败,调用堆栈将在代理上的属性中运行。