Utility classes: static class vs member variable vs local variable - c#

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.

Related

How do I design a class that would normally be static when I'm using dependency injection?

I have a class that encapsulates a bunch of strings that serve as defaults for app settings that haven't been otherwise explicitly specified by the user.
I'm currently using a plain old class with relevantly-named instance methods—this sort of thing:
class SiteConfigurationConventions : ISiteConfigurationConventions
{
public String GetConfigurationFileName()
{
return "SiteConfiguration.xml";
}
}
It seems that a static class would be more conceptually appropriate (like System.Math) since these strings won't ever change at run time and no fields are required, but I'm not sure how compatible static classes are with DI. For example, it doesn't seem possible to register a static class with the container so it returns it to constructors asking for it in other objects being resolved by the container.
As it is now, I register
container.RegisterType<ISiteConfiguration, SiteConfiguration>();
So that the requesting constructor gets what it needs:
public SiteGenerator(ISiteConfiguration siteConfiguration)
My design options would seem to be:
Refactor to a static class and reference the concrete type directly in my consuming class rather than using constructor injection
Leave it as-is (class and instance resolved to an interface), perhaps optionally registering it using the singleton lifetime for the sake of correctness
Creatging some kind of facade or factory to hide the static behind. However, for some reason this options just strikes me as silly.
The notion of an "instance" of a class like this seems odd—static seems more conceptually correct. The only reason I'd be making it an instantiable class is to make it more DI friendly. Does that sound OK, or correct? Am I missing something entirely?
Any counsel would be most appreciated. :)
Most DI libraries give you the option to specify that a single instance can be used for all injections (creates a single instance and give that as the answer every time). This is a form of Singleton, and would probably suit your problem well.
For example, using MS Unity library, you would put:
container.RegisterInstance(new SiteConfiguration());
I consider the static keyword to be a form of built-in singleton implementation, while the DI route does much the same thing, but without using the compiler to take care of the details.
OK, after a bit of research, Googling, and thinking, I believe I've arrived at my own conclusions.
The use of static classes is in a sense at odds with the IoC principle and loose coupling that I intend to bake into my architecture. The static modifier is a way of saying that only one implementation can answer a particular purpose, which is at odds with DI generally (loose coupling, programming to interfaces, testability, and all the things that go with that).
Equally, the static modifier is really just a way of telling the compiler we want to restrict the number of instances of a class to one while simultaneously never allowing it to be assigned to a variable (i.e., no use of the new operator). If we are to employ IoC, we should be leaving lifestyle management like this up to the composition root, and we're never directly referencing concrete classes (other than FCL classes) this way anyway. So static classes serve little purpose to us.
Therefore, I say leave it as a plain old (non-static) class and apply a singleton lifestyle at the composition root. Unless, of course, you think your would-be static class is unlikely ever to change and that you'll never need to fake it in testing, in which case you could just treat it like a stable dependency (like an FCL class) and exclude it from your normal DI scheme, referencing the concrete class directly in consuming classes.
If you must depend on a third-party class that uses static methods or is itself entirely static that you want to inject as a dependency (and thus be able to substitute for testing, etc., purposes), you should perhaps still create an interface and rely on an instantiable adapter that calls the static methods to get those values.

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.

Why choose a static class over a singleton implementation?

