Appropriate use of Static Method

2019-04-26 01:15发布

Conceptually, is it appropriate to use a static method (C#) when the method will only take inputs and reformat the input as the output? For example:

public static string FormatString(string inputString){
  return "some formatting" + inputString + "Some other formatting";
}

If I were to have a few of these types of methods, would a static "utility" class be a good idea?

10条回答
叛逆
2楼-- · 2019-04-26 01:24

You could use an extension method for this to extend the String class. It would make the calling code a little neater, but it's just a matter of personal taste in the end.

    public static string MyWeirdFormat(this string str)
    {
        return string.Format("{0} is weird",str);
    }

    public static void Test()
    {
        string myString = "ABCD";
        string weirdString =  myString.MyWeirdFormat();
    }
查看更多
家丑人穷心不美
3楼-- · 2019-04-26 01:26

In my opinion the answer is yes you would put these methods in a Utility (Util) class. On a Java web-based application that I am currently working on we actually have 3 such Util classes each of which comprises of only static methods similar to the one you have shown. The reason why we have 3 is one for the client only Util methods, one for server only and a third one for shared Util methods.

Depending on what your app is you may end up with something similar.

As an aside, if you want to learn more about when to use static classes in C#, have a look here.

I hope that answered your question sufficiently.

查看更多
冷血范
4楼-- · 2019-04-26 01:29

Yes, if you have several static methods that are generally related, putting them together in a static utility class is a good idea.

If you're talking about convention, it's also worth noting that naming conventions in most .NET code call for Pascal-cased public members (so FormatString instead of formatString) and camel-cased parameters and fields (so inputString instead of InputString).

查看更多
欢心
5楼-- · 2019-04-26 01:29

If you're making these public, then yes, it might potentially be better to make a utility class of some sort.

That being said, I would try to make it as "general purpose" as possible, since otherwise, they tend to get unmaintainable quickly.

查看更多
\"骚年 ilove
6楼-- · 2019-04-26 01:39

Yes, you could do that. Or you could create a string extension method.

msdn extension methods

For your example above, I would use the string formatter instead of inline concatenation.

string.Format("some formatting {0} some other formatting", inputString )
查看更多
祖国的老花朵
7楼-- · 2019-04-26 01:40

Yes that's fine, your class will then act as a 'library' of related functions. Your other choices for this would be to either pollute the global namespace with various functions or to create a Singleton which would be unneeded since there's no 'state' to account for...

查看更多
登录 后发表回答