我为COM对象编写了一个包装器,它只排除了字符串作为输入,因此在良好的OOP实践中,我将字符串包装在函数中,以便更容易构建和调用。

我只是想知道是否有人能想出更好的方法来执行以下代码。

   Public Function OpenTable(ByVal TablePath As String, Optional ByVal OpenAs As String = Nothing, _
            Optional ByVal Hide As Boolean = False, Optional ByVal AsReadOnly As Boolean = False, _
            Optional ByVal Interactive As Boolean = True, Optional ByVal Password As String = Nothing, _
            Optional ByVal NoIndex As Boolean = False, Optional ByVal ViewAutomatic As Boolean = True) As TableInfo

            If String.IsNullOrEmpty(TablePath) Then
                Throw New ArgumentNullException("TablePath", "TablePath cannot be null or empty")
            End If

            Dim Builder = New StringBuilder("Open Table ")
            Builder.AppendFormat("{0}{1}{2}", ControlChars.Quote, TablePath, ControlChars.Quote)

            If (Not String.IsNullOrEmpty(OpenAs)) Then Builder.AppendFormat(" as {0} ", OpenAs)
            If (Hide) Then Builder.Append(" Hide ")
            If (AsReadOnly) Then Builder.Append(" ReadOnly ")
            If (Interactive) Then Builder.Append(" Interactive ")
            If (Not String.IsNullOrEmpty(Password)) Then Builder.AppendFormat(" Password {0} ", Password)
            If (NoIndex) Then Builder.Append(" NoIndex ")
            If (ViewAutomatic) Then Builder.Append(" View Automatic ")

            MyComApp.Do(Builder.ToString)

            Dim FileInfo = New IO.FileInfo(TablePath)
            Return New TableInfo(FileInfo.Name.Substring(0, InStrRev(FileInfo.Name, ".") - 1))
        End Function

该函数必须采用的参数数量是我最担心的。这个并不算太差,但是我将来可能要做的其他一些函数需要更多的参数,所以我主要是寻找更好的方法来构建大的参数函数。

有帮助吗?

解决方案

在这种情况下,似乎很多参数只是'配置值'(最终成为字符串),您可以修改它以接受您在调用之前准备的所有配置的单个类,这将返回给您相应的字符串。

这样的东西
class COMConfiguration {
    private bool Hide = false;
    private bool AsReadOnly = false;
    //and so on...

    public void setHide(bool v) { Hide = v; }

    //only setters

    public string getConfigString() {
        StringBuilder sb = new StringBuilder();
        if (Hide) { sb.Append(" Hide "); }
        if (AsReadOnly) { sb.Append(" ReadOnly "); }
        //and so on
        return sb.ToString()
    }
}

其他提示

处理可能需要大量参数的函数的一种方法是创建一个新的对象类型,其唯一目的是保存该函数的参数。然后创建该类型的新对象,根据需要设置属性,然后将该对象引用传递给 OpenTable 函数。

由于我不知道您的编程语言,我会将其保留为伪代码,但我的一般答案是使用ann数组作为单个参数:

function OpenTable( options As array) {
    if (options is not array or options is empty) {
        Throw exception
    }
    return_string = "";
    if ( key is set ('readOnly', options) and is not empty) {
        return_string = return_string + ' readonly';
    }
    // repeat last 3 lines for all your params
}

好的,你的函数的最后一部分对我来说没有意义,但我认为应该遇到一系列params的想法。祝你好运。

您可以将所有布尔参数切换为枚举类型,标记为 Flags 。这是一个示例声明:

' Define an Enum with FlagsAttribute.
<FlagsAttribute( )> _
Enum TableOptions as Short
    Hide = 1
    AsReadOnly = 2
    Interactive = 4
    NoIndex = 8
    ViewAutomatic = 16
End Enum
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top