The Static Vs. Singleton question has been discussed before many times in SO.
However, all the answers pointed out the many advantages of a singleton.
My question is - what are the advantages of a static class over a singleton?
Why not simply choose a singleton every time?
Static class is a technical tool in your box - basically a language feature.
Singleton is an architectural concept.
You may use a static class as a means to implement the singleton concept. Or you may use some other approach.
With static classes in C# there are two potential dangers if you're not careful.
The requested resources will not be freed until the end of application life
The values of static variables are shared within an application. Especially bad for ASP.NET applications, because these values will then be shared between all users of a site residing in a particular Application Domain.
From MSDN
Static classes and class members are used to create data and functions
that can be accessed without creating an instance of the class. Static
class members can be used to separate data and behavior that is
independent of any object identity: the data and functions do not
change regardless of what happens to the object. Static classes can be
used when there is no data or behavior in the class that depends on
object identity.
A key point is that static classes do not require an instance reference. Also note that static classes are specifically enabled by the language and compiler.
Singleton classes are just user coded classes implementing the Singleton design pattern. Singleton purpose is to restrict instantiation of an class to a single instance.
If you coded every static class as a singleton you'd have to instantiate the class every time you used it.
i.e.
Console.WriteLine('Hello World');
would become
Console c = Console.getInstance();
c.WriteLine('Hello World');
I'd say they're both (generally) poor solutions. There are a few use cases for static classes, primarily simple utility ones (Extension Methods in C# 3.0 come to mind). With any degree of complexity, though, testability issues start cropping up.
Say class A depends on static class B. You want to test class A in isolation. That's hard.
So you go with a Singleton. You have the same problem - class A depends on singleton B. You can't test class A in isolation.
When class B has other dependencies (such as hitting a database) or is mutable (other classes can change its global state), the problem is exacerbated.
IoC (Inversion of Control) container libraries are one solution to this problem; they let you define Plain Old Classes as having a long lifespan. When combined with a mocking library, they can make your code very testable.
Static classes are much easier to implement - I have seen many attempts at thread-safe singletons in C# that employs naive locking schemes instead of depending on the run-time's guaranteed one-time initialization of static fields (optionally inside a nested class to delay instantiation).
Other than that, I think singletons are great if you need to pass around a reference to an object that implements a specific interface, when that 'implemention' should be singleton, something which you cannot do with static classes.
One consideration I don't see mentioned is that preferring a solution using an instance of a class (singletons, or their DI equivalent) allows you to provide a class on which other users of your code may define extension methods -- since extension methods only work with non-static classes as the this parameter. In other words, if you have a line like:
GlobalSettings.SomeMethod();
Then syntactically the only thing that can be accessed via GlobalSettings are members you provide. In contrast, if GlobalSettings is an instance (singleton or otherwise) then consumers may add their own extensions to GlobalSettings that they would be unable to do otherwise:
application.GlobalSettings.CustomSomethingOrOther();
or
GlobalSettings.Instance.CustomSomethingOrOther();
The question leads to the need for a better understanding of what you are implementing, how it suppose to work, and what it should be capable of.
Let's say, you need some kind of Manager class that handles your object's in a particular way. Singleton requires a bit more work, but in return, it gives you the ability to treat your manager by its interface (IManager) rather than the strict name. With a static class, you obviously losing the inheritance, interfaces, and the ability to swap or reset the object by just re-instantiating it rather than manually zeroing all the static variables, but it also gets you rid of a bit of extra work in case if your static object is kept simple.
There are more extra details if you go deeper, but in general 99% of times, it's just a question of personal preference or your team's coding guidelines.

Utility classes.. Good or Bad?

I have been reading that creating dependencies by using static classes/singletons in code, is bad form, and creates problems ie. tight coupling, and unit testing.
I have a situation where I have a group of url parsing methods that have no state associated with them, and perform operations using only the input arguments of the method. I am sure you are familiar with this kind of method.
In the past I would have proceeded to create a class and add these methods and call them directly from my code eg.
UrlParser.ParseUrl(url);
But wait a minute, that is introducing a dependency to another class. I am unsure whether these 'utility' classes are bad, as they are stateless and this minimises some of the problems with said static classes, and singletons. Could someone clarify this?
Should I be moving the methods to the calling class, that is if only the calling class will be using the method. THis may violate the 'Single Responsibilty Principle'.
From a theoretical design standpoint, I feel that Utility classes are something to be avoided when possible. They basically are no different than static classes (although slightly nicer, since they have no state).
From a practical standpoint, however, I do create these, and encourage their use when appropriate. Trying to avoid utility classes is often cumbersome, and leads to less maintainable code. However, I do try to encourage my developers to avoid these in public APIs when possible.
For example, in your case, I feel that UrlParser.ParseUrl(...) is probably better handled as a class. Look at System.Uri in the BCL - this handles a clean, easy to use interface for Uniform Resource Indentifiers, that works well, and maintains the actual state. I prefer this approach to a utility method that works on strings, and forcing the user to pass around a string, remember to validate it, etc.
Utility classes are ok..... as long as they don't violate design principles. Use them as happily as you'd use the core framework classes.
The classes should be well named and logical. Really they aren't so much "utility" but part of an emerging framwework that the native classes don't provide.
Using things like Extension methods can be useful as well to align functionality onto the "right" class. BUT, they can be a cause of some confusion as the extensions aren't packaged with the class they extend usually, which is not ideal, but, still, can be very useful and produce cleaner code.
You could always create an interface and use that with dependency injection with instances of classes that implement that interface instead of static classes.
The question becomes, is it really worth the effort? In some systems, the answer in yes, but in others, especially smaller ones, the answer is probably no.
This really depends on the context, and on how we use it.
Utility classes, itself, is not bad. However, It will become bad if we use it the bad way. Every design pattern (especially Singleton pattern) can easily be turned into anti-pattern, same goes for Utility classes.
In software design, we need a balancing between flexibility & simplicity. If we're going to create a StringUtils which is only responsible for string-manipulation:
Does it violate SRP (Single Responsibility Principle)? -> Nope, it's the developers that put too much responsibilities into utility classes that violate SRP.
"It can not be injected using DI frameworks" -> Are StringUtils implementation gonna varies? Are we gonna switch its implementations at runtime? Are we gonna mock it? Of course not.
=> Utility classes, themselve, are not bad. It's the developers' fault that make it bad.
It all really depends on the context. If you're just gonna create a utility class that only contains single responsibility, and is only used privately inside a module or a layer. Then you're still good with it.
I agree with some of the other responses here that it is the classic singleton which maintains a single instance of a stateful object which is to be avoided and not necessarily utility classes with no state that are evil. I also agree with Reed, that if at all possible, put these utility methods in a class where it makes sense to do so and where one would logically suspect such methods would reside. I would add, that often these static utility methods might be good candidates for extension methods.
I really, really try to avoid them, but who are we kidding... they creep into every system. Nevertheless, in the example given I would use a URL object which would then expose various attributes of the URL (protocol, domain, path and query-string parameters). Nearly every time I want to create a utility class of statics, I can get more value by creating an object that does this kind of work.
In a similar way I have created a lot of custom controls that have built in validation for things like percentages, currency, phone numbers and the like. Prior to doing this I had a Parser utility class that had all of these rules, but it makes it so much cleaner to just drop a control on the page that already knows the basic rules (and thus requires only business logic validation to be added).
I still keep the parser utility class and these controls hide that static class, but use it extensively (keeping all the parsing in one easy to find place). In that regard I consider it acceptable to have the utility class because it allows me to apply "Don't Repeat Yourself", while I get the benefit of instanced classes with the controls or other objects that use the utilities.
Utility classes used in this way are basically namespaces for what would otherwise be (pure) top-level functions.
From an architectural perspective there is no difference if you use pure top-level "global" functions or basic (*) pure static methods. Any pros or cons of one would equally apply to the other.
Static methods vs global functions
The main argument for using utility classes over global ("floating") functions is code organization, file and directory structure, and naming:
You might already have a convention for structuring class files in directories by namespace, but you might not have a good convention for top-level functions.
For version control (e.g. git) it might be preferable to have a separate file per function, but for other reasons it might be preferable to have them in the same file.
Your language might have an autoload mechanism for classes, but not for functions. (I think this would mostly apply to PHP)
You might prefer to write import Acme:::Url; Url::parse(url) over import function Acme:::parse_url; parse_url();. Or you might prefer the latter.
You should check if your language allows passing static methods and/or top-level functions as values. Perhaps some languages only allow one but not the other.
So it largely depends on the language you use, and conventions in your project, framework or software ecosystem.
(*) You could have private or protected methods in the utility class, or even use inheritance - something you cannot do with top-level functions. But most of the time this is not what you want.
Static methods/functions vs object methods
The main benefit of object methods is that you can inject the object, and later replace it with a different implementation with different behavior. Calling a static method directly works well if you don't ever need to replace it. Typically this is the case if:
the function is pure (no side effects, not influenced by internal or external state)
any alternative behavior would be considered as wrong, or highly strange. E.g. 1 + 1 should always be 2. There is no reason for an alternative implementation where 1 + 1 = 3.
You may also decide that the static call is "good enough for now".
And even if you start with static methods, you can make them injectable/pluggable later. Either by using function/callable values, or by having small wrapper classes with object methods that internally call the static method.
They're fine as long as you design them well ( That is, you don't have to change their signature from time to time).
These utility methods do not change that often, because they do one thing only. The problem comes when you want to tight a more complex object to another. If one of them needs to change or be replaced, it will be harder to to if you have them highly coupled.
Since these utility methods won't change that often I would say that is not much problem.
I think it would be worst if you copy/paste the same utility method over and over again.
This video How to design a good API and why it matters by Joshua Bloch, explains several concepts to bear in mind when designing an API ( that would be your utility library ). Although he's a recognized Java architect the content applies to all the programming languages.
Use them sparingly, you want to put as much logic as you can into your classes so they dont become just data containers.
But, at the same time you can't really avoid utilites, they are required sometimes.
In this case i think it's ok.
FYI there is the system.web.httputility class which contains alot of common http utilities which you may find useful.

Method can be made static, but should it?

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

Categories