Making Methods All Static in Class - c#

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

Related

Static abstract objects with virtual methods

I'm working on a personal project and I've run into an issue.
I have object a couple of objects that have the same properties, methods, etc. The only things that differ are their names, values of properties, and the implementation of the methods. They also need common default implementation of methods. So right away, an interface is out of the question.
So I created a base class with the properties and "default" methods. But this base class needs to be abstract. The methods are virtual so they can be overridden.
The reason I need them to be static is that objects will be properties of other objects.
So, for example, the objects referenced above are (for sake of simplicity) objX, objY, objZ. They are derived from their base, objW.
objContainer is a completely unrelated object, but it has a property of type objW, which is an instance of either objX, objY, objZ.
objX, objY, and objZ will never change. Their properties will all be readonly. So multiple objects of instance objContainer will have objX, objY, or objZ.
public class objContainer1
{
objW processor = new objY;
}
public class objContainer2
{
objW processor = new objY;
}
How do I go about doing this? I wanted to keep them static so I don't have multiple instances of the same objects, when all of them are the exact same, really.
Do I use a singleton? Factory pattern?
I'm lost as to which direction to go with this (if any). Maybe I'm overthinking it and there's a very simple solution/
You want to use static classes sparingly. There are obvious downsides to static classes, such as the inability to take advantage of the polymorphic nature of class inheritance since you can't inherit from a static class. The only time you want to use a static class, really, is when you have something like a set of related tools that you want to make available across your application and for which you don't need to maintain any state. Think of the System.Math class, for example: a set of math functions that you can use anywhere in your application. Having an instance of that class doesn't really make any sense, and it would be rather cumbersome and unnecessary.
I would suggest sticking to non-static classes and creating instances of those classes. If you should only ever have one instance of your class, then you should use a singleton, as you suggested.

Whether to use static class or not [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.

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.

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.

Static classes in 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.

Categories

Resources