Appropriate use of Static Method

2019-04-26 01:33发布

问题:

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?

回答1:

I'd agree with the other answers so far that it certainly makes sense a lot of the time.

Sometimes, you may want to actually give yourself a little more flexibility by defining an interface and implementing that with instance methods. This gives you the option of using different methods in your code down the road.

Here's an example of what I mean. Say you are using this formatString method of yours in some code somewhere that looks like this:

public void DumpToConsole()
{
    foreach (DataField field in m_fields)
    {
        Console.WriteLine(StringUtils.formatString(field.ToString()));
    }
}

OK, this is great. (Actually, it's stupid, but whatever—for illustration only!) But you could make such a method more flexible by having it accept an interface, of which you might have various implementations which provide completely different sorts of formatting:

public void DumpToConsole(IFormatter<DataField> formatter = null)
{
    // Perhaps you could specify a default. Up to you.
    formatter = formatter ?? Formatter<DataField>.Default;

    foreach (DataField field in m_fields)
    {
        Console.WriteLine(formatter.Format(field));
    }
}

Then instead of StringUtils being a static utility class, it would be merely one implementation of a class that offers a way to format a certain type of object (in your case, string objects; in my example, these imaginary DataField objects).

So this is all a very long-winded way of saying, it depends. If you're aiming for super flexibility down the road, maybe you should consider implementing an interface instead of going with a static helper class.

Do note that in my example above, another completely acceptable way of approaching the problem could've been to accept a Func<T, string> delegate instead of this hypothetical IFormatter<T> interface. This is mostly a stylistic choice, in my opinion. But often interfaces become more realistic when there are multiple behaviors that you want to customize; i.e., defining methods that accept 3, 4, or more delegates can quickly become cumbersome compared to accepting a single interface.



回答2:

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).



回答3:

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.



回答4:

Yes, the static methods in the way you are using them in C# is very similar to C++'s idea of "free functions". It just so happens C# doesn't have free functions. Eric Lippert has an interesting post around here somewhere of why that is the case. A static class is used to group functions of similar utility and would be appropriate if you had several of these that were similar.



回答5:

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...



回答6:

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:

It is if that particular formatting would be useful in more than one place in your code.

If it would make sense only within one specific class, then I'd rather use a private method (static or instance, it wouldn't make a difference).

Utility classes are a useful thing. The only thing you should be careful about is not to use them too often. If most of your code is in utility classes, then you're doing something wrong. But factoring out some common code in helper methods is a perfectly justified use.



回答8:

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


回答9:

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.



回答10:

Personally I'd lean more towards the use of an extension method, still static though ;)

public static class StringExtensions
{
    public static string MyFormat(this string input)
    {
        return string.Format("some formatting {0} Some other formatting", input);
    }
}