Static classes in c# - c#

In answering this question (https://stackoverflow.com/questions/352317/c-coding-question#352327), it got me wondering...
Is there any danger in regarding a static class as being equivalent to a non-static class instatiation that implements the singleton pattern?

The only thing that seems immediately apparent to me is that a static class is basically just a collection of scoped functions (explicitly avoiding "methods" here) and a singleton is still something you can instantiate, even if you can only have 1. 1 > 0.
You can pass a singleton as an argument to something that expects an object of a certain interface, you cannot pass a static class anywhere (except through some reflection trickery)

In many ways, a static class and a singleton are similar. One big difference is that a singleton might implement some interfaces, which isn't possible with a static class. For example, Comparer<T>.Default / EqualityComparer<T>.Default provide (via the interface) the ability to use the item in sorting / dictionary usage.
It is also possible (though tricky) to use a singleton with the standard serialization frameworks. With a static class, you'd have to manage any state persistence manually.

It isn't exactly equivalent. For example you can pass a reference to a singleton instance as an argument, which you can't do with a static class as there isn't an instance.
What do you mean by "danger"?

As Robert Gould pointed out, you loose control over construction. You will also get construction issues which are a lot more obscure. Static classes quickly end up with static initializer blocks. These blocks get called the first time someone references your type, and this order may not be as well defined as you like to think. So the run-order of these static initializers may change without you planning so, and can cause strange bugs.

The main danger that I can see with static classes is that they are much harder to mock when writing unit tests. With a singleton you can create it in such a way that you can inject a different class in its place that does test specific functionality, with a static class this is not so easy.

Not sure about C#, but in C++ a static Object will get initialized when it gets initialized, and you have no direct control over that (especially in multithreaded apps). So you need a function to call your object, not just call it directly (unless you want unportable code)

As Robert said before, the initialization is a main disadvantage of a static class.
The static class will usually be initialized lazily, at the last possible moment. However, you lose control over the exact behavior and static constructors are slow.
Often static classes are used to hold global data. And global data creates an implicit dependency between your other objects / classes. So you must be carful when changing this "global object". Can break your application.

In context of singleton implementation there is no any danger, I think. I often do the same, imlementing singletone via static class. Logically, object reference isn't necessary if it's alone and unique.

Related

Static methods/class vs non static [duplicate]

I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.
I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.
Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?
Hope this makes sense, and my question isn't too basic !
Many thanks
You need to think about static variables as belonging to the class, not to instances of the class.
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.
Best practice is to avoid public static. In OOP, class is meant to hide its members. Static is actually not a member of the instance but of the type.
Static comes handy if you are implementing singleton pattern. But then again they need to be made private and accessible through a public property.
You need to read Static Classes and Static Class Members (C# Programming Guide).
Well I can't conclusively say that one is better, because they serve different purposes.
Are you familiar with OOP? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.
C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).
In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?
The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)
However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)
For the sake of no further complicating things, I'll stop here. Let me know if you misunderstood anything.
Your choice depends on your architecture.
Static makes part of a Type, others make part of an instance of that type. If you want have some shared state (say) between different instances of the same type, use static. If you want that every instance have it's own value, independent from others, use instance fields.
In both cases, by the way, avoid to expose like a public fields, but use properties.
I completely agree with Mr Oded:
If, in all instances of the class this variable should be identical, use a static variable.
If not, use an instance variable.
Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance. And yes, it becomes a global resource, or even a global variable if you will.
But I think there's at least another (heavily edited) good point to be made here...
Using static members as global vars go against OOP
This means once you set a static member you can't pass it around as an object. The more you use static as global var, the more difficult it is for unit testing / mocking classes.
There is a solution for that, Singletons. But they should never come without warnings!
At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern. It's a not well known extension of Singleton pattern. It's so unknown in fact, if you google for it you won't find it with those keywords (toolbox pattern).
So plan ahead. Read more. Get to know about every option so you can decide better. Even get a book. Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.
In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that. This is for sure a principle that you will love to follow.
But despite some of the other answers I cannot say don't use static. Static is not the devil that you should avoid in any case. What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.
Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them. An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances. To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance. Especially if this factor changes in the lifetime of your program to affect the next calculation.
You need to ask a question to youself: why I need x to be static?
If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.
In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.
I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton

