如何重构需要大量参数的函数?

发布于 2024-07-07 10:11:06 字数 1703 浏览 7 评论 0原文

我为 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

该函数必须接受的参数数量是我最担心的。 这个还不错,但是将来我可能需要制作一些其他函数,这些函数将需要更多参数,所以我主要寻找更好的方法来构建大参数函数。

I wrote a wrapper for a COM object that only excepted strings as input, so in good OOP practice I wrapped the string up in a function so that it was easier to build and call.

I was just wondering if anyone could think of a better way to do the following code.

   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

The amount of arguments that the function has to take is my biggest worry. This one is not too bad but there are some other functions that I may have to make in the future that will take a lot more arguments, so I'm mainly looking for better ways to build large argument functions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

波浪屿的海角声 2024-07-14 10:11:06

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

就像是

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()
    }
}

In this case it seems many of the parameters are just 'configuration values' (which end up being strings), you could modify it to accept a single class for all the configuration that you prepare before the call and that will return you the string accordingly.

Something like

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()
    }
}
哥,最终变帅啦 2024-07-14 10:11:06

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

One way to handle functions that can take lots of arguments is to create a new object type whose sole purpose is to hold arguments for that function. Then you create a new object of that type, set the properties as needed, then pass that one object reference to your OpenTable function.

成熟的代价 2024-07-14 10:11:06

由于我不知道你的编程语言,我将把它保留为伪代码,但我的一般答案是使用 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
}

好吧,你的函数的最后一部分对我来说没有意义,但参数数组的想法应该我想遇到过。 祝你好运。

Since i dont know your programming language, im gonna keep this to pseudo code, but my general answer is to use ann array as single parameter:

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
}

Ok the last part of your function doesnt make sense to me, but the idea of array of params should come across i think. Good luck.

夏天碎花小短裙 2024-07-14 10:11:06

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

' Define an Enum with FlagsAttribute.
<FlagsAttribute( )> _
Enum TableOptions as Short
    Hide = 1
    AsReadOnly = 2
    Interactive = 4
    NoIndex = 8
    ViewAutomatic = 16
End Enum

You can switch all your boolean parameters to a single parameter of an enum type, marked as Flags. Here's an example declaration:

' Define an Enum with FlagsAttribute.
<FlagsAttribute( )> _
Enum TableOptions as Short
    Hide = 1
    AsReadOnly = 2
    Interactive = 4
    NoIndex = 8
    ViewAutomatic = 16
End Enum
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文