Method can be made static, but should it? - c#

ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?

Performance, namespace pollution etc are all secondary in my view. Ask yourself what is logical. Is the method logically operating on an instance of the type, or is it related to the type itself? If it's the latter, make it a static method. Only move it into a utility class if it's related to a type which isn't under your control.
Sometimes there are methods which logically act on an instance but don't happen to use any of the instance's state yet. For instance, if you were building a file system and you'd got the concept of a directory, but you hadn't implemented it yet, you could write a property returning the kind of the file system object, and it would always be just "file" - but it's logically related to the instance, and so should be an instance method. This is also important if you want to make the method virtual - your particular implementation may need no state, but derived classes might. (For instance, asking a collection whether or not it's read-only - you may not have implemented a read-only form of that collection yet, but it's clearly a property of the collection itself, not the type.)

Static methods versus Instance methods
Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that).
Rule CA1822 in FxCop or Code Analysis states:
"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at
runtime for each call that ensures the current object pointer is
non-null. This can result in a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue."
Utility Class
You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).

Marking a method as static within a class makes it obvious that it doesn't use any instance members, which can be helpful to know when skimming through the code.
You don't necessarily have to move it to another class unless it's meant to be shared by another class that's just as closely associated, concept-wise.

I'm sure this isn't happening in your case, but one "bad smell" I've seen in some code I've had to suffer through maintaining used a heck of a lot of static methods.
Unfortunately, they were static methods that assumed a particular application state. (why sure, we'll only have one user per application! Why not have the User class keep track of that in static variables?) They were glorified ways of accessing global variables. They also had static constructors (!), which are almost always a bad idea. (I know there are a couple of reasonable exceptions).
However, static methods are quite useful when they factor out domain-logic that doesn't actually depend on the state of an instance of the object. They can make your code a lot more readable.
Just be sure you're putting them in the right place. Are the static methods intrusively manipulating the internal state of other objects? Can a good case be made that their behavior belongs to one of those classes instead? If you're not separating concerns properly, you may be in for headaches later.

This is interesting read:
http://thecuttingledge.com/?p=57
ReSharper isn’t actually suggesting you make your method static.
You should ask yourself why that method is in that class as opposed to, say, one of the classes that shows up in its signature...
but here is what ReSharper documentaion says:
http://confluence.jetbrains.net/display/ReSharper/Member+can+be+made+static

Just to add to #Jason True's answer, it is important to realise that just putting 'static' on a method doesn't guarantee that the method will be 'pure'. It will be stateless with regard to the class in which it is declared, but it may well access other 'static' objects which have state (application configuration etc.), this may not always be a bad thing, but one of the reasons that I personally tend to prefer static methods when I can is that if they are pure, you can test and reason about them in isolation, without having to worry about the surrounding state.

For complex logic within a class, I have found private static methods useful in creating isolated logic, in which the instance inputs are clearly defined in the method signature and no instance side-effects can occur. All outputs must be via return value or out/ref parameters. Breaking down complex logic into side-effect-free code blocks can improve the code's readability and the development team's confidence in it.
On the other hand it can lead to a class polluted by a proliferation of utility methods. As usual, logical naming, documentation, and consistent application of team coding conventions can alleviate this.

You should do what is most readable and intuitive in a given scenario.
The performance argument is not a good one except in the most extreme situations as the only thing that is actually happening is that one extra parameter (this) is getting pushed onto the stack for instance methods.

ReSharper does not check the logic. It only checks whether the method uses instance members.
If the method is private and only called by (maybe just one) instance methods this is a sign to let it an instance method.

I hope you have already understood the difference between static and instance methods. Also, there can be a long answer and a short one. Long answers are already provided by others.
My short answer: Yes, you can convert them to static methods as ReSharper suggests. There is no harm in doing so. Rather, by making the method static, you are actually guarding the method so that you do not unnecessarily slip any instance members into that method. In that way, you can achieve an OOP principle "Minimize the accessibility of classes and members".
When ReSharper is suggesting that an instance method can be converted to a static one, it is actually telling you, "Why the .. this method is sitting in this class but it is not actually using any of its states?" So, it gives you food for thought. Then, it is you who can realize the need for moving that method to a static utility class or not. According to the SOLID principles, a class should have only one core responsibility. So, you can do a better cleanup of your classes in that way. Sometimes, you do need some helper methods even in your instance class. If that is the case, you may keep them within a #region helper.

If the functions are shared across many pages, you could also put them in a base page class, and then have all asp.net pages using that functionality inherit from it (and the functions could still be static as well).

Making a method static means you can call the method from outside the class without first creating an instance of that class. This is helpful when working with third-party vendor objects or add-ons. Imagine if you had to first create a Console object "con" before calling con.Writeline();

It helps to control namespace pollution.

Just my tuppence: Adding all of the shared static methods to a utility class allows you to add
using static className;
to your using statements, which makes the code faster to type and easier to read. For example, I have a large number of what would be called "global variables" in some code I inherited. Rather than make global variables in a class that was an instance class, I set them all as static properties of a global class. It does the job, if messily, and I can just reference the properties by name because I have the static namespace already referenced.
I have no idea if this is good practice or not. I have so much to learn about C# 4/5 and so much legacy code to refactor that I am just trying to let the Roselyn tips guide me.
Joey

Related

Utility classes: static class vs member variable vs local variable

I'm creating a utility class CommonDaoOperations that contains several generic methods: Create, Update, Delete.
This is not a base class because some DAOs are more complex and can't use these generic methods, but many DAOs can.
I'm now pondering how that utiliy class should look like exactly:
static class with only static generic methods
regular class with generic methods, created once per DAO as private readonly member
regular class with generic methods, created once per DAO method (in each call)
Creating an instance of a class per DAO / method obviously costs more than calling a static method, but I'm pretty sure that these costs are negligable in almost any application.
I'd favor solution 2 or 3 because of the benefits of non-static classes (interfaces, can be mocked, can be derived / enhanced, could gather parameters via constructor in the future should it be necessary (compared to a 10-parameter-method in a static class)).
So I guess the real question is: should I be creating my utility class as a member variable, or instantiate it per DAO method?
public void Create(User user) {
new CommonDaoOperations().Create(user);
}
public void Delete(User user) {
var daoOps = new CommonDaoOperations();
daoOps.CheckSomething(); // just an example of multiple calls to the class
daoOps.Delete(user);
}
I'm interested to hear what other devs think about any of these approaches, or if there's still anothere / better way to do this.
Edit
Just realized that I should have given approach #3 more thought - as Vadim pointed out, replacing the concrete class would be cumbersome when it's instantiated in each method, but I could factor that in a property:
private CommonDaoOperations DaoOps {
get { return new CommonDaoOperations(); }
}
public void Create(User user) {
DaoOps.Create(user);
}
I believe this to be more maintianable than the above snippet, however know I introduced a property for a 'utility' class in my DAO, which might be a code smell by itself (as Ant P pointed out).
Summary
This was a tough decision - while I accepted the answer from Ant P, Vadim's answer is also legitimate. Which approach to use depends on the utility class, all 3 approaches have their uses (except the updated #3). At least that is my take of the provided answers.
Static classes do have their uses, but also many downsides as briefly mentioned above.
Regular class, instantiated per method: the utiliy class is created and used just where it is required. Reduces dependencies, keeps your type pure.
Regular class, instantiated as member: when many/all methods require an instance of the utility class, it may be a better idea to create a member variable. Changing the type or how it is instantiated becomes easier this way.
I will let those more qualified comment on the performance implications; however, here are my thoughts on each:
1. Static class
This concept is fine for simple, 'uncomprehensive' utility methods that require no real extensibility but - as you note yourself - your common DAO operations stand to grow considerably more sophisticated. This is unlikely to be very manageable as a single static class, particularly when it's used across multiple different types of DAO.
2. Concrete class, instantiated per-DAO object
This is all fine and dandy, but do you really need the utility class to be a member of the individual DAO? I could understand this if you needed some kind of consistency or state persistence within the utility class, across the lifetime of the DAO, but it seems that these methods are fairly nebulous (true to its name as a "utility" class).
Which leaves 3. Concrete class, instantiated per method. This seems the most natural solution to me. This gives you the flexibility to make use of all of the advantages of a concrete class as you acknowledge in your question, while restricting the scope of the object to where it's needed - the individual method call.
Should your class evolve into something that's needed across the entire DAO, e.g. you suddenly need to maintain the state of the object (or if you need to inject it into the DAO's constructor, or something else along those lines), you can always change where it's instantiated (though it seems to me that, if this happens, you don't really have a utility class any more and you need to reconsider how this class fits into your architecture).
Unless you plan to create an exceptionally large number of these objects, I don't think it'll affect performance.
I would prefer (2). There's simply need to create it for each use, that's just writing code for nothing. In addition, if you'd ever want to use some sort of IOC, get the utility class as a parameter, change the way it is initialized or simply change the class to another class - having a single member to change is a lot easier than changing all the places where it's used.
Unless you have a very good reason, stay away from statics or Singletons. (an example of a very good reason is something like developing an addon or a plugin in which you don't control the way your classes are initialized and used).
When considering the difference and usages between static classes and concrete classes sure there are implications to take in mind, see the testability for example (but this is not so sure at all as shown after), but there are first of all, some assumptions to do:
instance classes have state, manage state, and behaviors are related to it's internal state, if operations are not related to internal state in some ways, these are truly candidates for static methods, but I will say more after about that. This is the base even for encapsulation, and goes hand by hand with SRP (Single Responsibility Principle) which says that a class should have a single responsibility, doing one thing and no more, so, this gives you the fact that methods are all related to it's internal state directly or indirectly
static classes haven't and don't manage state. Maybe some one could say that it's not true at all, see singletons. Well, singleton's maybe good, but singletons designed as static classes are too close to anti-pattern, in this case, singletons could be managed as IoC containers does, by managing justo one instance at all. If needed I could provide some examples about with and without containers.
Well, someone says static classes are something close to anti-pattern, because for example testability.. well, this is non true, and this depends of what the static class and test which involves to is related.
I will report a very good example on that by on of the great software architect at all, Udi Dahan, which for example, in a good article about Domain Events, he talks between other things, about static classes and testability, here the link Domain Events Salvation if you go to the section How to raise domain events and Unit testing with domain events, he talks about that.
After that, as you says, another difference about the two, is about memory cost, but others says about that. Take in mind that, tools like Reshaper, makes suggestions to transform instance classes/methods which doesn't handle state to the static representation, this in advantage of memory and usage.
The last words about your design: CommonDaoOperations seems to a truly static class which doesn't handle state, so it's a good candidate to be a static class, for it's nature, for jobs it does. You can instead treat it as "singleton" using a IoC container and configuring that class in the right way. There are many ways to accomplish that in other ways without Containers.. here a simple article which talks about singletons and static classes C# Singleton, Static Class. Sure making a property which returns the helper is not so a good design, and a property which returns a new instance for a get operation is always a bad design, it will be justified with solid reasons...
So seeing your design and how you use the helper class, the words says by Udi in the link above describe well the solution you should implement.

Is it acceptable to use extension methods on a class which you can modify

I've recently been toying with the idea of using extension methods to implement helper utilities on classes which I control (ie, are in the same program and I can modify). The rationale behind it is that many times, these helper utilities are used in very specific scenarios and don't require access to the classes internal values.
For instance, let's say I have a StackExchange class. It'd have methods like PostQuestion and Search and AnswerQuestion.
Now, what if I wanted to manually calculate my reputation to ensure that StackOverflow isn't cheating me. I'd implement something along the lines of:
int rep=0;
foreach(var post in StackExchangeInstance.MyPosts)
{
rep+=post.RepEarned;
}
I could add a method to the StackExchange class, but it doesn't require any internals, and it is only used from one or two other portions of the program.
Now imagine if instead you had 10 or 20 of these specific helper methods. Useful in a certain scenario for sure, but definitely not for the general case. My idea is changing something like
public static RepCalcHelpers
{
public static int CalcRep(StackExchange inst){ ... }
}
To something like
namespace Mynamespace.Extensions.RepCalculations
{
public static RepCalcExtensions
{
public static int CalcRep(this Stackexchange inst){...}
}
}
Note the namespace. I'd ideally use this to group extension methods within a certain scenario. For instance, "RepCalculations", "Statistics", etc.
I've tried searching for if this type of pattern is at all heard of, and haven't found any evidence of extension methods being used for anything but classes you can't modify.
What shortcomings are there with this "pattern"? Should I instead stick to inheritance or composition, or just a good ol' static helper class for this?
I would read the section of Framework Design Guidelines on Extension methods. Here is a post by one of the authors for the 2nd edition. The use case you are describing
(specialized helper methods) is cited by Phil Haack as a valid use for extension methods with the drawback that it requires extra knowledge of the API to find those "hidden" methods.
Not mentioned in that post but recommended in the book is that the extension methods go into a separate namespace from the extended class. Otherwise, they will always appear with intellisense and there is no way to turn them off.
I think I have seen this pattern somewhere else. It could quite confusing, but also quite powerful. That way you can provide a class in a library and a set of extension methods in separate namespace. Then whoever is using your library can choose to import namespace with your extension methods or provide their own extension methods.
A good candidate for this pattern would be if you have some extension methods used for unit testing only (e.g. to compare if two objects are equal in a sense you'd need for unit tests only).
You seem to be making the comparison that the extension method is equivalent to a public instance method. It's really not.
An extension method is just a public static utility method that happens to have a more convenient syntax for being called.
So first we have to ask ourselves, it it appropriate for this method to be an instance method of the class itself or is it more appropriate for it to be a static method of an external class. The fact that very few users of the class need this functionality because it's highly localized and not truly behavior that the class itself performs but rather behavior performed on the class by an external entity means that it's appropriate for it to be static. The primary drawback is that it's behavior that is potentially harder to find if someone has a User and wants to recalculate their rep. Now, in this particular case it's a bit on the fence, and you could go the other way, but I am leaning towards static method.
Now that we've decided it should be static it's an entirely separate question of whether or not it should be an extension method or not. This is much more subjective and goes into the personal preference realm. Are the methods likely to be chained? If so, extension methods chain much more nicely than nested calls to static methods. Is it likely to be used a lot in the files that do use it? If yes, extension methods are likely going to simplify the code a bit, if not, it doesn't really help as much, or even hurts. To the toy example I'd probably say that I personally wouldn't, but I wouldn't have any problem at all with someone who did (after all you can still use an extension method as if it's a regular public static method syntax wise). For a non-toy example, it's mostly a case-by-case decision. A key point is to be careful what classes you extend, and to ask yourself if a user is willing to clutter the Intellisense of a type just to call a methods slightly more conveniently (this again gets back to how much it's used per file it's used in).
It's also worth mentioning that there are a few edge cases where extension methods can be more powerful than instanced methods. In particular through utilizing type inference. With a regular instance method it's easy enough to accept a type or any sub-type of that type, but sometimes it's useful to return whatever the type is that was passed in instead of the parent type. This is used particularly in fluent APIs. This isn't a very common example though, and is only loosely related to your question, so I won't expand on that.
Extension methods could be very useful in cases where you class implements an interface and you want to avoid having to implement the same method on other "future" classes that implement the same interface. For example, StackExchange implements IStackExchange and ProgrammersExchange also implements IStackExchange. Your example extension method would be useful for implementing the CalcRep just once, and not having to re-implement it on both classes. This is exactly the reason for all the extension methods present in the static Enumerable class.
Other than this I dont see a compelling reason for using extension methods on a class you can already modify. If anything it has the disadvantage of being considered late in the overload resolution process.

Do extension methods benefit in any practical way from being a part of a static class vs. [theoretically] a part of a namespace?

When it comes to extension methods class names seem to do nothing, but provide a grouping which is what name-spaces do. As soon as I include the namespace I get all the extension methods in the namespace. So my question comes down to this: Is there some value I can get from the extension methods being in the static class?
I realize it is a compiler requirement for them to be put into a static class, but it seems like from an organizational perspective it would be reasonable for it to be legal to allow extension methods to be defined in name-spaces without classes surrounding them. Rephrasing the above question another way: Is there any practical benefit or help in some scenario I get as a developer from having extension methods attached to the class vs. attached to the namespace?
I'm basically just looking to gain some intuition, confirmation, or insight - I suspect it's may be that it was easiest to implement extension methods that way and wasn't worth the time to allow extension methods to exist on their own in name-spaces.
Perhaps you will find a satisfactory answer in Eric Lippert's blog post Why Doesn't C# Implement "Top Level" Methods? (in turn prompted by SO question Why C# is not allowing non-member functions like C++), whence (my emphasis):
I am asked "why doesn't C# implement feature X?" all the time. The
answer is always the same: because no one ever designed, specified,
implemented, tested, documented and shipped that feature. All six of
those things are necessary to make a feature happen. All of them cost
huge amounts of time, effort and money. Features are not cheap, and we
try very hard to make sure that we are only shipping those features
which give the best possible benefits to our users given our
constrained time, effort and money budgets.
I understand that such a general answer probably does not address the
specific question.
In this particular case, the clear user benefit was in the past not
large enough to justify the complications to the language which would
ensue. By restricting how different language entities nest inside each
other we (1) restrict legal programs to be in a common, easily
understood style, and (2) make it possible to define "identifier
lookup" rules which are comprehensible, specifiable, implementable,
testable and documentable.
By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified
identifier used in an invocation context; such a thing is always an
invocable member of the current type (or a base type).
To me putting them in the class is all about grouping related functions inside a class. You may have a number of extension methods in the same namespace. If I wanted to write some extension methods for the DirectoryInfo and FileInfo classes I would create two classes in an IO namespace called DirectoryInfoExtensions and FileInfoExtensions.
You can still call the extension methods like you would any other static method. I dont know how the compiler works but perhaps the output assembly if compiled for .net 2 can still be used by legacy .net frameworks. It also means the existing reflection library can work and be used to run extension methods without any changes. Again I am no compiler expert but I think the "this" keyword in the context of an extension method is to allow for syntactical sugar that allows us to use the methods as though they belong to the object.
The .NET Framework requires that every method exist in a class which is within an assembly. A language could allow methods or fields to be declared without an explicitly-specified enclosing class, place all such methods in assembly Fnord into a class called Fnord_TopLevelDefault, and then search the Fnord_TopLevelDefault class of all assemblies when performing method lookup; the CLS specification would have to be extended for this feature to work smoothly for mixed-language projects, however. As with extension methods, such behavior could be CLS compliant if the CLS didn't acknowledge it, since code in a language which didn't use such a feature could use a "free-floating" method Foo in assembly Fnord by spelling it Fnord_TopLevelDefault.Foo, but that would be a bit ugly.
A more interesting question is the extent to which allowing an extension method Foo to be invoked from an arbitrary class without requiring a clearly visible reference to that class is less evil than would be allowing a non-extension static methods to be likewise invoked. I don't think Math.Sqrt(x) is really more readable than Sqrt; even if one didn't want to import Math everywhere, being able to do so at least locally could in some cases improve code legibility considerably.
They can reference other static class members internally.
You should not only consider the consumer side aspect, but also the code maintenance aspect.
Even though intellisense doesn't distinguish with respect to the owner class, the information is still there through tool tips and whatever productivity tools you have added to your IDE. This can easily be used to provide some context for the method in what otherwise would be a flat (and sometimes very long) list.
Consumer wise, bottom line, I do not think it matters much.

Is it better to use static functions if no class members are needed?

I have a member function that does not depend on any member variables of the class. (in my case the class is an ASP.Net Page)
The function is protected, I dont need it outside of this class. Its only purpose is to build an URL from an given object.
Should I make all my functions static if they dont depend on the class, even if they are not used outside of this class?
Is there any reason like performance or maintainability to do so?
Probably, but I'd take it a step further.
In these situations you really want to ask yourself if the method still belongs with the type at all. If this method has no dependence on the type's data, why is it part of that type? Is there a better or more appropriate type? Do you have several of these, perhaps scattered among a few different types, that could be logically grouped together?
It is good practive to make functions that don't interact with member data static. It just helps describe how the function interacts with its environment. There should be no performance issues though.
Yes; they should be static.
I can't say I know enough about the performance, but I've heard that it's a good idea to make it static if it doesn't depend on class members. Usually it gives you the benefit of not having to waste an allocation in case you just need that method, but since it's just inside the class for you, you're probably already working with an instance of your object. I would make it static, but in your case I don't know if there's much difference (from a coding perspective).
If you make the method static you will not need to instantiate a class to use it. This will be quicker. Also, if its static I find it makes the code a little shorter.
I dont think there are any performance issues with static, if anything its quicker. Just think of all the extension methods that have appeared in newer versions of .net. they are all static!
It depends actually. Whether your method uses any instance data or not is an implementation detail of this method. If it's private than you can make it static if you want. However, if it can be visible outside of your class (e.g. it's protected method) you should think about interface first and make it static only if it would never make sense for this method to access object data.

When to go for static classes?

Whenever I code a solution to something I tend to either use a lot of static classes or none at all. For example in a recent project I had to send a class with some string/bool/datetime data through a number of hoops and the only thing that wasn't static was this data-holding class. Everything else (3 pretty hefty classes with different processing responsibilities) were static.
I think what I'm asking for here is some input on when (and why) I should avoid using static classes for these "process X, output Y" cases. Is it ok to always use them as long as they work or am I shooting myself in the foot concerning scalability, plugin-support etc?
I hope this is an OK question to ask here. I'm not asking for an argument concerning whether or not static classes are "better" - just input on when I should avoid using them.
Most of the code i write:
Uses dependency injection/IoC
And needs to be mockable/testable
So i just use objects for almost everything.
I do still use statics for things like:
Extension methods
Constants
Helper/Utility methods (pre extension methods)
operator methods
Still the two questions remain a bit the same. My main concern on static classes is inheritance and accessability.
When using a static class (public in the worst case), everyone is able to access your processes and functions. Which is most of the time not what you want. It is too easy for some object to get to your functions and do some modifications. Therefore, dependency injection is nice to use. (Pass the object you want to modify in the parameters, which is in this case your process-object).
To prevent others from manipulating your process-object, why not try to use some kind of singleton pattern (or even an ex-singleton pattern), so there is actually a real object to talk to? You can pass the object into the parameters of your functions if something should be modified. And then you can just have one manager that holds your process-object. Others shouldn't get to the object.
Static classes are also hard to inherit. Overriding static methods seems a bit strange. So if you are sure that the process will not be the only process, and some more specific processes will be created by you, then a static class should be avoided as well.
Static classes are commonly used for small data containers and general methods. It should not contain large data until unless required. These classes are non-extensible.
I would recommend you to have a method as static if it has only one method. In this case creating an instance of the class hardly makes sense
You can have static properties in case you want a field to act somewhat like global variable. This is a design pattern which matches Singleton pattern
I use static properties for tracking state which needs to be consumed by the whole application.
For rest everything related to my work objects is the way to go (with minor exceptions obviously)
Making extensive use of statics is like puting your application into concrete. They should be avoided except for very particular situations like utility/helper methods that are very general. A nice list was posted in a previous answer by djeeg.
The main problem I see with using static classes as you describe is that the dependencies are hardwired. If class A needs to use features from class B, it must explicitly know about it, which results in tight coupling.
While this is not always a problem, as your code grows you might find it more difficult to alter the behavior of the program to accommodate new requirements. For example, if you want to make the behavior of the program configurable, it will be difficult because that will require explicit if / switch in the code. Otherwise, you could simply make a class depend on an interface and swap implementations.
In short, you are preventing yourself from using well known design patterns that are known good solutions to solve issues you will likely encounter.
I usually try to avoid using static methods in classes. If I need to access some data globally I would at least wrap a class in a singleton. For larger projects I would recommend using an Inversion of Control container to instantiate and inject your "global" instances in a Singleton way.

Categories