How to refactor a singleton class and avoid doing the same mistakes again

I've started a small application in WPF and used a Singleton class to handle all the application logic. Plus I had a few ObservableCollections there that are binded to DataGrids on the View.
The problem: what was supposed to be a small program started to grow in functionality and the code is now too hard to maintain, reuse and there is a high level of code coupling.
And so I've started to move the code to other classes. For example, I've a class that just handles the File readings. I've made this class static because I just run those methods once (when I need to import data to a database), and when they are finished I don't need those objects anymore and just forget that they exist.
Now I'm considering doing the same for other methods, like the ones that retrieve data form the database.
My doubt is if that is that the correct way to solve the problem? I'm afraid that the use of a static classes will be like a multiplication of singletons.
Static classes are considered evil by some people, but that is just an opinion. When I have these questions, I take a look at the .NET-framework: How is it solved inside there?
Sometimes a singleton can be refactored to a static class. It depends on the situation. If your singleton is of a type that inherits (read: must inherit) other classes or interfaces, it cannot be converted to a static class, since a static class cannot inherit anything.
If you create a static class, try to obey the following rules: (These rules are also obeyed by the .NET framework):
All static members must be thread safe.
That's it! :)
The rule sounds simple, but implies a lot:
All static members work independent of each other. So one call will never affect the result of another call.
A static class is not allowed to maintain a (static) state.
If the class has static fields, make sure they are readonly or const. Make sure the content of those fields never changes.
Of course there could be some little exceptions. For example: A static class could maintain an internal dictionary for caching results. Modifying this cache must be thread safe. Since it is internal stuff, for the outside world the static class still obeys the rules stated above.
So... in short: If your singleton is NOT thread safe (holds state, etc.) do NOT convert it to a static class.
* EDIT *
Using a singleton normally means you have a static property containing one instance of a certain type. Since this is a static property it also must obey above rules, which means that the instance must be thread safe.
If your (singleton) instance is not thread safe, redesign your application so it does not use this singleton or static class. Let all code create a new instance of this class when needed.

Is there anything wrong with a class with all static methods?

I'm doing code review and came across a class that uses all static methods. The entrance method takes several arguments and then starts calling the other static methods passing along all or some of the arguments the entrance method received.
It isn't like a Math class with largely unrelated utility functions. In my own normal programming, I rarely write methods where Resharper pops and says "this could be a static method", when I do, they tend to be mindless utility methods.
Is there anything wrong with this pattern? Is this just a matter of personal choice if the state of a class is held in fields and properties or passed around amongst static methods using arguments?
UPDATE: the particular state that is being passed around is the result set from the database. The class's responsibility is to populate an excel spreadsheet template from a result set from the DB. I don't know if this makes any difference.
Is there anything wrong with this
pattern? Is this just a matter of
personal choice if the state of a
class is held in fields and properties
or passed around amongst static
methods using arguments?
Speaking from my own personal experience, I've worked on 100 KLOC applications which have very very deep object hiearchies, everything inherits and overrides everything else, everything implements half a dozen interfaces, even the interfaces inherit half a dozen interfaces, the system implements every design pattern in the book, etc.
End result: a truly OOP-tastic architecture with so many levels of indirection that it takes hours to debug anything. I recently started a job with a system like this, where the learning curve was described to me as "a brick wall, followed by a mountain".
Sometimes overzealous OOP results in classes so granular that it actually a net harm.
By contrast, many functional programming languages, even the OO ones like F# and OCaml (and C#!), encourage flat and shallow hiearchy. Libraries in these languages tend to have the following properties:
Most objects are POCOs, or have at most one or two levels of inheritance, where the objects aren't much more than containers for logically related data.
Instead of classes calling into each other, you have modules (equivalent to static classes) controlling the interactions between objects.
Modules tend to act on a very limited number of data types, and so have a narrow scope. For example, the OCaml List module represents operations on lists, a Customer modules facilitates operations on customers. While modules have more or less the same functionality as instance methods on a class, the key difference with module-based libraries is that modules are much more self-contained, much less granular, and tend to have few if any dependencies on other modules.
There's usually no need to subclass objects override methods since you can pass around functions as first-class objects for specialization.
Although C# doesn't support this functionality, functors provide a means to subclass an specialize modules.
Most big libraries tend to be more wide than deep, for example the Win32 API, PHP libraries, Erlang BIFs, OCaml and Haskell libraries, stored procedures in a database, etc. So this style of programming is battle testing and seems to work well in the real world.
In my opinion, the best designed module-based APIs tend to be easier to work with than the best designed OOP APIs. However, coding style is just as important in API design, so if everyone else on your team is using OOP and someone goes off and implements something in a completely different style, then you should probably ask for a rewrite to more closely match your teams coding standards.
What you describe is simply structured programming, as could be done in C, Pascal or Algol. There is nothing intrinsically wrong with that. There are situations were OOP is more appropriate, but OOP is not the ultimate answer and if the problem at hand is best served by structured programming then a class full of static methods is the way to go.
Does it help to rephrase the question:
Can you describe the data that the static methods operates on as an entity having:
a clear meaning
responsibility for keeping it's internal state consistent.
In that case it should be an instantiated object, otherwise it may just be a bunch of related functions, much like a math library.
Here's a refactor workflow that I frequently encounter that involves static methods. It may lend some insight into your problem.
I'll start with a class that has reasonably good encapsulation. As I start to add features I run into a piece of functionality that doesn't really need access to the private fields in my class but seems to contain related functionality. After this happens a few times (sometimes just once) I start to see the outlines of a new class in the static methods I've implemented and how that new class relates to the old class in which I first implemented the static methods.
The benefit that I see of turning these static methods into one or more classes is, when you do this, it frequently becomes easier to understand and maintain your software.
I feel that if the class is required to maintain some form of state (e.g. properties) then it should be instantiated (i.e. a "normal" class.)
If there should only be one instance of this class (hence all the static methods) then there should be a singleton property/method or a factory method that creates an instance of the class the first time it's called, and then just provides that instance when anyone else asks for it.
Having said that, this is just my personal opinion and the way I'd implement it. I'm sure others would disagree with me. Without knowing anything more it's hard to give reasons for/against each method, to be honest.
The biggest problem IMO is that if you want to unit test classes that are calling the class you mention, there is no way to replace that dependency. So you are forced to test both the client class, and the staticly called class at once.
If we are talking about a class with utility methods like Math.floor() this is not really a problem. But if the class is a real dependency, for instance a data access object, then it ties all its clients in to its implementation.
EDIT: I don't agree with the people saying there is 'nothing wrong' with this type of 'structured programming'. I would say a class like this is at least a code smell when encountered within a normal Java project, and probably indicates misunderstanding of object-oriented design on the part of the creator.
There is nothing wrong with this pattern. C# in fact has a construct called static classes which is used to support this notion by enforcing the requirement that all methods be static. Additionally there are many classes in the framework which have this feature: Enumerable, Math, etc ...
Nothing is wrong with it. It is a more "functional" way to code. It can be easier to test (because no internal state) and better performance at runtime (because no overhead to instance an otherwise useless object).
But you immediately lose some OO capabilities
Static methods don't respond well (at all) to inheritance.
A static class cannot participate in many design patterns such as factory/ service locator.
No, many people tend to create completely static classes for utility functions that they wish to group under a related namespace. There are many valid reasons for having completely static classes.
One thing to consider in C# is that many classes previously written completely static are now eligible to be considered as .net extension classes which are also at their heart still static classes. A lot of the Linq extensions are based on this.
An example:
namespace Utils {
public static class IntUtils {
public static bool IsLessThanZero(this int source)
{
return (source < 0);
}
}
}
Which then allows you to simply do the following:
var intTest = 0;
var blNegative = intTest.IsLessThanZero();
One of the disadvantages of using a static class is that its clients cannot replace it by a test double in order to be unit tested.
In the same way, it's harder to unit test a static class because its collaborators cannot be replaced by test doubles (actually,this happens with all the classes that are not dependency-injected).
It depends on whether the passed arguments can really be classified as state.
Having static methods calling each other is OK in case it's all utility functionality split up in multiple methods to avoid duplication. For example:
public static File loadConfiguration(String name, Enum type) {
String fileName = (form file name based on name and type);
return loadFile(fileName); // static method in the same class
}
Well, personnally, I tend to think that a method modifying the state of an object should be an instance method of that object's class. In fact, i consider it a rule a thumb : a method modifying an object is an instance method of that object's class.
There however are a few exceptions :
methods that process strings (like uppercasing their first letters, or that kind of feature)
method that are stateless and simply assemble some things to produce a new one, without any internal state. They obviously are rare, but it is generally useful to make them static.
In fact, I consider the static keyword as what it is : an option that should be used with care since it breaks some of OOP principles.
Passing all state as method parameters can be a useful design pattern. It ensures that there is no shared mutable state, and so the class is intrinsicly thread-safe. Services are commonly implemented using this pattern.
However, passing all state via method parameters doesn't mean the methods have to be static - you can still use the same pattern with non-static methods. The advantages of making the methods static is that calling code can just use the class by referencing it by name. There's no need for injection, or lookup or any other middleman. The disadvantage is maintanability - static methods are not dynamic dispatch, and cannot be easily subclassed, nor refactored to an interface. I recommend using static methods when there is intrinsicly only one possible implementation of the class, and when there is a strong reason not to use non-static methods.
"state of a class is ...passed around amongst static methods using arguments?"
This is how procedual programming works.
A class with all static methods, and no instance variables (except static final constants) is normally a utility class, eg Math.
There is nothing wrong with making a unility class, (not in an of itself)
BTW: If making a utility class, you chould prevent the class aver being used to crteate an object. in java you would do this by explictily defining the constructor, but making the constructor private.
While as i said there is nothing wrong with creating a utility class,
If the bulk of the work is being done by a utiulity class (wich esc. isn't a class in the usual sense - it's more of a collection of functions)
then this is prob as sign the problem hasn't been solved using the object orientated paradim.
this may or maynot be a good thing
The entrance method takes several arguments and then starts calling the other static methods passing along all or some of the arguments the entrance method received.
from the sound of this, the whole class is just effectivly one method (this would definatly be the case is al lthe other static methods are private (and are just helper functions), and there are no instance variables (baring constants))
This may be and Ok thing,
It's esc. structured/procedual progamming, rather neat having them (the function and it's helper)all bundled in one class. (in C you'ld just put them all in one file, and declare the helper's static (meaning can't be accesses from out side this file))
if there's no need of creating an object of a class, then there's no issue in creating all method as static of that class, but i wanna know what you are doing with a class fullof static methods.
I'm not quite sure what you meant by entrance method but if you're talking about something like this:
MyMethod myMethod = new MyMethod();
myMethod.doSomething(1);
public class MyMethod {
public String doSomething(int a) {
String p1 = MyMethod.functionA(a);
String p2 = MyMethod.functionB(p1);
return p1 + P2;
}
public static String functionA(...) {...}
public static String functionB(...) {...}
}
That's not advisable.
I think using all static methods/singletons a good way to code your business logic when you don't have to persist anything in the class. I tend to use it over singletons but that's simply a preference.
MyClass.myStaticMethod(....);
as opposed to:
MyClass.getInstance().mySingletonMethod(...);
All static methods/singletons tend to use less memory as well but depending on how many users you have you may not even notice it.

Making Methods All Static in Class

I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in the class or make the class a singleton so that you don't have to use the keyword new for calling methods in this BL class.
I assume this is common and good practice? Basic OOP? I just want to see people's opinion on that.
I think basically he's saying since there's no state, no need for the methods to be instance methods.
I'm not sure about making it a singleton every time as an option in this case...is that some sort of pattern or good advice he's giving me?
Here's the class I'm talking about (please do not repost any of this code in this thread, this is private): http://www.elbalazo.net/post/class.txt
There is very little downside to calling new and constructing a class reference, especially if the class has no state. Allocations are fast in .NET, so I wouldn't use this alone as a justification for a class to be static.
Typically, I feel a class should be made static if the class has no specific context - if you're using the class just as a placeholder for "utility" methods or non-context specific operations, then it makes sense to be a static class.
If that class has a specific need for context, and a meaning in a concrete sense, then it probably does not justify being static, even if it has no state (although this is rare). There are times where the class purpose is defined by its reference itself, which provides "state" of a sort (the reference itself) without any local variables.
That being said, there is a big difference between a static class and a singleton. A singleton is a different animal - you want to use it when you need an instance, but only one instance, of the class to be created. There is state in a singleton, but you are using this pattern to enforce that there is only a single copy of the state. This has a very different meaning, and I would highly recommend avoiding using a singleton just to prevent needing to "call new".
There's no absolute rule for when a class should be static. It may have no state, but you may need it for reference equality or locking. Classes should be static when their purpose fits it being implemented as a static class. You shouldn't follow hard-and-fast rules in these situations; use what you 'feel' is right.
Having no state makes it a candidate for static-ness, but look at what it's being used for before arbitarily refactoring it.
A lack of state alone is no reason to make methods static. There are plenty of cases where a stateless class should still have instance methods. For example, any time you need to pass specific implementations of some logic between routines, it's much easier to do it with classes that have instance methods, as it allows us to use interfaces:
interface IConnectionProvider
{
object GetConnectedObject();
}
We could have a dozen implementations of the above, and pass them into routines that require an IConnectionProvider. In that case, static is a very clumsy alternative.
There's nothing wrong with having to use new to use a method in a stateless class.
As long as you don't need to create any abstraction from your class then static methods are fine. If your class needs to be mocked or implement any sort of interface then you're better off making the class a singleton, since you cannot mock static methods on classes. You can have a singleton implement an interface and can inherit instance methods from a singleton whereas you cannot inherit static methods.
We generally use singletons instead of static methods to allow our classes to be abstracted easily. This has helped in unit testing many times since we've run into scenarios where we wanted to mock something and could easily do so since the behavior was implemented as instance methods on a singleton.
Utility classes are often composed of independant methods that don't need state. In that case it is good practice to make those method static. You can as well make the class static, so it can't be instantiated.
With C# 3, you can also take advantage of extension methods, that will extend other classes with those methods. Note that in that case, making the class static is required.
public static class MathUtil
{
public static float Clamp(this float value, float min, float max)
{
return Math.Min(max, Math.Max(min, value));
}
}
Usage:
float f = ...;
f.Clamp(0,1);
I can think of lots of reasons for a non-static class with no members. For one, it may implement an interface and provide/augment behavior of another. For two, it may have virtual or abstract methods that allow customization. Basically using 'static' methods is procedural programming at it's worst and is contrary to object-oriented design.
Having said that, often small utilities routines are best done with a procedural implementation so don't shy away if it make sense. Consider String.IsNullOrEmpty() a great example of a procedural static routine that provides benefit in not being a method. (the benefit is that it can also check to see if the string is null)
Another example on the other side of the fence would be a serialization routine. It doesn't need any members per-say. Suppose it has two methods Write(Stream,Object) and object Read(Stream). It's not required that this be an object and static methods could suffice; however, it make sense to be an object or interface. As an object I could override it's behavior, or later change it's implementation so that it cached information about the object types it serialized. By making it an object to begin with you do not limit yourself.
Most of the time it's OK to make the class static. But a better question is why do you have a class without state?
There are very rare instances where a stateless class is good design. But stateless classes break object oriented design. They are usually a throwback to functional decomposition (all the rage before object oriented techniques became popular). Before you make a class static, ask yourself whether the data that it is working on should be included int he class or whether all of the functionality in the utility class shouldn't be broken up between other classes that may or may not already exist.
Make sure that you have a good reason to make class static.
According to Framework Design Guidelines:
Static classes should be used only as
supporting classes for the
object-oriented core of the framework.
DO NOT treat static classes as a miscellaneous bucket.
There should be a clear charter for
the class.
Static Class, Static Methods and Singleton class are three different concepts. Static classes and static methods are usually used to implement strictly utility classes or making them stateless and hence thread-safe and conncurrently usable.
Static classes need not be Singletons. Singleton means there is only one instance of a class, which is otherwise instantiable. It is most often used to encapsulate the physical world representation of a truly single instance of a resource, such as a single database pool or a single printer.
Coming back to your colleague's suggestion -- I tend to agree it is a sound advice. There is no need to instantiate a class if the methods are made static, when they can be static. It makes the caller code more readable and the called methods more easily usable.
It sounds like you're talking about a strictly Utility class, in which case there's really no reason to have seperate instances.
Make those utility methods static. You can keep the class as a regular object if you'd like (to allow for the future addition of instance methods/state information).

what is the inconveniences of using static property or method in OO approach?

I need to explain myself why I do not use static methods/propertis. For example,
String s=String.Empty;
is this property (belongs to .Net framework) wrong? is should be like?
String s= new EmptySting();
or
IEmptyStringFactory factory=new EmptyStringFactory();
String s= factory.Create();
Why would you want to create a new object every time you want to use the empty string? Basically the empty string is a singleton object.
As Will says, statics can certainly be problematic when it comes to testing, but that doesn't mean you should use statics everywhere.
(Personally I prefer to use "" instead of string.Empty, but that's a discussion which has been done to death elsewhere.)
I think the worst thing about using statics is that you can end up with tight coupling between classes. See the ASP.NET before System.Web.Abstractions came out. This makes your classes harder to test and, possibly, more prone to bugs causing system-wide issues.
Well, in the case of String.Empty it is more of a constant (kind of like Math.PI or Math.E) and is defined for that type. Creating a sub-class for one specific value is typically bad.
On to your other (main) question as to how they are "inconvenient:"
I've only found static properties and methods to be inconvenient when they are abused to create a more functional solution instead of the object-oriented approach that is meant with C#.
Most of my static members are either constants like above or factory-like methods (like Int.TryParse).
If the class has a lot of static properties or methods that are used to define the "object" that is represented by the class, I would say that is typically bad design.
One major thing that does bother me with the static methods/properties is that you sometimes they are too tied to one way of doing something without providing an easy way to create an instance the provides with easy overrides to the behavior. For example, imagine that you want to do your mathematical computations in degrees instead of radians. Since Math is all static, you can't do that and instead have to convert each time. If Math were instance-based, you could create a new Math object that defaulted to radians or degrees as you wished and could still have a static property for the typical behaviors.
For example, I wish I could say this:
Math mD = new Math(AngleMode.Degrees); // ooooh, use one with degrees instead
double x = mD.Sin(angleInDegrees);
but instead I have to write this:
double x = Math.Sin(angleInDegrees * Math.PI / 180);
(of course, you can write extension methods and constants for the conversions, but you get my point).
This may not be the best example, but I hope it conveys the problem of not being able to use the methods with variations on the default. It creates a functional construct and breaks with the usual object-oriented approach.
(As a side note, in this example, I would have a static property for each mode. That in my eyes would be a decent use of the static properties).
The semantics of your three different examples are very different. I'll try to break it down as I do it in practice.
String s=String.Empty;
This is a singleton. You would use this when you want to ensure that there's only ever one of something. In this case, since a string is immutable, there only ever needs to be one "empty" string. Don't overuse singletons, because they're hard to test. When they make sense, though, they're very powerful.
String s= new EmptySting();
This is your standard constructor. You should use this whenever possible. Refactor to the singleton pattern only when the case for a singleton is overwhelming. In the case of string.Empty, it very much makes sense to use singleton because the string's state cannot be changed by referring classes.
IEmptyStringFactory factory=new EmptyStringFactory();
String s= factory.Create();
Instance factories and static factories, like singletons, should be used sparingly. Mostly, they should be used when the construction of a class is complex and relies on multiple steps, and possibly state.
If the construction of an object relies on state that might not be known by the caller, then you should use instance factories (like in your example). When the construction is complex, but the caller knows the conditions that would affect construction, then you should use a static factory (such as StringFactory.CreateEmpty() or StringFactory.Create("foo"). In the case of a string, however, the construction is simple enough that using a factory would smell of a solution looking for a problem.
Generally, it is a bad idea to create a new empty string - this creates extra objects on the heap, so extra work for the garbage collector. You should always use String.Empty or "" when you want the empty string as those are references to existing objects.
In general, the purpose of a static is to make sure that there is ever only one instance of the static "thing" in your program.
Static fields maintain the same value throughout all instances of a type
Static methods and properties do not need an instance in order to be invoked
Static types may only contain static methods/properties/fields
Statics are useful when you know that the "thing" you are creating will never change through the lifetime of the program. In your example, System.String defines a private static field to store the empty string, which is allocated only once, and exposed through a static property.
As mentioned, there are testability issues with statics. For example, it is hard to mock static types since they can't be instantiated or derived from. It is also hard to introduce mocks into some static methods since the fields they use must also be static. (You can use a static setter property to get around this issue, but I personally try to avoid this as it usually breaks encapsulation).
For the most part, use of statics is o.k. You need to decide when to make the trade-off of using static and instance entities based on the complexity of your program.
In a purist OO approach, static methods break the OO paradigm because you're attaching actual data to the definition of data. A class is a definition of a set of objects that conform to semantics. Just like there are mathematical sets that contain one or zero elements, there can be classes that contain only one or zero possible states.
The way of sharing a common object and allowing multiple actors on its state is to pass a reference.
The main problem with static methods comes from, what if in the future you want two of them? We're writing computer programs, one would assume that if we can make one of something, we should be able to make two very simply, with statics this isn't the case. To change something from a static state to a normal instance state is a complete rewrite of the class in question.
I might assume I want to only ever use one SqlConnection pool, but now what if I want a high priority pool and a low priority pool. If the connection pool was instanced instead of static the solution would be simple, instead I have to couple pooling with connection instantiation. I better hope the library writer had forsight or else I have to reimplement the pooling.
Edit:
Static methods in single inheritance languages are a hack to provide reuse of code. Normally if there are methods one wanted to share common code between classes you could pull it in through multiple inheritance or a mixin. Single inheritance languages force you to call static methods; there's no way to use multiple abstract classes with state.
There are draw backs to using statics such as:
Statics dont allow extension methods.
Static constructor is called automatically to initialize the class before the first instance is created (depending on the static class being called of course)
Static class data lives throughout the lifespan of the execution scope, this wastes memory.
Reasons to use static methods
Statics are good for helper methods, as you dont want to create a local copy of a non-static class, just to calla single helper method.
Eeerm, static classes make the singleton pattern possible.
From a scenario-driven design, the criteria for choosing statics vs. instance methods should be: if a method can be called without an instance of a class to be created, make it static. Else, make it an instance method. First option makes the call a once line process, and avoid .ctor calls.
Another useful criteria here is whether responsabilities are in the right place. For ex. you got an Account class. Say you need functionality for currency conversion e.g. from dollars to euros. Do you make that a member of the Account class? account.ConvertTo(Currency.Euro)? Or do you create a different class that encapsulates that responsibility? CurrencyConverter.Convert(account, Currency.Euro)? To me, the latter is better in the sense that encapsulates responsibilities on a different class, while in the former I would be spreading currency conversion knowledge across different accounts.

Categories

Resources